/* CommandPalette.jsx — ⌘K, live API замість MOCK_*. */

const { useState: useStateCP, useEffect: useEffectCP, useRef: useRefCP } = React;

const NAV_PALETTE = [
  { kind: "nav", label: "Огляд",          icon: "◉", screen: "overview" },
  { kind: "nav", label: "Зупинки",        icon: "📍", screen: "stops" },
  { kind: "nav", label: "Маршрути",       icon: "🛤",  screen: "routes" },
  { kind: "nav", label: "Моніторинг",     icon: "📡", screen: "monitoring" },
  { kind: "nav", label: "Аналітика",      icon: "📊", screen: "analytics" },
  { kind: "nav", label: "Історія змін",   icon: "🕓", screen: "history" },
  { kind: "nav", label: "Налаштування",   icon: "⚙",  screen: "settings" },
];

const ACTIONS_PALETTE = [
  { kind: "action", label: "Нова зупинка", icon: "➕",
    fn: (nav) => { nav("stops"); window.showToast && window.showToast("Натисніть «+ Нова зупинка»","info"); } },
  { kind: "action", label: "Новий маршрут", icon: "➕",
    fn: (nav) => { nav("routes"); window.showToast && window.showToast("Натисніть «+ Новий маршрут»","info"); } },
  { kind: "action", label: "Логаут", icon: "⏻",
    fn: async () => {
      try { await window.passengerApi.auth.logout(); window.location.reload(); } catch {}
    } },
];

const KIND_LABELS = { nav: "Перейти", action: "Дія", stop: "Зупинка", route: "Маршрут" };

