// Command palette: ⌘K / Ctrl-K
function CommandPalette({ open, onClose, palette, onSetPalette }) {
  const [q, setQ] = React.useState('');
  const [sel, setSel] = React.useState(0);
  const [view, setView] = React.useState('main');
  const inputRef = React.useRef(null);

  const actions = React.useMemo(() => {
    const go = (id) => () => {
      onClose();
      setTimeout(() => {
        const el = document.getElementById(id);
        if (el) el.scrollIntoView ? window.scrollTo({ top: el.offsetTop - 40, behavior: 'smooth' }) : null;
      }, 40);
    };
    return [
      { k: 'nav', label: 'Go to About', hint: '02', action: go('about') },
      { k: 'nav', label: 'Go to Selected work', hint: '03', action: go('work') },
      { k: 'nav', label: 'Go to Writing', hint: '04', action: go('writing') },
      { k: 'nav', label: 'Go to Stack', hint: '05', action: go('skills') },
      { k: 'nav', label: 'Go to Resume', hint: '06', action: go('resume') },
      { k: 'action', label: 'Change theme', hint: '→', action: () => { setView('theme'); setQ(''); setSel(0); } },
      { k: 'link', label: 'Email: bleach@gmail.com', hint: '✉', action: () => { window.location.href = 'mailto:bleach@gmail.com'; onClose(); } },
      { k: 'link', label: 'LinkedIn · /in/bleach', hint: '↗', action: () => { window.open('https://www.linkedin.com/in/bleach/', '_blank'); onClose(); } },
      ...(window.POSTS || []).map((p) => ({
        k: 'post', label: p.title, hint: p.date, action: () => { window.open(p.href, '_blank'); onClose(); },
      })),
      ...(window.PROJECTS || []).map((p) => ({
        k: 'work',
        label: p.title + ' · ' + p.tag,
        hint: p.year,
        action: () => {
          onClose();
          setTimeout(() => {
            const el = document.getElementById('work');
            if (el) el.scrollIntoView({ behavior: 'smooth' });
          }, 40);
        },
      })),
    ];
  }, [onClose, onSetPalette]);

  const themeActions = React.useMemo(() => {
    return Object.entries(window.V4_PALETTES || {}).map(([k, p]) => ({
      k: 'theme',
      label: p.label,
      hint: palette === k ? '● active' : '',
      action: () => { onSetPalette(k); },
    }));
  }, [palette, onSetPalette]);

  const isThemeView = view === 'theme';
  const baseItems = isThemeView ? themeActions : actions;

  const filtered = React.useMemo(() => {
    const s = q.trim().toLowerCase();
    if (!s) return baseItems;
    return baseItems.filter((a) => a.label.toLowerCase().includes(s) || a.k.includes(s));
  }, [q, baseItems]);

  React.useEffect(() => { setSel(0); }, [q, open, view]);
  React.useEffect(() => {
    if (open) {
      setView('main');
      setQ('');
      setTimeout(() => inputRef.current && inputRef.current.focus(), 20);
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') {
        if (isThemeView) { setView('main'); setQ(''); setSel(0); }
        else onClose();
      }
      else if (e.key === 'Backspace' && q === '' && isThemeView) { setView('main'); setSel(0); }
      else if (e.key === 'ArrowDown') { e.preventDefault(); setSel((s) => Math.min(s + 1, filtered.length - 1)); }
      else if (e.key === 'ArrowUp') { e.preventDefault(); setSel((s) => Math.max(s - 1, 0)); }
      else if (e.key === 'Enter') {
        e.preventDefault();
        const a = filtered[sel];
        if (a) a.action();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, filtered, sel, isThemeView, q]);

  if (!open) return null;

  return (
    <div className="cmdk-scrim" onClick={onClose}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()} role="dialog" aria-label="Command palette">
        <div className="cmdk-input-row">
          {isThemeView && (
            <button className="cmdk-back" onClick={() => { setView('main'); setQ(''); setSel(0); }}>←</button>
          )}
          <span className="cmdk-glyph">{isThemeView ? '🎮' : '⌘'}</span>
          <input
            ref={inputRef}
            className="cmdk-input"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder={isThemeView ? 'Select a theme...' : 'Search pages, posts, actions…'}
          />
          <kbd className="kbd-inline">esc</kbd>
        </div>
        <div className="cmdk-list">
          {filtered.length === 0 && <div className="cmdk-empty mono small muted">no matches</div>}
          {filtered.map((a, i) => (
            <div
              key={i}
              className={'cmdk-item' + (i === sel ? ' sel' : '')}
              onMouseEnter={() => setSel(i)}
              onClick={() => a.action()}
            >
              <span className={'cmdk-kind k-' + a.k}>{a.k}</span>
              <span className="cmdk-label">{a.label}</span>
              <span className="cmdk-hint mono small muted">{a.hint}</span>
            </div>
          ))}
        </div>
        <div className="cmdk-foot mono small muted">
          <span>↑↓ navigate</span>
          <span>↵ select</span>
          <span>{isThemeView ? 'esc back' : 'esc close'}</span>
        </div>
      </div>
    </div>
  );
}

window.CommandPalette = CommandPalette;
