// Palette — ⌘K / any-key triggered command palette.
// Commands: cycle to a specific metric, open LinkedIn, open case study detail, toggle motion.

const COMMANDS = [
  { id: 'm0', label: 'SHOW PORTFOLIO ARR',           tag: 'METRIC',  action: 'metric', param: 0 },
  { id: 'm1', label: 'SHOW NET REVENUE RETENTION',   tag: 'METRIC',  action: 'metric', param: 1 },
  { id: 'm2', label: 'SHOW PIPELINE COVERAGE',       tag: 'METRIC',  action: 'metric', param: 2 },
  { id: 'm3', label: 'SHOW ACCOUNT HEALTH',          tag: 'METRIC',  action: 'metric', param: 3 },
  { id: 'm4', label: 'SHOW DEAL VELOCITY',           tag: 'METRIC',  action: 'metric', param: 4 },
  { id: 'm5', label: 'SHOW LIVE SIGNALS · 24H',      tag: 'METRIC',  action: 'metric', param: 5 },
  { id: 'c',  label: 'OPEN CASE · MEDBAYOS',         tag: 'DETAIL',  action: 'detail', param: 'case' },
  { id: 'd',  label: 'OPEN LIVE DASHBOARD BRIEFING', tag: 'DETAIL',  action: 'detail', param: 'dash' },
  { id: 'b',  label: 'READ TODAY\u2019S AUTO-BRIEFING',tag: 'DETAIL',  action: 'detail', param: 'briefing' },
  { id: 'l',  label: 'CONTACT · LINKEDIN',           tag: 'EXTERNAL',action: 'link',   param: 'https://www.linkedin.com/in/john-dahms' },
  { id: 'e',  label: 'CONTACT · EMAIL',              tag: 'EXTERNAL',action: 'link',   param: 'mailto:john.dahms@outlook.de' },
  { id: 't',  label: 'TOGGLE MOTION',                tag: 'SYSTEM',  action: 'toggle', param: 'motion' },
  { id: 'r',  label: 'RANDOMIZE ACCENT HUE',         tag: 'SYSTEM',  action: 'randAccent' },
];

const Palette = ({ open, setOpen }) => {
  const [q, setQ] = useState('');
  const [sel, setSel] = useState(0);
  const inputRef = useRef(null);

  const filtered = useMemo(() => {
    if (!q.trim()) return COMMANDS;
    const qn = q.toLowerCase();
    return COMMANDS.filter((c) => (c.label + ' ' + c.tag).toLowerCase().includes(qn));
  }, [q]);

  useEffect(() => { setSel(0); }, [q]);

  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => inputRef.current?.focus());
    } else {
      setQ('');
    }
  }, [open]);

  const run = (cmd) => {
    if (!cmd) return;
    switch (cmd.action) {
      case 'metric':
        window.dispatchEvent(new CustomEvent('signal:metric', { detail: cmd.param }));
        break;
      case 'detail':
        window.dispatchEvent(new CustomEvent('signal:detail', { detail: cmd.param }));
        break;
      case 'link':
        window.open(cmd.param, cmd.param.startsWith('mailto:') ? '_self' : '_blank', 'noopener');
        break;
      case 'toggle':
        if (cmd.param === 'motion') {
          const cur = window.__TWEAKS__?.motion !== false;
          window.dispatchEvent(new CustomEvent('tweak:update', { detail: { motion: !cur } }));
        }
        break;
      case 'randAccent':
        window.dispatchEvent(new CustomEvent('tweak:update', { detail: { accentHue: Math.floor(Math.random() * 360) } }));
        break;
    }
    setOpen(false);
  };

  useEffect(() => {
    const onKey = (e) => {
      if (!open) return;
      if (e.key === 'Escape') { setOpen(false); e.preventDefault(); }
      if (e.key === 'ArrowDown') { setSel((s) => (s + 1) % filtered.length); e.preventDefault(); }
      if (e.key === 'ArrowUp') { setSel((s) => (s - 1 + filtered.length) % filtered.length); e.preventDefault(); }
      if (e.key === 'Enter') { run(filtered[sel]); e.preventDefault(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, filtered, sel]);

  if (!open) return null;

  return (
    <div className="palette-backdrop" onClick={(e) => { if (e.target.classList.contains('palette-backdrop')) setOpen(false); }}>
      <div className="palette" role="dialog" aria-label="Command palette">
        <input
          ref={inputRef}
          className="palette-input"
          placeholder="query signal. type a command…"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <div className="palette-results">
          {filtered.length === 0 && (
            <div className="palette-item" style={{ color: 'var(--ink-faint)' }}>
              <span className="prefix">—</span>no matching signal
            </div>
          )}
          {filtered.map((c, i) => (
            <div
              key={c.id}
              className={`palette-item ${i === sel ? 'on' : ''}`}
              onMouseEnter={() => setSel(i)}
              onClick={() => run(c)}
            >
              <span className="prefix">{i === sel ? '›' : ' '}</span>
              <span>{c.label}</span>
              <span className="tag">{c.tag}</span>
            </div>
          ))}
        </div>
        <div className="palette-footer">
          <span><kbd>↑</kbd><kbd>↓</kbd> navigate</span>
          <span><kbd>↵</kbd> execute</span>
          <span><kbd>esc</kbd> close</span>
        </div>
      </div>
    </div>
  );
};

window.Palette = Palette;
