// Command palette (⌘K). Searches trilhas, módulos, artefatos, feed posts.
const CommandPalette = ({ open, onClose, go }) => {
  const [q, setQ] = React.useState('');
  const [cursor, setCursor] = React.useState(0);
  const inputRef = React.useRef(null);

  // Build a single flat list of commands + content
  const entries = React.useMemo(() => {
    const out = [];
    // Actions
    out.push({ type: 'Ação', label: 'Ir para Início', run: () => go({name:'inicio'}), icon: 'home' });
    out.push({ type: 'Ação', label: 'Ver todas as trilhas', run: () => go({name:'trilhas'}), icon: 'route' });
    out.push({ type: 'Ação', label: 'Abrir Playbooks', run: () => go({name:'playbooks'}), icon: 'book' });
    out.push({ type: 'Ação', label: 'Ir para Biblioteca', run: () => go({name:'biblioteca'}), icon: 'library' });
    out.push({ type: 'Ação', label: 'Conteúdo vivo', run: () => go({name:'feed'}), icon: 'pulse' });
    out.push({ type: 'Ação', label: 'Certificações', run: () => go({name:'cert'}), icon: 'award' });
    out.push({ type: 'Ação', label: 'Meu perfil', run: () => go({name:'perfil'}), icon: 'user' });
    out.push({ type: 'Ação', label: 'Continuar de onde parei', run: () => go({name:'modulo', trilha:'fundamentos', modulo:'m6'}), icon: 'playFill' });

    // Trilhas
    VELYX.trilhas.forEach(t => {
      out.push({ type: 'Trilha', label: t.name, sub: `${t.modules} módulos · ${t.hours}`, run: () => go({name:'trilha', id:t.id}), icon: 'route' });
    });
    // Módulos
    Object.entries(VELYX.modulos).forEach(([tId, mods]) => {
      const t = VELYX.trilhas.find(x => x.id === tId);
      mods.forEach(m => {
        out.push({ type: 'Módulo', label: m.title, sub: `${t.name} · ${m.dur}`, run: () => go({name:'modulo', trilha:tId, modulo:m.id}), icon: 'playFill' });
      });
    });
    // Artefatos
    VELYX.biblioteca.forEach(b => {
      out.push({ type: 'Artefato', label: b.title, sub: `${b.type} · .${b.fmt}`, run: () => go({name:'biblioteca'}), icon: 'doc' });
    });
    // Posts
    VELYX.feed.forEach((p, i) => {
      out.push({ type: 'Post', label: p.title, sub: `${p.date} · ${p.tag}`, run: () => go({name:'post', idx:i}), icon: 'pulse' });
    });
    return out;
  }, [go]);

  const filtered = React.useMemo(() => {
    if (!q.trim()) return entries.slice(0, 10);
    const needle = q.toLowerCase();
    return entries.filter(e => (e.label + ' ' + (e.sub||'') + ' ' + e.type).toLowerCase().includes(needle)).slice(0, 30);
  }, [q, entries]);

  React.useEffect(() => { setCursor(0); }, [q]);
  React.useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 0);
    else setQ('');
  }, [open]);

  const handleKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setCursor(c => Math.min(c+1, filtered.length-1)); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setCursor(c => Math.max(c-1, 0)); }
    if (e.key === 'Enter')     { e.preventDefault(); const hit = filtered[cursor]; if (hit) { hit.run(); onClose(); } }
    if (e.key === 'Escape')    { e.preventDefault(); onClose(); }
  };

  if (!open) return null;

  // Group filtered entries by type
  const groups = {};
  filtered.forEach((e, i) => {
    groups[e.type] ??= [];
    groups[e.type].push({ ...e, _i: i });
  });

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-[12vh] px-4"
         onClick={onClose}>
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm"/>
      <div onClick={e => e.stopPropagation()}
           className="relative w-full max-w-[620px] rounded-[12px] bg-panel hairline2 shadow-[0_20px_60px_-10px_rgba(0,0,0,0.8)] overflow-hidden fade-in">
        {/* Input */}
        <div className="flex items-center gap-3 px-4 h-[52px] border-b border-line">
          <I.search size={16} className="text-mute2"/>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} onKeyDown={handleKey}
            placeholder="Busque trilhas, módulos, artefatos, posts..."
            className="flex-1 bg-transparent text-ink text-[14px] placeholder:text-mute2 focus:outline-none"/>
          <kbd className="font-mono text-[10.5px] text-mute2 hairline2 px-1.5 h-5 inline-flex items-center rounded">Esc</kbd>
        </div>

        {/* Results */}
        <div className="max-h-[50vh] overflow-y-auto py-2">
          {filtered.length === 0 && (
            <div className="py-8 text-center text-mute text-[13px]">Nada encontrado pra "{q}".</div>
          )}
          {Object.entries(groups).map(([type, items]) => (
            <div key={type} className="pb-1">
              <div className="px-4 pt-2 pb-1 text-mute2 text-[10px] font-mono uppercase tracking-[0.12em]">{type}</div>
              {items.map(item => {
                const active = item._i === cursor;
                const Icon = I[item.icon] || I.doc;
                return (
                  <button key={item._i}
                    onMouseEnter={() => setCursor(item._i)}
                    onClick={() => { item.run(); onClose(); }}
                    className={`w-full flex items-center gap-3 px-4 h-10 text-left t-fast ${active ? 'bg-white/[0.06]' : ''}`}>
                    <Icon size={14} className={active ? 'text-accent' : 'text-mute'}/>
                    <span className={`flex-1 text-[13px] truncate ${active ? 'text-ink' : 'text-ink/90'}`}>{item.label}</span>
                    {item.sub && <span className="text-mute2 text-[11.5px] font-mono truncate max-w-[220px]">{item.sub}</span>}
                    {active && <I.arrowRight size={12} className="text-accent"/>}
                  </button>
                );
              })}
            </div>
          ))}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-4 h-9 border-t border-line text-mute2 text-[11px] font-mono">
          <div className="flex items-center gap-3">
            <span className="flex items-center gap-1"><kbd className="hairline2 px-1 rounded">↑↓</kbd> navegar</span>
            <span className="flex items-center gap-1"><kbd className="hairline2 px-1 rounded">↵</kbd> abrir</span>
          </div>
          <span>{filtered.length} resultados</span>
        </div>
      </div>
    </div>
  );
};

window.CommandPalette = CommandPalette;