function CommandPalette({ open, onClose, onNav }) {
  const [q, setQ] = useStateCP("");
  const [sel, setSel] = useStateCP(0);
  const [stopsItems, setStopsItems] = useStateCP([]);
  const [routesItems, setRoutesItems] = useStateCP([]);
  const inputRef = useRefCP();

  // При відкритті — підтягуємо stops + routes (limit 50 кожен).
  useEffectCP(() => {
    if (!open) return;
    setQ(""); setSel(0);
    setTimeout(() => inputRef.current?.focus(), 30);

    let cancelled = false;
    (async () => {
      try {
        const [s, r] = await Promise.allSettled([
          window.passengerApi.stops.list({ limit: 50 }),
          window.passengerApi.routes.list({ limit: 50 }),
        ]);
        if (cancelled) return;
        if (s.status === "fulfilled") {
          setStopsItems((s.value.items || []).map(it => ({
            kind: "stop", icon: "📍",
            label: it.name, hint: `${it.code} · ${it.radius}м · ${it.status}`,
            screen: "stops",
          })));
        }
        if (r.status === "fulfilled") {
          setRoutesItems((r.value.items || []).map(it => ({
            kind: "route", icon: "🛤",
            label: `${it.code} ${it.name}`,
            hint: it.paused ? "⏸ призупинено" : `v${it.version} · ${it.status}`,
            screen: "routes",
          })));
        }
      } catch (e) { /* swallow */ }
    })();
    return () => { cancelled = true; };
  }, [open]);

  useEffectCP(() => {
    const handler = (e) => {
      if (e.key === "Escape" && open) { e.preventDefault(); onClose(); }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose]);

  const all = [...NAV_PALETTE, ...ACTIONS_PALETTE, ...stopsItems, ...routesItems];
  const filtered = q
    ? all.filter(i => i.label.toLowerCase().includes(q.toLowerCase()) || (i.hint || "").toLowerCase().includes(q.toLowerCase()))
    : all;

  useEffectCP(() => setSel(0), [q]);

  const activate = (item) => {
    if (item.fn) item.fn(onNav);
    else if (item.screen) onNav(item.screen);
    onClose();
  };

  const handleKey = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setSel(s => Math.min(s + 1, filtered.length - 1)); }
    if (e.key === "ArrowUp")   { e.preventDefault(); setSel(s => Math.max(s - 1, 0)); }
    if (e.key === "Enter" && filtered[sel]) activate(filtered[sel]);
  };

  const groups = filtered.reduce((acc, item) => {
    (acc[item.kind] = acc[item.kind] || []).push(item);
    return acc;
  }, {});

  let globalIdx = 0;

  if (!open) return null;

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)",
        zIndex: 200, display: "flex", alignItems: "flex-start", justifyContent: "center",
        paddingTop: "12vh", animation: "fadeIn 0.12s ease",
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        onKeyDown={handleKey}
        style={{
          width: "min(580px, 96vw)",
          background: "var(--surface)",
          border: "1px solid var(--border)",
          borderRadius: "var(--radius-lg)",
          boxShadow: "0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08)",
          overflow: "hidden",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 16px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ color: "var(--text-3)", fontSize: 16 }}>⌘</span>
          <input
            ref={inputRef}
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Пошук, навігація, дія…"
            style={{
              flex: 1, border: "none", outline: "none",
              fontFamily: "inherit", fontSize: 15,
              background: "transparent", color: "var(--text-1)",
            }}
          />
          <kbd style={{ fontSize: 11, color: "var(--text-3)", background: "var(--surface-3)", border: "1px solid var(--border)", padding: "2px 7px", borderRadius: 5, fontFamily: "monospace" }}>
            ESC
          </kbd>
        </div>

        <div style={{ maxHeight: 380, overflowY: "auto" }}>
          {filtered.length === 0 && (
            <div style={{ padding: "32px 16px", textAlign: "center", color: "var(--text-3)", fontSize: 14 }}>
              Нічого не знайдено
            </div>
          )}

          {Object.entries(groups).map(([kind, items]) => (
            <div key={kind}>
              <div style={{ padding: "8px 16px 4px", fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.6px", color: "var(--text-3)" }}>
                {KIND_LABELS[kind] || kind}
              </div>
              {items.map((item) => {
                const idx = globalIdx++;
                const isActive = idx === sel;
                return (
                  <div
                    key={kind + ":" + item.label}
                    onClick={() => activate(item)}
                    onMouseEnter={() => setSel(idx)}
                    style={{
                      display: "flex", alignItems: "center", gap: 12,
                      padding: "9px 16px", cursor: "pointer",
                      background: isActive ? "var(--accent-soft)" : "transparent",
                      borderLeft: `3px solid ${isActive ? "var(--accent)" : "transparent"}`,
                      transition: "background 0.08s",
                    }}
                  >
                    <span style={{ fontSize: 16, width: 22, textAlign: "center", flexShrink: 0 }}>{item.icon}</span>
                    <span style={{ flex: 1, fontSize: 14, fontWeight: 500, color: isActive ? "var(--accent)" : "var(--text-1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {item.label}
                    </span>
                    {item.hint && (
                      <span style={{ fontSize: 12, color: "var(--text-3)", flexShrink: 0 }}>{item.hint}</span>
                    )}
                  </div>
                );
              })}
            </div>
          ))}
        </div>

        <div style={{ padding: "8px 16px", borderTop: "1px solid var(--border)", display: "flex", justifyContent: "space-between", background: "var(--surface-2)" }}>
          <span style={{ fontSize: 11, color: "var(--text-3)" }}>
            <kbd style={{ fontFamily: "monospace", background: "var(--surface-3)", border: "1px solid var(--border)", padding: "1px 5px", borderRadius: 3 }}>↑↓</kbd> навігація &nbsp;
            <kbd style={{ fontFamily: "monospace", background: "var(--surface-3)", border: "1px solid var(--border)", padding: "1px 5px", borderRadius: 3 }}>↵</kbd> вибір
          </span>
          <span style={{ fontSize: 11, color: "var(--text-3)" }}>
            {filtered.length} результатів
          </span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CommandPalette });
