// SQSEO command palette (Cmd/Ctrl-K). Fuzzy search over: navigate to a screen,
// switch project, switch workspace, open settings, sign out. Full keyboard nav
// (up/down/enter/escape). Controlled by App: <CommandPalette open onClose onNavigate/>.
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Icon } = DS;
window.LTQ = window.LTQ || {};
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

const FALLBACK_NAV = [
  { id: "dashboard", label: "Overview", icon: "layout-grid" },
  { id: "research", label: "Keyword Research", icon: "search" },
  { id: "ai", label: "AI Search Queries", icon: "sparkles" },
  { id: "competitor", label: "Competitor Gaps", icon: "git-compare" },
  { id: "content", label: "Content Ideas", icon: "lightbulb" },
  { id: "saved", label: "Saved Lists", icon: "bookmark" },
  { id: "exports", label: "Exports", icon: "download" },
];

// Subsequence fuzzy match (e.g. "kwr" matches "Keyword Research").
function fuzzy(q, s){
  if (!q) return true;
  q = q.toLowerCase(); s = s.toLowerCase();
  let i = 0;
  for (let k = 0; k < s.length && i < q.length; k++) if (s[k] === q[i]) i++;
  return i === q.length;
}

function buildCommands(onNavigate, close){
  const boot = window.LTQ.boot || {};
  const nav = window.LTQ.NAV || FALLBACK_NAV;
  const cmds = [];
  nav.forEach((n) => cmds.push({ id: "nav-" + n.id, icon: n.icon, label: t("nav." + n.id), group: t("palette.go_to"), run: () => { onNavigate(n.id); close(); } }));
  cmds.push({ id: "nav-settings", icon: "settings", label: t("nav.settings"), group: t("palette.go_to"), run: () => { onNavigate("settings"); close(); } });

  (boot.projects || []).forEach((p) => cmds.push({
    id: "proj-" + p.id, icon: "folder", label: p.name, group: t("palette.switch_project"),
    active: boot.project && p.id === boot.project.id,
    run: async () => { close(); const r = await window.LTQ.api.post("/api/project/switch", { projectId: p.id }); if (r.ok) { await window.LTQ.reloadBoot(); window.LTQ.toast(t("chrome.switched_to", { name: p.name })); } },
  }));
  if ((boot.workspaces || []).length > 1) {
    boot.workspaces.forEach((w) => cmds.push({
      id: "ws-" + w.id, icon: "layers", label: w.name, group: t("palette.switch_workspace"),
      active: w.id === boot.active_workspace,
      run: async () => { close(); const r = await window.LTQ.api.post("/api/workspace/switch", { workspaceId: w.id }); if (r.ok) { await window.LTQ.reloadBoot(); window.LTQ.toast(t("chrome.switched_to", { name: w.name })); } },
    }));
  }
  cmds.push({ id: "tour-core", icon: "map", label: t("palette.tour_core"), group: t("palette.help"),
    run: () => { close(); onNavigate("dashboard"); setTimeout(() => window.LTQ.startTour(window.LTQ.coreTour(), { onNavigate }), 500); } });
  cmds.push({ id: "tour-depth", icon: "compass", label: t("palette.tour_depth"), group: t("palette.help"),
    run: () => { close(); setTimeout(() => window.LTQ.startTour(window.LTQ.depthTour(), { onNavigate }), 400); } });
  cmds.push({ id: "signout", icon: "log-out", label: t("chrome.sign_out"), group: t("palette.account"), danger: true,
    run: async () => { await window.LTQ.api.post("/api/auth/logout"); window.location.href = "/app/login.html"; } });
  return cmds;
}

