// ============================================================
// CommandPalette.jsx — Cmd+K
// ============================================================
function CommandPalette() {
  const { cmdOpen, setCmdOpen, navigate, setCopilotOpen, setTheme, theme, seed } = useStore();
  const [q, setQ] = React.useState('');
  const [sel, setSel] = React.useState(0);

  React.useEffect(() => {
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setCmdOpen((o) => !o);
      } else if (e.key === 'Escape') {
        setCmdOpen(false);
      }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [setCmdOpen]);

  if (!cmdOpen) return null;

  const PAGES = [
    { kind: 'Pagine', id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
    { kind: 'Pagine', id: 'projects', label: 'Progetti CAPEX', icon: 'projects' },
    { kind: 'Pagine', id: 'workflow', label: 'Workflow CAPEX', icon: 'workflow' },
    { kind: 'Pagine', id: 'archive', label: 'Archivio storico', icon: 'archive' },
    { kind: 'Pagine', id: 'rda', label: 'Richieste di Acquisto', icon: 'rda' },
    { kind: 'Pagine', id: 'oda', label: 'Ordini di Acquisto', icon: 'rda' },
    { kind: 'Pagine', id: 'benchmark', label: 'Benchmark', icon: 'benchmark' },
    { kind: 'Pagine', id: 'communications', label: 'Comunicazioni', icon: 'comm' },
    { kind: 'Pagine', id: 'documents', label: 'Documenti', icon: 'docs' },
    { kind: 'Pagine', id: 'vendors', label: 'Vendor', icon: 'vendors' },
    { kind: 'Pagine', id: 'reports', label: 'Reportistica', icon: 'reports' },
    { kind: 'Pagine', id: 'alerts', label: 'Alert', icon: 'alerts' },
    { kind: 'Pagine', id: 'audit', label: 'Audit log', icon: 'audit' },
    { kind: 'Pagine', id: 'customizing', label: 'Customizing', icon: 'sliders' },
    { kind: 'Pagine', id: 'settings', label: 'Impostazioni', icon: 'settings' },
    { kind: 'Pagine', id: 'aichat', label: 'AI Assistant', icon: 'sparkle', act: () => setCopilotOpen(true) },
  ];
  const AI = [
    { kind: 'Agent action', id: 'ai_summary', label: 'Riassumi portfolio', icon: 'sparkle', act: () => { setCopilotOpen(true); } },
    { kind: 'Agent action', id: 'ai_risks', label: 'Trova progetti a rischio', icon: 'warning_tri', act: () => { setCopilotOpen(true); } },
    { kind: 'Agent action', id: 'ai_rda', label: 'Genera bozza RdA', icon: 'rda', act: () => { navigate('rda'); } },
    { kind: 'Agent action', id: 'ai_bench', label: 'Benchmark su offerta corrente', icon: 'benchmark', act: () => { navigate('benchmark'); } },
  ];
  const UTIL = [
    { kind: 'Utility', id: 'theme', label: 'Cambia tema (' + (theme === 'dark' ? 'chiaro' : 'scuro') + ')', icon: theme === 'dark' ? 'sun' : 'moon', act: () => { setTheme(theme === 'dark' ? 'light' : 'dark'); } },
    { kind: 'Utility', id: 'copilot', label: 'Apri Copilot', icon: 'sparkle', act: () => setCopilotOpen(true) },
  ];
  const PROJ = seed.PROJECTS.slice(0, 10).map((p) => ({ kind: 'Progetti', id: 'project:' + p.id, label: p.code + ' — ' + p.name, icon: 'projects', act: () => navigate('project_detail', p.id) }));

  const all = [...PAGES, ...AI, ...PROJ, ...UTIL];
  const filtered = q ? all.filter((x) => x.label.toLowerCase().includes(q.toLowerCase())) : all;
  const groups = {};
  filtered.forEach((x) => { (groups[x.kind] = groups[x.kind] || []).push(x); });

  function pick(it) {
    setCmdOpen(false);
    setQ('');
    if (it.act) it.act();
    else navigate(it.id);
  }

  function onKeyDown(e) {
    if (e.key === 'ArrowDown') { setSel((s) => Math.min(s + 1, filtered.length - 1)); e.preventDefault(); }
    if (e.key === 'ArrowUp') { setSel((s) => Math.max(s - 1, 0)); e.preventDefault(); }
    if (e.key === 'Enter') { pick(filtered[sel] || filtered[0]); }
  }

  return (
    <div className="cmdk-backdrop" onClick={() => setCmdOpen(false)}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()}>
        <input
          autoFocus
          placeholder="Cerca pagine, progetti, azioni AI…"
          value={q}
          onChange={(e) => { setQ(e.target.value); setSel(0); }}
          onKeyDown={onKeyDown}
        />
        <div className="cmdk-list">
          {Object.keys(groups).map((k) => (
            <div key={k}>
              <div className="cmdk-group-label">{k}</div>
              {groups[k].map((it, idx) => {
                const globalIdx = filtered.indexOf(it);
                return (
                  <div key={it.id} className={`cmdk-item ${globalIdx === sel ? 'active' : ''}`} onClick={() => pick(it)} onMouseEnter={() => setSel(globalIdx)}>
                    <Icon name={it.icon} size={14} /> {it.label}
                    <span className="kbd">↵</span>
                  </div>
                );
              })}
            </div>
          ))}
          {filtered.length === 0 && <div style={{ padding: 20, color: 'var(--text-2)', textAlign: 'center', fontSize: 12 }}>Nessun risultato</div>}
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { CommandPalette });
