// ViG Command Center — ⌘K global command palette (search + navigate everything)
const { useState: useStateCK, useEffect: useEffectCK, useMemo: useMemoCK, useRef: useRefCK } = React;

const CK_TYPE_META = {
  Page: { color: '#FF6B00', icon: 'grid' },
  Calculator: { color: '#2563eb', icon: 'bolt' },
  General: { color: '#16a34a', icon: 'database' },
  Dragon: { color: '#9333ea', icon: 'flame' },
  Covenant: { color: '#ca8a04', icon: 'link' },
  Guide: { color: '#0891b2', icon: 'book' },
};

function buildCommandIndex(nav) {
  const items = [];
  (nav || []).forEach(sec => sec.items.forEach(it => {
    if (it.admin) return;
    items.push({ type: 'Page', label: it.label, meta: sec.section, page: it.id, icon: it.icon, kw: it.label + ' ' + sec.section });
    (it.children || []).forEach(c => {
      const clean = c.label.replace(/^[^A-Za-z]+/, '').trim();
      items.push({ type: 'Calculator', label: clean, meta: 'Calculator', sub: c.sub, page: c.page || 'tools', kw: clean + ' calculator' });
    });
  }));
  const V = window.VIG || {};
  (V.generals || []).forEach(g => items.push({ type: 'General', label: g.name, meta: g.type + ' · #' + g.rank, page: 'generals', search: g.name, kw: g.name + ' ' + g.type }));
  (V.dragons || []).forEach(d => items.push({ type: 'Dragon', label: d.name, meta: 'Dragon · ' + (d.source || ''), page: 'dragons', kw: d.name + ' dragon ' + (d.source || '') }));
  (V.covenants || []).forEach(c => items.push({ type: 'Covenant', label: c.main, meta: 'Covenant', page: 'covenants', search: c.main, kw: c.main + ' covenant ' + [c.c1, c.c2, c.c3].join(' ') }));
  (window.GUIDE_INDEX || []).forEach(g => items.push({ type: 'Guide', label: g.q, meta: g.cat, page: 'guide', kw: g.q + ' ' + g.cat }));
  return items;
}

function scoreMatch(item, q) {
  const kw = (item.kw || item.label).toLowerCase();
  const label = item.label.toLowerCase();
  if (label === q) return 1000;
  if (label.startsWith(q)) return 800 - label.length;
  const wi = kw.indexOf(q);
  if (wi === 0) return 600;
  if (wi > 0) return 400 - wi;
  // subsequence fallback
  let i = 0; for (const ch of kw) { if (ch === q[i]) i++; if (i === q.length) break; }
  return i === q.length ? 100 : -1;
}

