// Command palette — ⌘K / Ctrl+K. Unified finder and action launcher.

function GMCommandPalette({ open, onClose, nav, customer, persona, onNav, onChangePersona, onToggleTheme, onExitWorkspace, pushToast }) {
  const [query, setQuery] = React.useState('');
  const [active, setActive] = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setQuery(''); setActive(0);
      setTimeout(() => inputRef.current?.focus(), 40);
    }
  }, [open]);

  const commands = React.useMemo(() => {
    const base = [
      ...nav.map(n => ({ id: `nav-${n.id}`, group: 'Navigate', title: n.label, sub: `Go to ${n.label}`, icon: n.icon, run: () => { onNav(n.id); onClose(); } })),
      { id: 'cmd-approve',   group: 'Guardian AI', title: 'Approve all low-risk onboarding',   sub: '5 matching contractors',        icon: 'sparkle',
        run: () => { pushToast({ title: 'Guardian approved 5 contractors', sub: 'Matched your previous approvals', kind: 'ai' }); onClose(); } },
      { id: 'cmd-bulk',      group: 'Guardian AI', title: 'Revoke expired credentials',        sub: '3 credentials past end-date',    icon: 'bolt',
        run: () => { pushToast({ title: 'Guardian revoked 3 credentials', sub: 'Audit log updated', kind: 'ai' }); onClose(); } },
      { id: 'cmd-invite',    group: 'Actions', title: 'Invite cardholder',                     sub: 'Start an invitation flow',       icon: 'plus',
        run: () => { pushToast({ title: 'Cardholder invite flow', sub: 'Opens inviter (mock)', kind: 'system' }); onClose(); } },
      { id: 'cmd-export',    group: 'Actions', title: 'Export cardholder CSV',                  sub: 'Current filter',                  icon: 'export',
        run: () => { pushToast({ title: 'Export started', sub: 'CSV will download when ready', kind: 'system' }); onClose(); } },
    ];
    const personas = Object.values(window.GM_PERSONAS).map(p => ({
      id: `persona-${p.id}`, group: 'Persona',
      title: `Switch to ${p.label}`,
      sub: p.desc,
      icon: 'swap',
      run: () => { onChangePersona(p.id); onClose(); },
    }));
    const other = [
      { id: 'cmd-theme',     group: 'Appearance', title: 'Toggle dark mode',                  sub: 'Personal preference',            icon: 'moon',
        run: () => { onToggleTheme(); onClose(); } },
      { id: 'cmd-exit',      group: 'Workspace',  title: 'Exit to partner portal',             sub: 'Return to Acme Identity Partners', icon: 'arrowLeft',
        run: () => { onExitWorkspace(); onClose(); } },
    ];
    return [...base, ...personas, ...other];
  }, [nav, onNav, onChangePersona, onToggleTheme, onExitWorkspace, pushToast, onClose]);

  const filtered = query
    ? commands.filter(c => (c.title + ' ' + (c.sub || '') + ' ' + c.group).toLowerCase().includes(query.toLowerCase()))
    : commands;

  const grouped = filtered.reduce((acc, c) => {
    (acc[c.group] = acc[c.group] || []).push(c);
    return acc;
  }, {});

  const onKey = (e) => {
    if (e.key === 'Escape') { onClose(); return; }
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(a + 1, filtered.length - 1)); return; }
    if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); return; }
    if (e.key === 'Enter') { e.preventDefault(); filtered[active]?.run(); return; }
  };

  if (!open) return null;

  let idx = -1;
  return (
    <div className="cp-backdrop" onClick={onClose}>
      <div className="cp" onClick={e => e.stopPropagation()}>
        <div className="cp-input-row">
          <GMI.search/>
          <input
            ref={inputRef}
            className="cp-input"
            value={query}
            onChange={e => { setQuery(e.target.value); setActive(0); }}
            onKeyDown={onKey}
            placeholder="Jump to, ask Guardian, or run a command…"
          />
          <span className="cp-kbd">Esc</span>
        </div>
        <div className="cp-results">
          {filtered.length === 0 && (
            <div style={{ padding: 24, textAlign: 'center', fontSize: 13, color: 'var(--ink-3)' }}>
              No matches. Try <em>cardholders</em>, <em>switch persona</em>, or <em>approve</em>.
            </div>
          )}
          {Object.entries(grouped).map(([g, items]) => (
            <div key={g}>
              <div className="cp-group-label">{g}</div>
              {items.map(c => {
                idx++;
                const myIdx = idx;
                const Icon = GMI[c.icon] || GMI.arrowRight;
                return (
                  <button
                    key={c.id}
                    className={`cp-item ${myIdx === active ? 'is-active' : ''}`}
                    onMouseEnter={() => setActive(myIdx)}
                    onClick={c.run}
                  >
                    <div className="cp-item-icon"><Icon/></div>
                    <div className="cp-item-body">
                      <div className="cp-item-title">{c.title}</div>
                      {c.sub && <div className="cp-item-sub">{c.sub}</div>}
                    </div>
                    <GMI.arrowRight style={{ width: 12, height: 12, color: 'var(--ink-3)' }}/>
                  </button>
                );
              })}
            </div>
          ))}
        </div>
        <div className="cp-footer">
          <span className="cp-footer-legend">
            <span><span className="cp-kbd">↑↓</span> navigate</span>
            <span><span className="cp-kbd">↵</span> select</span>
            <span><span className="cp-kbd">Esc</span> close</span>
          </span>
          <span>Guardian Mesh · prototype</span>
        </div>
      </div>
    </div>
  );
}

window.GMCommandPalette = GMCommandPalette;
