// admin-panel.jsx — Admin settings modal (ADMIN role only)

function AdminPanel({ currentUser, onClose }) {
  const [users, setUsers]       = React.useState([]);
  const [loading, setLoading]   = React.useState(true);
  const [saving, setSaving]     = React.useState({});   // uid → bool
  const [error, setError]       = React.useState(null);
  const [needsRules, setNeedsRules] = React.useState(false);
  const overlayRef = React.useRef(null);

  const RULES_URL = 'https://console.firebase.google.com/project/kcgmatch-228f2/firestore/rules';

  const RULES_TEXT = `rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    function isAdmin() {
      return request.auth != null
          && exists(/databases/$(database)/documents/users/$(request.auth.uid))
          && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'ADMIN';
    }

    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
      allow read, write: if isAdmin();
    }

    match /users/{userId}/{rest=**} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
      allow read, write: if isAdmin();
    }

  }
}`;

  // Load all registered users from Firestore
  React.useEffect(() => {
    fbDb.collection('users').get()
      .then((snap) => {
        const docs = snap.docs.map((d) => ({ uid: d.id, ...d.data() }));
        // Sort: current user first, then alphabetically by name/email
        docs.sort((a, b) => {
          if (a.uid === currentUser.uid) return -1;
          if (b.uid === currentUser.uid) return  1;
          const na = a.displayName || a.email || a.uid;
          const nb = b.displayName || b.email || b.uid;
          return na.localeCompare(nb);
        });
        setUsers(docs);
        setLoading(false);
      })
      .catch(() => {
        setNeedsRules(true);
        setLoading(false);
      });
  }, [currentUser.uid]);

  const handleRoleChange = async (uid, role) => {
    setSaving((p) => ({ ...p, [uid]: true }));
    setError(null);
    try {
      await fbDb.collection('users').doc(uid).set({ role: role || null }, { merge: true });
      setUsers((prev) => prev.map((u) => u.uid === uid ? { ...u, role: role || null } : u));
    } catch (e) {
      setError('Failed to save role: ' + e.message);
    } finally {
      setSaving((p) => ({ ...p, [uid]: false }));
    }
  };

  // Close on overlay click
  const handleOverlayClick = (e) => {
    if (e.target === overlayRef.current) onClose();
  };

  // Close on Escape
  React.useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [onClose]);

  const initials = (u) => {
    const name = u.displayName || u.email || '?';
    return name.slice(0, 2).toUpperCase();
  };

  return (
    <div className="adm-overlay" ref={overlayRef} onClick={handleOverlayClick}>
      <div className="adm-panel" role="dialog" aria-modal="true" aria-label="Admin Settings">

        {/* Header */}
        <div className="adm-hd">
          <div>
            <div className="adm-eyebrow mono">ADMIN</div>
            <h2 className="adm-title">Settings</h2>
          </div>
          <button className="btn btn-ghost btn-sm adm-close" onClick={onClose}>
            <Icon name="x" size={14} />
          </button>
        </div>

        {/* User Management */}
        <div className="adm-section">
          <div className="adm-section-label">User Management</div>
          <div className="adm-section-sub">
            Assign roles to control what each user can approve and access.
            Changes take effect immediately on the user's next action.
          </div>

          {error && (
            <div className="adm-error">
              <Icon name="flag" size={13} /> {error}
            </div>
          )}

          {needsRules ? (
            <div className="adm-rules-needed">
              <div className="adm-rules-hd">
                <Icon name="flag" size={14} />
                Firestore rules update required
              </div>
              <p className="adm-rules-p">
                Your current rules only let users read their own document.
                To let the admin list all users, paste the rules below into the
                Firebase console, then reload this panel.
              </p>
              <div className="adm-rules-steps">
                <div className="adm-step">
                  <span className="adm-step-n">1</span>
                  <a className="adm-console-link" href={RULES_URL} target="_blank" rel="noreferrer">
                    Open Firebase Console → Firestore → Rules
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{marginLeft:4}}><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
                  </a>
                </div>
                <div className="adm-step">
                  <span className="adm-step-n">2</span>
                  <span>Replace the rules editor content with the block below and click <strong>Publish</strong></span>
                </div>
                <div className="adm-step">
                  <span className="adm-step-n">3</span>
                  <span>Close and reopen this panel — users will load</span>
                </div>
              </div>
              <div className="adm-rules-code-wrap">
                <button className="adm-copy-btn" onClick={() => {
                  navigator.clipboard.writeText(RULES_TEXT).catch(() => {});
                }}>
                  Copy
                </button>
                <pre className="adm-rules-code">{RULES_TEXT}</pre>
              </div>
            </div>
          ) : loading ? (
            <div className="adm-loading-wrap">
              <div className="adm-spin" />
              <span>Loading users…</span>
            </div>
          ) : users.length === 0 ? (
            <div className="adm-empty">No users found in Firestore.</div>
          ) : (
            <div className="adm-user-list">
              {/* Column headers */}
              <div className="adm-col-hd">
                <span className="adm-col-user">User</span>
                <span className="adm-col-role">Role</span>
              </div>

              {users.map((u) => {
                const isSelf = u.uid === currentUser.uid;
                const displayName = u.displayName || u.email?.split('@')[0] || 'Unknown';
                const email = u.email || u.uid;
                return (
                  <div key={u.uid} className={`adm-user-row${isSelf ? ' adm-self' : ''}`}>
                    <div className="adm-avatar" data-role={u.role || 'none'}>
                      {initials(u)}
                    </div>
                    <div className="adm-user-info">
                      <div className="adm-user-name">
                        {displayName}
                        {isSelf && <span className="adm-you">You</span>}
                      </div>
                      <div className="adm-user-email">{email}</div>
                    </div>
                    <div className="adm-role-cell">
                      {saving[u.uid] ? (
                        <div className="adm-row-spin" />
                      ) : null}
                      <select
                        className={`select adm-role-select${saving[u.uid] ? ' adm-role-saving' : ''}`}
                        value={u.role || ''}
                        disabled={!!saving[u.uid]}
                        onChange={(e) => handleRoleChange(u.uid, e.target.value)}
                      >
                        <option value="">— No role —</option>
                        {ROLES.map((r) => (
                          <option key={r} value={r}>{ROLE_LABEL[r] || r}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Role reference */}
        <div className="adm-section adm-section-ref">
          <div className="adm-section-label">Role Permissions</div>
          <div className="adm-role-ref">
            {[
              { role: 'ESTIMATOR',       desc: 'View jobs and upload quotes/invoices' },
              { role: 'PROJECT_MANAGER', desc: 'All above + approve invoices up to $5,000' },
              { role: 'ACCOUNTING',      desc: 'All above + approve invoices up to $25,000' },
              { role: 'EXECUTIVE',       desc: 'All above + approve any invoice amount' },
              { role: 'ADMIN',           desc: 'Full access including user management' },
            ].map(({ role, desc }) => (
              <div key={role} className="adm-ref-row">
                <span className="adm-ref-role">{ROLE_LABEL[role] || role}</span>
                <span className="adm-ref-desc">{desc}</span>
              </div>
            ))}
          </div>
        </div>

      </div>
      <AdminPanelStyles />
    </div>
  );
}

const AdminPanelStyles = () => (
  <style>{`
    /* ── Overlay ────────────────────────────────────────────────── */
    .adm-overlay {
      position: fixed; inset: 0; z-index: 500;
      background: oklch(0 0 0 / 0.5);
      display: flex; align-items: center; justify-content: center;
      padding: 24px;
      animation: adm-fade-in .15s ease;
    }
    @keyframes adm-fade-in { from { opacity: 0; } to { opacity: 1; } }

    /* ── Panel ──────────────────────────────────────────────────── */
    .adm-panel {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--r-lg); box-shadow: var(--shadow-2);
      width: 100%; max-width: 580px; max-height: 85vh;
      display: flex; flex-direction: column;
      animation: adm-slide-in .18s cubic-bezier(.3,.7,.4,1);
      overflow: hidden;
    }
    @keyframes adm-slide-in { from { transform: translateY(12px); opacity: 0; } to { transform: none; opacity: 1; } }

    /* ── Header ─────────────────────────────────────────────────── */
    .adm-hd {
      display: flex; align-items: flex-start; justify-content: space-between;
      padding: 22px 24px 16px; border-bottom: 1px solid var(--border);
      flex-shrink: 0;
    }
    .adm-eyebrow { font-size: 10px; letter-spacing: 0.14em; color: var(--fg-dim); margin-bottom: 4px; }
    .adm-title { margin: 0; font-size: 20px; font-weight: 600; letter-spacing: -0.015em; }
    .adm-close { margin-top: 2px; }

    /* ── Sections ───────────────────────────────────────────────── */
    .adm-section {
      padding: 20px 24px;
      border-bottom: 1px solid var(--border);
      overflow-y: auto;
    }
    .adm-section:last-child { border-bottom: none; }
    .adm-section-ref { flex-shrink: 0; }
    .adm-section-label {
      font-size: 12px; font-weight: 600; letter-spacing: 0.03em;
      text-transform: uppercase; color: var(--fg-dim); margin-bottom: 6px;
    }
    .adm-section-sub {
      font-size: 12.5px; color: var(--fg-muted); line-height: 1.55;
      margin-bottom: 16px;
    }

    /* ── Error ──────────────────────────────────────────────────── */
    .adm-error {
      display: flex; align-items: center; gap: 8px;
      background: var(--bad-bg); border: 1px solid oklch(from var(--bad) l calc(c*.5) h / .4);
      color: var(--bad); border-radius: var(--r); padding: 9px 12px;
      font-size: 12.5px; line-height: 1.5; margin-bottom: 14px;
    }

    /* ── Loading ────────────────────────────────────────────────── */
    .adm-loading-wrap {
      display: flex; align-items: center; gap: 10px;
      color: var(--fg-dim); font-size: 13px; padding: 16px 0;
    }
    .adm-spin, .adm-row-spin {
      width: 18px; height: 18px; border-radius: 50%; flex-shrink: 0;
      border: 2px solid var(--border); border-top-color: var(--accent);
      animation: adm-sp .65s linear infinite;
    }
    .adm-row-spin { width: 14px; height: 14px; }
    @keyframes adm-sp { to { transform: rotate(360deg); } }
    .adm-empty { font-size: 13px; color: var(--fg-dim); padding: 8px 0; }

    /* ── Column headers ─────────────────────────────────────────── */
    .adm-col-hd {
      display: flex; align-items: center;
      padding: 0 0 8px; border-bottom: 1px solid var(--border);
      margin-bottom: 4px;
      font-size: 10.5px; font-weight: 600; text-transform: uppercase;
      letter-spacing: 0.06em; color: var(--fg-dim);
    }
    .adm-col-user { flex: 1; }
    .adm-col-role { width: 168px; text-align: right; padding-right: 2px; }

    /* ── User rows ──────────────────────────────────────────────── */
    .adm-user-list { display: flex; flex-direction: column; }
    .adm-user-row {
      display: flex; align-items: center; gap: 12px;
      padding: 10px 0; border-bottom: 1px solid var(--border);
    }
    .adm-user-row:last-child { border-bottom: none; }
    .adm-self { background: oklch(from var(--accent) l c h / 0.03); border-radius: var(--r); padding-left: 8px; padding-right: 8px; margin-left: -8px; margin-right: -8px; }

    .adm-avatar {
      width: 34px; height: 34px; border-radius: 50%; flex-shrink: 0;
      display: grid; place-items: center;
      font-size: 12px; font-weight: 700; letter-spacing: 0.01em;
      background: oklch(from var(--accent) l c h / 0.18);
      color: var(--accent); border: 1px solid oklch(from var(--accent) l c h / 0.3);
    }
    .adm-avatar[data-role="ADMIN"]           { background: oklch(from var(--bad)  l c h / 0.15); color: var(--bad);  border-color: oklch(from var(--bad)  l c h / 0.3); }
    .adm-avatar[data-role="EXECUTIVE"]       { background: oklch(from var(--warn) l c h / 0.15); color: var(--warn); border-color: oklch(from var(--warn) l c h / 0.3); }
    .adm-avatar[data-role="ACCOUNTING"]      { background: oklch(from var(--info) l c h / 0.15); color: var(--info); border-color: oklch(from var(--info) l c h / 0.3); }
    .adm-avatar[data-role="PROJECT_MANAGER"] { background: oklch(from var(--ok)   l c h / 0.15); color: var(--ok);   border-color: oklch(from var(--ok)   l c h / 0.3); }
    .adm-avatar[data-role="none"]            { background: var(--surface-2); color: var(--fg-dim); border-color: var(--border); }

    .adm-user-info { flex: 1; min-width: 0; }
    .adm-user-name {
      font-size: 13px; font-weight: 500; color: var(--fg);
      display: flex; align-items: center; gap: 7px;
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }
    .adm-user-email { font-size: 11.5px; color: var(--fg-dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .adm-you {
      font-size: 9.5px; padding: 1px 6px; border-radius: 999px;
      background: oklch(from var(--accent) l c h / 0.15);
      color: var(--accent); border: 1px solid oklch(from var(--accent) l c h / 0.3);
      font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; flex-shrink: 0;
    }

    .adm-role-cell {
      display: flex; align-items: center; gap: 8px; flex-shrink: 0; width: 168px; justify-content: flex-end;
    }
    .adm-role-select { font-size: 12.5px; padding: 5px 8px; width: 152px; }
    .adm-role-saving { opacity: 0.5; }

    /* ── Rules needed state ─────────────────────────────────────── */
    .adm-rules-needed {
      border: 1px solid oklch(from var(--warn) l calc(c*.5) h / .45);
      background: oklch(from var(--warn) l c h / 0.05);
      border-radius: var(--r-lg); padding: 16px 18px;
    }
    .adm-rules-hd {
      display: flex; align-items: center; gap: 8px;
      font-size: 13.5px; font-weight: 600; color: var(--warn);
      margin-bottom: 10px;
    }
    .adm-rules-p {
      margin: 0 0 14px; font-size: 12.5px; color: var(--fg-muted); line-height: 1.6;
    }
    .adm-rules-steps {
      display: flex; flex-direction: column; gap: 8px; margin-bottom: 14px;
    }
    .adm-step {
      display: flex; align-items: flex-start; gap: 10px; font-size: 12.5px; color: var(--fg-muted);
    }
    .adm-step-n {
      width: 20px; height: 20px; border-radius: 50%; flex-shrink: 0;
      background: var(--surface-3); border: 1px solid var(--border);
      display: grid; place-items: center;
      font-size: 11px; font-weight: 700; color: var(--fg-dim);
    }
    .adm-console-link {
      color: var(--accent); text-decoration: none; font-weight: 500;
      display: inline-flex; align-items: center;
    }
    .adm-console-link:hover { text-decoration: underline; }
    .adm-rules-code-wrap {
      position: relative;
    }
    .adm-copy-btn {
      position: absolute; top: 8px; right: 8px;
      appearance: none; border: 1px solid var(--border);
      background: var(--surface-2); border-radius: var(--r);
      padding: 3px 10px; font: inherit; font-size: 11px; font-weight: 500;
      color: var(--fg-muted); cursor: pointer;
      transition: background .12s, color .12s;
    }
    .adm-copy-btn:hover { background: var(--surface-3); color: var(--fg); }
    .adm-rules-code {
      display: block; margin: 0;
      background: var(--surface-2); border: 1px solid var(--border);
      border-radius: var(--r); padding: 12px 14px;
      font-family: 'Courier New', monospace; font-size: 11px;
      line-height: 1.6; color: var(--fg-muted);
      overflow-x: auto; white-space: pre;
    }

    /* ── Role reference table ───────────────────────────────────── */
    .adm-role-ref { display: flex; flex-direction: column; gap: 6px; }
    .adm-ref-row { display: flex; align-items: baseline; gap: 12px; font-size: 12.5px; }
    .adm-ref-role {
      font-size: 11px; padding: 1px 8px; border-radius: 999px;
      background: var(--surface-2); color: var(--fg-dim);
      border: 1px solid var(--border); font-weight: 500;
      white-space: nowrap; flex-shrink: 0; min-width: 112px; text-align: center;
    }
    .adm-ref-desc { color: var(--fg-muted); line-height: 1.4; }
  `}</style>
);

Object.assign(window, { AdminPanel });