function CommandPalette({ open, onClose, onNavigate, nav }) {
  const [q, setQ] = useStateCK('');
  const [active, setActive] = useStateCK(0);
  const inputRef = useRefCK(null);
  const listRef = useRefCK(null);
  const index = useMemoCK(() => buildCommandIndex(nav), [nav, open]);

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

  const TYPE_ORDER = ['Page', 'Calculator', 'General', 'Dragon', 'Covenant', 'Guide'];
  const results = useMemoCK(() => {
    const ql = q.trim().toLowerCase();
    if (!ql) {
      // default: show primary pages + a few quick actions
      return index.filter(i => i.type === 'Page').slice(0, 8);
    }
    return index.map(i => ({ i, s: scoreMatch(i, ql) }))
      .filter(x => x.s > 0)
      .sort((a, b) => b.s - a.s || TYPE_ORDER.indexOf(a.i.type) - TYPE_ORDER.indexOf(b.i.type))
      .slice(0, 30).map(x => x.i);
  }, [q, index]);

  useEffectCK(() => { setActive(0); }, [q]);
  useEffectCK(() => {
    if (!open) return;
    const h = e => {
      if (e.key === 'Escape') { e.preventDefault(); onClose(); }
      else if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(results.length - 1, a + 1)); }
      else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
      else if (e.key === 'Enter') { e.preventDefault(); const r = results[active]; if (r) { onNavigate(r); onClose(); } }
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, results, active, onClose, onNavigate]);

  useEffectCK(() => {
    if (!listRef.current) return;
    const el = listRef.current.querySelector('[data-active="true"]');
    if (el) el.scrollIntoView({ block: 'nearest' });
  }, [active]);

  if (!open) return null;

  // group results for display
  const groups = [];
  TYPE_ORDER.forEach(t => { const g = results.filter(r => r.type === t); if (g.length) groups.push([t, g]); });
  let flatIdx = -1;

  return (
    <div className="fixed inset-0 z-[70] flex items-start justify-center px-4 pt-[12vh]">
      <div onClick={onClose} className="absolute inset-0" style={{ background: 'rgba(6,8,14,.6)', backdropFilter: 'blur(4px)' }}></div>
      <div className="ck-panel relative w-full max-w-xl overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-2xl dark:border-zinc-700/70 dark:bg-zinc-900">
        {/* search bar */}
        <div className="flex items-center gap-3 border-b border-zinc-100 px-4 dark:border-zinc-800">
          <Icon name="search" size={18} className="text-zinc-400" />
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Search generals, calculators, guides, dragons…"
            className="flex-1 bg-transparent py-4 text-[15px] outline-none placeholder:text-zinc-400" />
          <kbd className="hidden rounded border border-zinc-200 px-1.5 py-0.5 text-[10px] font-semibold text-zinc-400 dark:border-zinc-700 sm:block">ESC</kbd>
        </div>

        {/* results */}
        <div ref={listRef} className="max-h-[52vh] overflow-y-auto py-2">
          {results.length === 0 ? (
            <div className="px-4 py-10 text-center text-[13px] text-zinc-400">No matches. Try the <span className="font-semibold text-brand">AI Assistant</span> for anything specific.</div>
          ) : groups.map(([type, list]) => (
            <div key={type} className="mb-1">
              <div className="px-4 py-1 text-[10px] font-bold uppercase tracking-wider text-zinc-400">{type === 'Page' ? 'Modules' : type === 'General' ? 'Generals' : type + 's'}</div>
              {list.map(r => {
                flatIdx++;
                const idx = flatIdx; const on = idx === active;
                const m = CK_TYPE_META[r.type] || CK_TYPE_META.Page;
                return (
                  <button key={r.type + r.label + idx} data-active={on} onMouseEnter={() => setActive(idx)} onClick={() => { onNavigate(r); onClose(); }}
                    className={`flex w-full items-center gap-3 px-4 py-2 text-left transition-colors ${on ? 'bg-brand/10' : ''}`}>
                    <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg" style={{ background: m.color + '1c', color: m.color }}><Icon name={m.icon} size={14} /></span>
                    <span className="min-w-0 flex-1">
                      <span className="block truncate text-[13.5px] font-medium text-zinc-800 dark:text-zinc-100">{r.label}</span>
                      <span className="block truncate text-[11.5px] text-zinc-400">{r.meta}</span>
                    </span>
                    {on && <span className="hidden items-center gap-1 text-[11px] font-semibold text-brand sm:flex">Open <Icon name="arrow" size={12} /></span>}
                  </button>
                );
              })}
            </div>
          ))}
        </div>

        {/* footer */}
        <div className="flex items-center gap-4 border-t border-zinc-100 px-4 py-2 text-[10.5px] text-zinc-400 dark:border-zinc-800">
          <span className="flex items-center gap-1"><kbd className="rounded border border-zinc-200 px-1 dark:border-zinc-700">↑</kbd><kbd className="rounded border border-zinc-200 px-1 dark:border-zinc-700">↓</kbd> navigate</span>
          <span className="flex items-center gap-1"><kbd className="rounded border border-zinc-200 px-1 dark:border-zinc-700">↵</kbd> open</span>
          <span className="ml-auto flex items-center gap-1">{results.length} result{results.length !== 1 ? 's' : ''}</span>
        </div>
      </div>
    </div>
  );
}
window.CommandPalette = CommandPalette;
window.buildCommandIndex = buildCommandIndex;
