/* Command Palette (⌘K) ============================================== */

function CommandPalette({ open, onClose, accountId, platformId, onAction }){
  const [q, setQ] = useState('');
  const [idx, setIdx] = useState(0);
  const inputRef = useRef(null);
  const listRef = useRef(null);

  /* Build searchable index */
  const items = useMemo(() => {
    const all = [];
    /* Pages */
    all.push({ kind:'page', icon:'columns',  label:'Go to Platform Overview',  sub:'Page',  action:'go-platform', payload:'overview' });
    PLATFORMS.filter(p=>p.id!=='overview').forEach(p => {
      all.push({ kind:'page', icon:'columns',  label:`Go to ${p.label}`,         sub:'Platform page', action:'go-platform', payload:p.id });
    });
    /* Quick actions */
    all.push({ kind:'action', icon:'sun',      label:'Toggle dark mode',            sub:'Theme',         action:'toggle-dark' });
    all.push({ kind:'action', icon:'sparkles', label:'Open budget reallocator',     sub:'What-if',       action:'open-reallocator' });
    all.push({ kind:'action', icon:'zap',      label:'Open Automations',            sub:'Rules',         action:'open-automations' });
    all.push({ kind:'action', icon:'columns',  label:'New custom column',           sub:'Formula builder',action:'open-columns' });
    all.push({ kind:'action', icon:'bell',     label:'Mark all notifications read', sub:'Notifications', action:'mark-read' });
    /* Campaigns + ad sets across all platforms for this account */
    const campaigns = getCampaigns(accountId, 'overview');
    campaigns.forEach(c => {
      all.push({ kind:'campaign', icon:'play', label:c.name, sub:`Campaign · ${(PLATFORMS.find(p=>p.id===c.platform)||{}).label}  ·  ${curPrefix()}${c.spend.toLocaleString()}`, platform:c.platform, action:'view-campaign', payload:c });
      c.adsets.forEach(a => {
        all.push({ kind:'adset', icon:'sliders', label:a.name, sub:`Ad Set in ${c.name}`, platform:c.platform, action:'view-adset', payload:{campaign:c, adset:a} });
      });
    });
    return all;
  }, [accountId]);

  const filtered = useMemo(() => {
    if (!q.trim()) return items.slice(0, 14);
    const ql = q.toLowerCase();
    return items
      .map(it => {
        const ll = it.label.toLowerCase();
        const sl = it.sub.toLowerCase();
        let score = 0;
        if (ll.startsWith(ql)) score += 100;
        if (ll.includes(ql))   score += 40;
        if (sl.includes(ql))   score += 12;
        return { it, score };
      })
      .filter(x => x.score > 0)
      .sort((a,b) => b.score - a.score)
      .slice(0, 40)
      .map(x => x.it);
  }, [q, items]);

  useEffect(() => { setIdx(0); }, [q]);
  useEffect(() => { if (open) setTimeout(()=>inputRef.current?.focus(), 50); }, [open]);

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

  /* Scroll selected into view */
  useEffect(()=>{
    if (!open || !listRef.current) return;
    const el = listRef.current.querySelector(`[data-i="${idx}"]`);
    if (el) el.scrollIntoView({ block:'nearest' });
  }, [idx, open]);

  if (!open) return null;

  /* Group items for visual sectioning while preserving global idx */
  const groups = {};
  filtered.forEach((it,i)=>{
    const k = it.kind;
    if (!groups[k]) groups[k] = [];
    groups[k].push({ ...it, _i: i });
  });
  const groupLabels = { page:'Pages', action:'Quick actions', campaign:'Campaigns', adset:'Ad sets' };
  const groupOrder = ['action','page','campaign','adset'];

  return (
    <div className="fixed inset-0 z-[55] flex items-start justify-center pt-[12vh] px-4">
      <div className="absolute inset-0 bg-ink-900/40 backdrop-blur-sm animate-fade" onClick={onClose}/>
      <div className="relative w-full max-w-[640px] origin-top bg-white dark:bg-ink-800 rounded-2xl shadow-float border border-ink-200 dark:border-white/10 overflow-hidden animate-dropin">
        {/* Search bar */}
        <div className="flex items-center gap-2.5 px-4 h-14 border-b border-ink-200 dark:border-white/10">
          <Icon name="search" size={16} className="text-ink-400"/>
          <input ref={inputRef} value={q} onChange={e=>setQ(e.target.value)}
            placeholder="Search campaigns, ad sets, or actions…"
            className="flex-1 bg-transparent text-[14px] focus:outline-none placeholder:text-ink-400"/>
          <span className="text-[10px] font-mono text-ink-400 border border-ink-200 dark:border-white/10 rounded px-1 py-0.5">ESC</span>
        </div>
        {/* Results */}
        <div ref={listRef} className="max-h-[420px] overflow-y-auto scroll-thin py-1">
          {filtered.length === 0 && (
            <div className="px-4 py-10 text-center text-ink-500 dark:text-ink-300 text-[13px]">
              No results for <span className="font-mono">"{q}"</span>
            </div>
          )}
          {groupOrder.map(k => {
            const list = groups[k];
            if (!list || !list.length) return null;
            return (
              <div key={k}>
                <div className="px-3 pt-2 pb-1 text-[10px] uppercase tracking-wide font-semibold text-ink-400 dark:text-ink-500">{groupLabels[k]}</div>
                {list.map(it => {
                  const isActive = it._i === idx;
                  return (
                    <button key={it._i} data-i={it._i}
                      onMouseEnter={()=>setIdx(it._i)}
                      onClick={()=>{ onAction(it); onClose(); }}
                      className={`w-full flex items-center gap-3 px-3 py-2 text-left transition
                        ${isActive ? 'bg-accent-50 dark:bg-accent-500/15' : 'hover:bg-ink-50 dark:hover:bg-white/[0.03]'}`}>
                      <span className={`inline-flex items-center justify-center h-7 w-7 rounded-md
                        ${isActive ? 'bg-accent-500 text-white' : 'bg-ink-100 dark:bg-white/10 text-ink-600 dark:text-ink-300'}`}>
                        <Icon name={it.icon} size={13}/>
                      </span>
                      <span className="flex-1 min-w-0">
                        <div className={`text-[13px] font-medium truncate ${isActive?'text-accent-700 dark:text-accent-100':'text-ink-800 dark:text-ink-100'}`}>{it.label}</div>
                        <div className="text-[11px] text-ink-500 dark:text-ink-400 truncate flex items-center gap-1.5">
                          {it.platform && <PlatformChip p={it.platform} size={12}/>}
                          {it.sub}
                        </div>
                      </span>
                      {isActive && <Icon name="chev-right" size={13} className="text-accent-500"/>}
                    </button>
                  );
                })}
              </div>
            );
          })}
        </div>
        {/* Footer */}
        <div className="px-3 h-9 border-t border-ink-100 dark:border-white/10 flex items-center justify-between text-[10.5px] font-mono text-ink-500 dark:text-ink-400 bg-ink-50/60 dark:bg-white/[0.02]">
          <div className="flex items-center gap-2">
            <span><kbd className="bg-white dark:bg-ink-700 border border-ink-200 dark:border-white/10 rounded px-1">↑</kbd> <kbd className="bg-white dark:bg-ink-700 border border-ink-200 dark:border-white/10 rounded px-1">↓</kbd> navigate</span>
            <span className="text-ink-300">·</span>
            <span><kbd className="bg-white dark:bg-ink-700 border border-ink-200 dark:border-white/10 rounded px-1">↵</kbd> select</span>
          </div>
          <div className="flex items-center gap-1">
            <Icon name="sparkles" size={11}/> <span>Search powered by MCP</span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CommandPalette });