function CommandPalette({ open, onClose, onNavigate }){
  const [q, setQ] = React.useState("");
  const [sel, setSel] = React.useState(0);
  const inputRef = React.useRef(null);
  const listRef = React.useRef(null);

  const all = React.useMemo(() => buildCommands(onNavigate, onClose), [open]);
  const matches = React.useMemo(() => all.filter((c) => fuzzy(q, c.label) || fuzzy(q, c.group)), [all, q]);

  React.useEffect(() => { if (open) { setQ(""); setSel(0); setTimeout(() => inputRef.current && inputRef.current.focus(), 30); } }, [open]);
  React.useEffect(() => { setSel(0); }, [q]);
  React.useEffect(() => {
    const el = listRef.current && listRef.current.querySelector('[data-sel="1"]');
    if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest" });
  }, [sel]);

  if (!open) return null;

  const run = (i) => { const c = matches[i]; if (c) c.run(); };
  const onKey = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setSel((s) => Math.min(matches.length - 1, s + 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setSel((s) => Math.max(0, s - 1)); }
    else if (e.key === "Enter") { e.preventDefault(); run(sel); }
    else if (e.key === "Escape") { e.preventDefault(); onClose(); }
  };

  // Group the filtered commands while keeping a flat index for keyboard nav.
  let flat = -1;
  const groups = [];
  matches.forEach((c) => {
    let g = groups.find((x) => x.name === c.group);
    if (!g) { g = { name: c.group, items: [] }; groups.push(g); }
    g.items.push(c);
  });

  return (
    <div onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: "fixed", inset: 0, zIndex: 200, display: "flex", justifyContent: "center", alignItems: "flex-start",
        padding: "min(12vh, 60px) 14px 0", background: "rgba(12,16,14,0.42)", backdropFilter: "blur(3px)" }}>
      <div className="lt-cmd-in" style={{ width: "100%", maxWidth: 580, background: "var(--paper)", border: "1px solid var(--border-subtle)",
        borderRadius: 14, boxShadow: "var(--shadow-lg)", overflow: "hidden", transformOrigin: "top center" }}>
        {/* search row */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
          <Icon name="search" size={18} style={{ color: "var(--text-faint)", flex: "none" }} />
          <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={onKey}
            placeholder={t("palette.placeholder")}
            style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 500, color: "var(--text-strong)" }} />
          <kbd style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-faint)", background: "var(--ink-50)", border: "1px solid var(--border-subtle)", borderRadius: 5, padding: "2px 6px" }}>esc</kbd>
        </div>
        {/* results */}
        <div ref={listRef} className="lt-scroll" style={{ maxHeight: 360, overflowY: "auto", padding: 6 }}>
          {matches.length === 0 && (
            <div style={{ padding: "28px 16px", textAlign: "center", fontSize: 13.5, color: "var(--text-faint)" }}>{t("palette.no_matches", { q })}</div>
          )}
          {groups.map((g) => (
            <div key={g.name} style={{ marginBottom: 4 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-faint)", letterSpacing: "0.02em", padding: "8px 9px 4px" }}>{g.name}</div>
              {g.items.map((c) => {
                flat++;
                const i = flat;
                const isSel = i === sel;
                return (
                  <button key={c.id} data-sel={isSel ? "1" : "0"} onMouseEnter={() => setSel(i)} onClick={() => run(i)}
                    style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "9px 10px", border: "none",
                      borderRadius: 9, cursor: "pointer", textAlign: "left", background: isSel ? "var(--ink-100)" : "transparent" }}>
                    <span style={{ width: 28, height: 28, flex: "none", borderRadius: 8, display: "grid", placeItems: "center",
                      background: isSel ? "var(--paper)" : "var(--ink-50)", color: c.danger ? "var(--viz-red)" : "var(--text-muted)" }}>
                      <Icon name={c.icon} size={15} />
                    </span>
                    <span style={{ flex: 1, minWidth: 0, fontSize: 13.5, fontWeight: 500, color: c.danger ? "var(--viz-red)" : "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.label}</span>
                    {c.active && <Icon name="check" size={15} style={{ color: "var(--accent-500)", flex: "none" }} />}
                    {isSel && !c.active && <Icon name="corner-down-left" size={14} style={{ color: "var(--text-faint)", flex: "none" }} />}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
window.LTQ.CommandPalette = CommandPalette;
})();
