// cmdk.jsx — Cmd+K command palette

const { useState: useStateK, useMemo: useMemoK, useEffect: useEffectK, useRef: useRefK } = React;

function CommandPalette({ open, onClose, onNavigate }) {
  const [q, setQ] = useStateK("");
  const [cursor, setCursor] = useStateK(0);
  const inputRef = useRefK(null);

  useEffectK(() => {
    if (open) {
      setQ("");
      setCursor(0);
      setTimeout(() => inputRef.current && inputRef.current.focus(), 10);
    }
  }, [open]);

  // Build items list: pages + accounts + chats + checks shortcuts
  const items = useMemoK(() => {
    const list = [];
    NAV.forEach((g) =>
      g.items.forEach((item) =>
        list.push({
          kind: "page",
          group: g.group,
          id: item.id,
          icon: item.icon,
          title: item.label,
          subtitle: g.group,
          hotkey: item.hotkey,
          run: () => onNavigate(item.id),
        })
      )
    );
    ACCOUNTS.slice(0, 14).forEach((a) =>
      list.push({
        kind: "account",
        group: "Аккаунты",
        id: "acc-" + a.id,
        icon: "users",
        title: a.name,
        subtitle: a.username,
        color: a.color,
        run: () => onNavigate("accounts"),
      })
    );
    CHATS.slice(0, 8).forEach((c) =>
      list.push({
        kind: "chat",
        group: "Переписки",
        id: "chat-" + c.id,
        icon: "chat",
        title: c.name,
        subtitle: "через " + c.account.name,
        color: c.account.color,
        run: () => onNavigate("chats"),
      })
    );
    // Actions
    [
      { id: "act-add-account", title: "Добавить аккаунт", icon: "plus", subtitle: "Аккаунты", run: () => onNavigate("accounts") },
      { id: "act-add-req", title: "Добавить реквизит", icon: "card", subtitle: "Реквизиты", run: () => onNavigate("requisites") },
      { id: "act-upload", title: "Загрузить контент", icon: "upload", subtitle: "Контент", run: () => onNavigate("content") },
      { id: "act-pending", title: "Открыть чеки на проверке", icon: "receipt", subtitle: "Чеки", run: () => onNavigate("checks") },
      { id: "act-stop", title: "Остановить бота", icon: "square", subtitle: "Бот · сейчас запущен", run: () => onNavigate("settings") },
      { id: "act-restart", title: "Перезапустить бота", icon: "refresh", subtitle: "Бот", run: () => onNavigate("settings") },
    ].forEach((a) => list.push({ kind: "action", group: "Действия", ...a }));
    return list;
  }, []);

  const filtered = useMemoK(() => {
    if (!q.trim()) return items;
    const lo = q.toLowerCase();
    return items.filter((i) =>
      i.title.toLowerCase().includes(lo) ||
      (i.subtitle || "").toLowerCase().includes(lo)
    );
  }, [q, items]);

  // Reset cursor when filter changes
  useEffectK(() => { setCursor(0); }, [q]);

  // Group filtered items by group, preserving order
  const grouped = useMemoK(() => {
    const map = new Map();
    filtered.forEach((it) => {
      if (!map.has(it.group)) map.set(it.group, []);
      map.get(it.group).push(it);
    });
    return Array.from(map.entries());
  }, [filtered]);

  // Keyboard
  useEffectK(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") { onClose(); }
      else if (e.key === "ArrowDown") {
        e.preventDefault();
        setCursor((c) => Math.min(c + 1, filtered.length - 1));
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setCursor((c) => Math.max(c - 1, 0));
      } else if (e.key === "Enter") {
        e.preventDefault();
        const it = filtered[cursor];
        if (it) { it.run(); onClose(); }
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, filtered, cursor, onClose]);

  if (!open) return null;

  let globalIdx = -1;

  return (
    <div className="fixed inset-0 z-[100] overlay-in" onClick={onClose}>
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
      <div className="absolute top-[12vh] left-1/2 -translate-x-1/2 w-[600px] max-w-[92vw]">
        <div
          onClick={(e) => e.stopPropagation()}
          className="palette-in bg-zinc-900/95 backdrop-blur-xl border border-zinc-800 rounded-2xl shadow-2xl shadow-black/40 overflow-hidden"
        >
          <div className="flex items-center gap-3 px-4 border-b border-zinc-800">
            <Icon name="search" className="w-4 h-4 text-zinc-500" />
            <input
              ref={inputRef}
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Поиск страниц, аккаунтов, действий…"
              className="flex-1 bg-transparent py-4 text-sm placeholder:text-zinc-500 focus:outline-none"
            />
            <Kbd>ESC</Kbd>
          </div>

          <div className="max-h-[60vh] overflow-y-auto py-1">
            {filtered.length === 0 && (
              <div className="px-4 py-12 text-center">
                <div className="text-sm text-zinc-400 mb-1">Ничего не найдено</div>
                <div className="text-[11px] text-zinc-600">Попробуй другой запрос</div>
              </div>
            )}
            {grouped.map(([group, items]) => (
              <div key={group} className="py-1">
                <div className="px-4 py-1.5 text-[10px] uppercase tracking-wider text-zinc-500 font-semibold">{group}</div>
                {items.map((it) => {
                  globalIdx++;
                  const isActive = globalIdx === cursor;
                  const myIdx = globalIdx;
                  return (
                    <button
                      key={it.id}
                      onMouseEnter={() => setCursor(myIdx)}
                      onClick={() => { it.run(); onClose(); }}
                      className={"w-full flex items-center gap-3 px-3 py-2 mx-1 rounded-lg text-left transition-colors " + (isActive ? "bg-indigo-500/15" : "")}
                    >
                      {it.color ? (
                        <Avatar name={it.title} color={it.color} size={26} />
                      ) : (
                        <div className={"w-7 h-7 rounded-lg flex items-center justify-center " + (isActive ? "bg-indigo-500/20 text-indigo-300" : "bg-zinc-800 text-zinc-400")}>
                          <Icon name={it.icon} className="w-3.5 h-3.5" />
                        </div>
                      )}
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium truncate">{it.title}</div>
                        {it.subtitle && <div className="text-[11px] text-zinc-500 truncate">{it.subtitle}</div>}
                      </div>
                      {it.hotkey && (
                        <div className="flex items-center gap-1">
                          {it.hotkey.split(" ").map((k, i) => <Kbd key={i}>{k.toUpperCase()}</Kbd>)}
                        </div>
                      )}
                      {isActive && !it.hotkey && (
                        <Icon name="arrowRight" className="w-3.5 h-3.5 text-indigo-400" />
                      )}
                    </button>
                  );
                })}
              </div>
            ))}
          </div>

          <div className="border-t border-zinc-800 px-3 py-2 flex items-center justify-between text-[10px] text-zinc-500">
            <div className="flex items-center gap-3">
              <span className="flex items-center gap-1"><Kbd>↑</Kbd><Kbd>↓</Kbd> навигация</span>
              <span className="flex items-center gap-1"><Kbd>↵</Kbd> выбор</span>
            </div>
            <div className="flex items-center gap-1">
              <span>{filtered.length} результатов</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================
   Hotkey hint toast
============================ */

function HotkeyHint({ show, label }) {
  if (!show) return null;
  return (
    <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[90]">
      <div className="bg-zinc-900/95 backdrop-blur-xl border border-zinc-800 rounded-xl px-3 py-2 flex items-center gap-2 shadow-2xl">
        <Kbd>G</Kbd>
        <span className="text-xs text-zinc-400">→</span>
        <span className="text-xs text-zinc-200 font-medium">{label}</span>
      </div>
    </div>
  );
}

Object.assign(window, { CommandPalette, HotkeyHint });
