/* @jsx React.createElement */
const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC, useRef: useRefC } = React;

const CMD_ITEMS = [
  { group: 'NAVIGATE', icon: '§', label: 'Home',                 meta: '/',              href: 'index.html' },
  { group: 'NAVIGATE', icon: '§', label: 'Doctrine',             meta: '/DOCTRINE',      href: 'doctrine.html' },
  { group: 'NAVIGATE', icon: '§', label: 'All episodes',         meta: '/EPISODES',      href: 'episodes.html' },
  { group: 'NAVIGATE', icon: '§', label: 'AAR ledger',           meta: '/AARS',          href: 'aars.html' },
  { group: 'NAVIGATE', icon: '§', label: 'About the team',       meta: '/ABOUT',         href: 'about.html' },
  { group: 'NAVIGATE', icon: '§', label: 'Support on Patreon',   meta: 'PATREON',        href: 'https://www.patreon.com/cw/VolunteerC2' },
  { group: 'EPISODES', icon: 'EP', label: "Commander's intent, and why your fleet keeps splitting at jump", meta: 'EP 014', href: 'episodes.html' },
  { group: 'EPISODES', icon: 'EP', label: 'The first nine minutes: what we changed before sortie 2',       meta: 'EP 013', href: 'episodes.html' },
  { group: 'EPISODES', icon: 'EP', label: 'Fuel, ammo, and patience: why your wing is on the ramp',         meta: 'EP 012', href: 'episodes.html' },
  { group: 'EPISODES', icon: 'EP', label: "You don't have a strategy problem — you have a sensing problem",  meta: 'EP 011', href: 'episodes.html' },
  { group: 'ACTIONS',  icon: '→', label: 'Support on Patreon',     meta: 'PATREON', href: 'https://www.patreon.com/cw/VolunteerC2' },
  { group: 'ACTIONS',  icon: '→', label: 'Subscribe to free brief', meta: 'EMAIL',   href: 'index.html#subscribe' },
  { group: 'ACTIONS',  icon: '→', label: 'Copy callsign — VC2',    meta: 'COPY',    href: null },
];

function CommandPalette({ open, onClose }) {
  const [q, setQ] = useStateC('');
  const [idx, setIdx] = useStateC(0);
  const inputRef = useRefC();

  useEffectC(() => {
    if (open) {
      setQ(''); setIdx(0);
      setTimeout(() => inputRef.current && inputRef.current.focus(), 30);
    }
  }, [open]);

  const items = useMemoC(() => {
    const t = q.trim().toLowerCase();
    if (!t) return CMD_ITEMS;
    return CMD_ITEMS.filter(it =>
      it.label.toLowerCase().includes(t) ||
      it.meta.toLowerCase().includes(t) ||
      it.group.toLowerCase().includes(t)
    );
  }, [q]);

  useEffectC(() => { setIdx(0); }, [q]);

  useEffectC(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') { e.preventDefault(); onClose(); }
      else if (e.key === 'ArrowDown') { e.preventDefault(); setIdx(i => Math.min(i + 1, items.length - 1)); }
      else if (e.key === 'ArrowUp')   { e.preventDefault(); setIdx(i => Math.max(i - 1, 0)); }
      else if (e.key === 'Enter') {
        e.preventDefault();
        const it = items[idx];
        if (it && it.href) { window.location.href = it.href; }
        onClose();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, idx, items, onClose]);

  if (!open) return null;

  // group by group, preserving order
  const groups = [];
  const seen = {};
  for (const it of items) {
    if (!seen[it.group]) { seen[it.group] = []; groups.push([it.group, seen[it.group]]); }
    seen[it.group].push(it);
  }

  let runningIdx = -1;
  return (
    <div className="vc-cmd-overlay" onClick={onClose}>
      <div className="vc-cmd" onClick={e => e.stopPropagation()}>
        <div className="vc-cmd__head">
          <span className="vc-cmd__prompt">VC2 //</span>
          <input
            ref={inputRef}
            className="vc-cmd__input"
            placeholder="navigate, search episodes, run actions…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
          <span className="vc-cmd__esc">ESC</span>
        </div>
        <div className="vc-cmd__list">
          {items.length === 0 && <div className="vc-cmd__empty">// NO MATCH FOR "{q}"</div>}
          {groups.map(([gname, gitems]) => (
            <React.Fragment key={gname}>
              <div className="vc-cmd__group">§ {gname}</div>
              {gitems.map(it => {
                runningIdx++;
                const active = runningIdx === idx;
                const myIdx = runningIdx;
                return (
                  <div
                    key={it.label}
                    className={"vc-cmd__item" + (active ? " is-active" : "")}
                    onMouseEnter={() => setIdx(myIdx)}
                    onClick={() => { if (it.href) window.location.href = it.href; onClose(); }}
                  >
                    <span className="vc-cmd__item-icon">{it.icon}</span>
                    <span>{it.label}</span>
                    <span className="vc-cmd__item-meta">{it.meta}</span>
                  </div>
                );
              })}
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
}
window.CommandPalette = CommandPalette;
