// ui_kits/site/CommandPalette.jsx — opens with ":" via Popover API. Konami swaps to plasma.
const COMMANDS = [
  { id: 'home',  label: '→ go home',         hint: '/',            action: 'route:/' },
  { id: 'about', label: '→ about',           hint: '/about',       action: 'route:/about' },
  { id: 'exp',   label: '→ experiments',     hint: '/experiments', action: 'route:/experiments' },
  { id: 'fun',   label: '→ fun',             hint: '/fun',         action: 'route:/fun' },
  { id: 'lava',  label: 'mode · lava',       hint: 'light',        action: 'mode:lava' },
  { id: 'abyss', label: 'mode · abyss',      hint: 'dark',         action: 'mode:abyss' },
  { id: 'plasma',label: 'mode · plasma',     hint: 'demo',         action: 'mode:plasma' },
  { id: '404',   label: '→ break the site',  hint: '/lost',        action: 'route:/lost' },
];

const CommandPalette = ({ setRoute, setMode }) => {
  const popRef = React.useRef(null);
  const inputRef = React.useRef(null);
  const [q, setQ] = React.useState('');
  const [idx, setIdx] = React.useState(0);

  React.useEffect(() => {
    const onKey = (e) => {
      // Open on `:` (also handle Cmd/Ctrl+K for convention)
      const target = e.target;
      const inField = target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable);
      if (!inField && (e.key === ':' || (e.key === 'k' && (e.metaKey || e.ctrlKey)))) {
        e.preventDefault();
        popRef.current?.showPopover();
        setTimeout(() => inputRef.current?.focus(), 0);
        setQ(''); setIdx(0);
      }
    };
    addEventListener('keydown', onKey);

    // Konami → plasma for 10s
    const seq = ['ArrowUp','ArrowUp','ArrowDown','ArrowDown','ArrowLeft','ArrowRight','ArrowLeft','ArrowRight','b','a'];
    let pos = 0;
    const konami = (e) => {
      if (e.key.toLowerCase() === seq[pos].toLowerCase()) {
        pos++;
        if (pos === seq.length) {
          pos = 0;
          const prev = document.documentElement.getAttribute('data-mode');
          setMode('plasma');
          setTimeout(() => setMode(prev || 'lava'), 10000);
        }
      } else pos = 0;
    };
    addEventListener('keydown', konami);

    return () => { removeEventListener('keydown', onKey); removeEventListener('keydown', konami); };
  }, [setMode]);

  const filtered = q ? COMMANDS.filter(c => (c.label + c.hint).toLowerCase().includes(q.toLowerCase())) : COMMANDS;
  React.useEffect(() => { if (idx >= filtered.length) setIdx(0); }, [filtered.length, idx]);

  const run = (cmd) => {
    popRef.current?.hidePopover();
    if (cmd.action.startsWith('route:')) setRoute(cmd.action.slice(6));
    if (cmd.action.startsWith('mode:'))  setMode(cmd.action.slice(5));
  };

  return (
    <div ref={popRef} id="koa-palette" popover="auto" className="koa-palette" onKeyDown={(e) => {
      if (e.key === 'ArrowDown') { e.preventDefault(); setIdx(i => Math.min(filtered.length - 1, i + 1)); }
      if (e.key === 'ArrowUp')   { e.preventDefault(); setIdx(i => Math.max(0, i - 1)); }
      if (e.key === 'Enter' && filtered[idx]) run(filtered[idx]);
      if (e.key === 'Escape') popRef.current?.hidePopover();
    }}>
      <div className="kp-input-row">
        <span className="kp-prompt">:</span>
        <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="type a command…" autoFocus />
      </div>
      <ul className="kp-list">
        {filtered.map((c, i) => (
          <li key={c.id} data-active={i === idx} onMouseEnter={() => setIdx(i)} onClick={() => run(c)}>
            <span>{c.label}</span><span className="kp-hint">{c.hint}</span>
          </li>
        ))}
        {filtered.length === 0 && <li className="kp-empty">no match. try again.</li>}
      </ul>
      <style>{`
        .koa-palette {
          position: fixed; inset: 0; margin: auto;
          width: min(540px, 92vw); height: max-content;
          padding: 0; border: 1px solid var(--border-strong);
          border-radius: 14px; background: color-mix(in oklch, var(--bg-elev) 90%, transparent);
          backdrop-filter: blur(28px) saturate(180%); -webkit-backdrop-filter: blur(28px) saturate(180%);
          box-shadow: var(--shadow-3);
          color: var(--fg);
        }
        .koa-palette::backdrop {
          background: color-mix(in oklch, var(--c-ink) 30%, transparent);
          backdrop-filter: blur(4px);
        }
        .kp-input-row {
          display: flex; align-items: center; gap: 10px; padding: 14px 16px;
          border-bottom: 1px solid var(--border);
        }
        .kp-prompt { font-family: var(--font-mono); font-size: 18px; color: var(--accent); }
        .kp-input-row input {
          flex: 1; background: transparent; border: 0; outline: 0;
          font-family: var(--font-sans); font-size: 16px; color: var(--fg);
        }
        .kp-list { list-style: none; margin: 0; padding: 6px; max-height: 320px; overflow: auto; }
        .kp-list li {
          padding: 10px 12px; border-radius: 8px; cursor: none;
          display: flex; justify-content: space-between; align-items: center; gap: var(--s-3);
          font-family: var(--font-sans); font-size: 14px; color: var(--fg);
        }
        .kp-list li[data-active="true"] { background: color-mix(in oklch, var(--accent) 14%, transparent); color: var(--fg); }
        .kp-hint { font-family: var(--font-mono); font-size: 11px; color: var(--fg-faint); }
        .kp-empty { color: var(--fg-faint); font-family: var(--font-mono); font-size: 12px; padding: 14px; }
      `}</style>
    </div>
  );
};

window.CommandPalette = CommandPalette;
