// Command palette — fuzzy search across nav + actions
const { useState: useStateK, useEffect: useEffectK, useRef: useRefK, useMemo: useMemoK } = React;

const CMDK_ACTIONS = [
  { id: 'go-discovery',   label: 'Go to Discovery',     section: 'Navigate', icon: 'Discovery',    ctx: 'G then D'},
  { id: 'go-jobs',        label: 'Go to Agent Jobs',    section: 'Navigate', icon: 'Jobs',         ctx: 'G then J'},
  { id: 'go-integrations',label: 'Go to Integrations',  section: 'Navigate', icon: 'Integrations', ctx: 'G then I'},
  { id: 'go-data',        label: 'Go to Data',          section: 'Navigate', icon: 'Data',         ctx: 'G then A'},
  { id: 'go-rules',       label: 'Go to Business Rules',section: 'Navigate', icon: 'Rules',        ctx: 'G then R'},

  { id: 'new-job',        label: 'New agent job',       section: 'Create',   icon: 'Plus',         ctx: 'C then J'},
  { id: 'new-rule',       label: 'New business rule',   section: 'Create',   icon: 'Plus',         ctx: 'C then R'},
  { id: 'new-integration',label: 'Connect integration', section: 'Create',   icon: 'Plus',         ctx: 'C then I'},

  { id: 'toggle-sidebar', label: 'Toggle sidebar',      section: 'Workspace',icon: 'Sidebar',      ctx: '⌘\\'},
  { id: 'settings',       label: 'Open settings',       section: 'Workspace',icon: 'Cog',          ctx: '⌘,'},
  { id: 'theme',          label: 'Switch theme',        section: 'Workspace',icon: 'Theme',        ctx: ''},
  { id: 'help',           label: 'Help & shortcuts',    section: 'Workspace',icon: 'Help',         ctx: '?'},

  { id: 'switch-membrane',label: 'Switch to Membrane Agency', section: 'Switch workspace', icon: 'Building', ctx: ''},
  { id: 'switch-sandbox', label: 'Switch to Membrane Sandbox',section: 'Switch workspace', icon: 'Building', ctx: ''},
  { id: 'switch-acme',    label: 'Switch to Acme Talent Co.', section: 'Switch workspace', icon: 'Building', ctx: ''},
];

function CmdK({ open, onClose, onAction }) {
  const [q, setQ] = useStateK('');
  const [active, setActive] = useStateK(0);
  const inputRef = useRefK(null);
  const listRef = useRefK(null);

  useEffectK(() => {
    if (open) {
      setQ('');
      setActive(0);
      setTimeout(() => inputRef.current?.focus(), 10);
    }
  }, [open]);

  const results = useMemoK(() => {
    const term = q.trim().toLowerCase();
    if (!term) return CMDK_ACTIONS;
    return CMDK_ACTIONS.filter(a => a.label.toLowerCase().includes(term) || a.section.toLowerCase().includes(term));
  }, [q]);

  // Group by section preserving result order
  const groups = useMemoK(() => {
    const out = [];
    const seen = new Map();
    results.forEach(r => {
      if (!seen.has(r.section)) { seen.set(r.section, out.length); out.push({ section: r.section, items: [] }); }
      out[seen.get(r.section)].items.push(r);
    });
    return out;
  }, [results]);

  // Flat ordered list for keyboard nav
  const flat = useMemoK(() => groups.flatMap(g => g.items), [groups]);

  useEffectK(() => { setActive(0); }, [q]);

  const handleKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(a + 1, flat.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); }
    else if (e.key === 'Enter' && flat[active]) { e.preventDefault(); onAction(flat[active]); }
    else if (e.key === 'Escape') { e.preventDefault(); onClose(); }
  };

  return (
    <div className="cmdk-overlay" data-open={open} onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="cmdk" onMouseDown={(e) => e.stopPropagation()}>
        <div className="cmdk-input-wrap">
          <span className="cmdk-search-icon"><Icons.Search size={16}/></span>
          <input
            ref={inputRef}
            className="cmdk-input"
            placeholder="Type a command or search…"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={handleKey}
          />
        </div>
        <div className="cmdk-list" ref={listRef}>
          {flat.length === 0 && <div className="cmdk-empty">No matches for "{q}"</div>}
          {groups.map(g => (
            <div key={g.section}>
              <div className="cmdk-section-label">{g.section}</div>
              {g.items.map(item => {
                const Ico = Icons[item.icon] || Icons.Plus;
                const idx = flat.indexOf(item);
                return (
                  <button
                    key={item.id}
                    className="cmdk-item"
                    data-active={idx === active}
                    onMouseEnter={() => setActive(idx)}
                    onClick={() => onAction(item)}
                  >
                    <Ico size={15} className="icon"/>
                    <span>{item.label}</span>
                    {item.ctx && <span className="ctx">{item.ctx}</span>}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
        <div className="cmdk-footer">
          <span><span className="kbd-key">↑</span><span className="kbd-key">↓</span> navigate</span>
          <span><span className="kbd-key">↵</span> select</span>
          <span><span className="kbd-key">esc</span> dismiss</span>
          <span style={{marginLeft:'auto'}}>Membrane ⌘K</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CmdK });
