// Command palette — ⌘K / Ctrl+K
const { useState, useEffect, useMemo, useRef } = React;
function CommandPalette({ open, onClose, store, go, openAppt, openPerson }) {
  const [q, setQ] = useState("");
  const [active, setActive] = useState(0);
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) {
      setQ("");
      setActive(0);
      setTimeout(() => inputRef.current?.focus(), 40);
    }
  }, [open]);

  // Build commands list
  const commands = useMemo(() => {
    if (!store) return [];
    const out = [];

    // Navigation actions
    const navs = [
      ["dashboard", "Dashboard", "dashboard"],
      ["hoje",      "Ir para Hoje", "today"],
      ["semana",    "Ver semana", "week"],
      ["mes",       "Ver mês", "month"],
      ["agendar",   "Novo agendamento", "plus"],
      ["pessoas",   "Lista de pessoas", "people"],
      ["tarefas",   "Tarefas (kanban)", "kanban"],
      ["alertas",   "Alertas", "bell"],
      ["notas",     "Notas", "note"],
    ];
    navs.forEach(([key, label, icon]) => out.push({
      kind: "nav", icon, label, hint: "Navegar",
      run: () => { go(key); onClose(); },
    }));

    // Actions
    out.push({ kind: "action", icon: "download", label: "Exportar JSON (backup)", hint: "Ação", run: () => { store.exportJSON(); onClose(); } });
    out.push({ kind: "action", icon: "moon", label: "Alternar tema (claro/escuro)", hint: "Ação", run: () => { store.setTheme(store.data.settings.theme === "dark" ? "light" : "dark"); onClose(); } });
    out.push({ kind: "action", icon: "reset", label: "Restaurar dados de exemplo", hint: "Ação", run: () => { store.resetAll(); onClose(); } });

    // People
    store.data.people.forEach(p => out.push({
      kind: "person", icon: "people", label: p.name, hint: `${p.tag} · ${p.source}`,
      run: () => { openPerson(p); onClose(); },
    }));

    // Appointments (next 30 + past 10)
    const sorted = store.data.appointments.slice().sort((a, b) => (b.date + b.time).localeCompare(a.date + a.time));
    const upcoming = sorted.filter(a => a.date >= TODAY_ISO).reverse().slice(0, 30);
    const recent = sorted.filter(a => a.date < TODAY_ISO).slice(0, 10);
    [...upcoming, ...recent].forEach(a => {
      const person = store.data.people.find(p => p.id === a.personId);
      const dateLabel = new Date(a.date + "T00:00:00").toLocaleDateString("pt-BR", { day: "2-digit", month: "short" });
      out.push({
        kind: "appt", icon: "today",
        label: a.title + (person ? ` · ${person.name}` : ""),
        hint: `${dateLabel} · ${a.time} · ${a.type}`,
        run: () => { openAppt(a); onClose(); },
      });
    });

    // Notes
    store.data.notes.forEach(n => out.push({
      kind: "note", icon: "note", label: n.title, hint: "Nota",
      run: () => { go("notas"); onClose(); },
    }));

    return out;
  }, [store?.data, open]);

  // Filter
  const filtered = useMemo(() => {
    if (!q.trim()) return commands.slice(0, 50);
    const needle = q.toLowerCase();
    return commands.filter(c => (c.label + " " + (c.hint || "")).toLowerCase().includes(needle)).slice(0, 60);
  }, [q, commands]);

  // Keep active in bounds
  useEffect(() => { setActive(0); }, [q]);

  const handleKey = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setActive(a => Math.min(filtered.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(); filtered[active]?.run(); }
    else if (e.key === "Escape") onClose();
  };

  if (!open) return null;

  // Group filtered by kind for visual separation when no query
  const groups = q.trim() ? [{ key: "results", label: "Resultados", items: filtered }] : [
    { key: "nav", label: "Navegar", items: filtered.filter(c => c.kind === "nav") },
    { key: "action", label: "Ações", items: filtered.filter(c => c.kind === "action") },
    { key: "appt", label: "Atendimentos", items: filtered.filter(c => c.kind === "appt").slice(0, 8) },
    { key: "person", label: "Pessoas", items: filtered.filter(c => c.kind === "person").slice(0, 6) },
    { key: "note", label: "Notas", items: filtered.filter(c => c.kind === "note").slice(0, 4) },
  ].filter(g => g.items.length > 0);

  // Flat list mapping for indexes
  let flatIdx = -1;
  const indexOf = (cmd) => filtered.indexOf(cmd);

  return (
    <div className="palette-backdrop" onClick={onClose}>
      <div className="palette" onClick={e => e.stopPropagation()}>
        <div className="palette-input">
          <Icon name="search" />
          <input
            ref={inputRef}
            value={q}
            onChange={e => setQ(e.target.value)}
            onKeyDown={handleKey}
            placeholder="Buscar pessoa, agendamento, ação..."
          />
          <kbd>esc</kbd>
        </div>
        <div className="palette-list">
          {groups.map(g => (
            <div key={g.key} className="palette-group">
              <div className="palette-group-label">{g.label}</div>
              {g.items.map((cmd) => {
                const idx = indexOf(cmd);
                const isActive = idx === active;
                return (
                  <button
                    key={g.key + "-" + idx + cmd.label}
                    className={`palette-item${isActive ? " active" : ""}`}
                    onMouseEnter={() => setActive(idx)}
                    onClick={() => cmd.run()}
                  >
                    <span className="palette-icon"><Icon name={cmd.icon} size={14} /></span>
                    <span className="palette-label">{cmd.label}</span>
                    {cmd.hint && <span className="palette-hint dim small">{cmd.hint}</span>}
                  </button>
                );
              })}
            </div>
          ))}
          {filtered.length === 0 && (
            <div className="palette-empty">
              <div className="dim">Nada encontrado para "{q}".</div>
            </div>
          )}
        </div>
        <div className="palette-foot">
          <span className="dim small"><kbd>↑↓</kbd> navegar</span>
          <span className="dim small"><kbd>↵</kbd> selecionar</span>
          <span className="dim small"><kbd>esc</kbd> fechar</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CommandPalette });
