// CommandPalette — ⌘K overlay. Modern, keyboard-first; fits the corporate aesthetic.

const COMMANDS = [
  { group: "Jump to",        items: [
    { id: "g-dash",      icon: "ti-layout-dashboard", label: "Go to Dashboard",         section: "dashboard",  meta: "G D" },
    { id: "g-tenants",   icon: "ti-buildings",        label: "Go to Tenants",           section: "tenants",    meta: "G T" },
    { id: "g-sanctions", icon: "ti-shield-half",      label: "Go to Sanctions queue",   section: "sanctions",  meta: "G S" },
    { id: "g-audit",     icon: "ti-history",          label: "Go to Audit search",      section: "audit",      meta: "G A" },
    { id: "g-settle",    icon: "ti-receipt-2",        label: "Go to Settlements",       section: "settlements",meta: "G F" },
  ]},
  { group: "Tenants",        items: [
    { id: "t-kht", icon: "ti-buildings", label: "Khao Hom Thai",  meta: "Producer · TH" },
    { id: "t-sia", icon: "ti-buildings", label: "Siam Cosmetic",  meta: "Producer · TH" },
    { id: "t-bkb", icon: "ti-buildings", label: "Bangkok Beauty", meta: "Producer · TH · manual review" },
  ]},
  { group: "Actions",        items: [
    { id: "a-add",   icon: "ti-plus",       label: "Add tenant",        meta: "" },
    { id: "a-exp",   icon: "ti-download",   label: "Export selected as CSV", meta: "" },
    { id: "a-rot",   icon: "ti-key",        label: "Rotate KMS key (requires approval)", meta: "I7" },
    { id: "a-feat",  icon: "ti-flag",       label: "Open feature flags", meta: "" },
  ]},
];

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

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

  // Filter
  const filtered = COMMANDS
    .map(g => ({ ...g, items: g.items.filter(it => (it.label + " " + (it.meta || "")).toLowerCase().includes(q.toLowerCase())) }))
    .filter(g => g.items.length > 0);
  const flat = filtered.flatMap(g => g.items);

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

  // reset cursor when query changes
  React.useEffect(() => { setCursor(0); }, [q]);

  let runningIdx = -1;

  return (
    <div className={"cmdk " + (open ? "open" : "")} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="cmdk-card" role="dialog" aria-modal="true" aria-label="Command palette">
        <div className="cmdk-input">
          <i className="ti ti-command"></i>
          <input ref={inputRef} placeholder="Jump to a tenant, action, or page…" value={q} onChange={(e) => setQ(e.target.value)} />
          <span className="kbd">Esc</span>
        </div>
        <div className="cmdk-list">
          {filtered.length === 0 && (
            <div style={{padding:"24px 16px", textAlign:"center", fontFamily:"var(--font-sans)", fontSize:13, color:"var(--on-surface-variant)"}}>
              No matches for &ldquo;{q}&rdquo;
            </div>
          )}
          {filtered.map(g => (
            <div key={g.group}>
              <div className="cmdk-group-label">{g.group}</div>
              {g.items.map(it => {
                runningIdx++;
                const isActive = runningIdx === cursor;
                return (
                  <div key={it.id} className={"cmdk-item" + (isActive ? " active" : "")}
                       onMouseEnter={() => setCursor(runningIdx)}
                       onClick={() => { if (it.section) onNavigate(it.section); onClose(); }}>
                    <i className={"ti " + it.icon}></i>
                    <span className="label">{it.label}</span>
                    {it.meta && <span className="meta">{it.meta}</span>}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
        <div className="cmdk-foot">
          <span className="hint"><span className="kbd">↑</span><span className="kbd">↓</span> navigate</span>
          <span className="hint"><span className="kbd">↵</span> open</span>
          <span className="hint"><span className="kbd">Esc</span> close</span>
          <span style={{marginLeft:"auto"}}>Press <span className="kbd">⌘K</span> from anywhere</span>
        </div>
      </div>
    </div>
  );
}

window.CommandPalette = CommandPalette;
