// Cmd+K — global search across all sections + their items.

function buildSearchIndex() {
  const idx = [];
  (window.SECTIONS || []).forEach((s) => {
    idx.push({
      kind: 'section', id: s.id, sectionId: s.id,
      title: s.name, sub: s.tagline,
      tag: `EP ${String(s.episodeNum || 1).padStart(2,'0')}`,
      color: s.colorHex, _hay: `${s.name} ${s.tagline} ${s.synopsis}`.toLowerCase(),
    });
    (s.rows || []).forEach((row) => {
      (row.items || []).forEach((it) => {
        const title = it.title || it.company || '';
        const sub = it.sub || it.bullets?.[0] || row.title;
        if (!title) return;
        idx.push({
          kind: 'item', id: `${s.id}:${title}`, sectionId: s.id,
          title, sub,
          tag: s.name,
          color: s.colorHex, _hay: `${title} ${sub} ${s.name} ${row.title}`.toLowerCase(),
        });
      });
    });
  });
  return idx;
}

function CmdK({ open, onClose, onPick }) {
  const [q, setQ] = React.useState('');
  const [cursor, setCursor] = React.useState(0);
  const inputRef = React.useRef(null);
  const idx = React.useMemo(buildSearchIndex, []);

  React.useEffect(() => {
    if (open) {
      setQ(''); setCursor(0);
      setTimeout(() => inputRef.current?.focus(), 30);
    }
  }, [open]);

  const results = React.useMemo(() => {
    const query = q.trim().toLowerCase();
    if (!query) {
      // show sections first when empty
      return idx.filter(r => r.kind === 'section');
    }
    return idx.filter(r => r._hay.includes(query)).slice(0, 18);
  }, [q, idx]);

  React.useEffect(() => { setCursor(0); }, [q]);

  const onKey = (e) => {
    if (e.key === 'Escape') { e.preventDefault(); onClose(); }
    if (e.key === 'ArrowDown') { e.preventDefault(); setCursor(c => Math.min(c+1, results.length-1)); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setCursor(c => Math.max(c-1, 0)); }
    if (e.key === 'Enter') {
      e.preventDefault();
      const r = results[cursor]; if (r) { onPick(r.sectionId); onClose(); }
    }
  };

  if (!open) return null;

  return (
    <div className="ck-backdrop" onClick={onClose}>
      <div className="ck-panel" onClick={(e) => e.stopPropagation()}>
        <div className="ck-head">
          <span className="ck-icon">⌕</span>
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={onKey}
            placeholder="Search episodes, skills, projects…"
            className="ck-input"
          />
          <kbd className="ck-kbd">esc</kbd>
        </div>

        <div className="ck-list" role="listbox">
          {results.length === 0 && (
            <div className="ck-empty">No results for "{q}" — try "ads", "react", "campaign"</div>
          )}
          {results.map((r, i) => (
            <button
              key={r.id}
              className={`ck-row ${i === cursor ? 'is-cursor' : ''}`}
              onMouseEnter={() => setCursor(i)}
              onClick={() => { onPick(r.sectionId); onClose(); }}
            >
              <span className="ck-dot" style={{ background: r.color }}/>
              <span className="ck-main">
                <span className="ck-row-title">{highlight(r.title, q)}</span>
                <span className="ck-row-sub">{highlight(r.sub, q)}</span>
              </span>
              <span className="ck-tag" style={{ borderColor: r.color, color: r.color }}>{r.tag}</span>
            </button>
          ))}
        </div>

        <div className="ck-foot">
          <span><kbd>↑</kbd><kbd>↓</kbd> navigate</span>
          <span><kbd>↵</kbd> open</span>
          <span><kbd>esc</kbd> close</span>
        </div>
      </div>

      <style>{`
        .ck-backdrop{
          position:fixed; inset:0; z-index: 9000;
          background: rgba(4,6,26,.7);
          backdrop-filter: blur(6px);
          display:flex; align-items:flex-start; justify-content:center;
          padding-top: 12vh;
          animation: ckIn .2s ease both;
        }
        @keyframes ckIn { from { opacity:0; } to { opacity:1; } }
        .ck-panel{
          width: min(640px, 92vw); max-height: 70vh; display:flex; flex-direction:column;
          background: #0a0e2e; border: 1px solid var(--line); border-radius: 18px;
          box-shadow: 0 24px 80px rgba(0,0,0,.5);
          overflow:hidden;
          animation: ckPop .25s cubic-bezier(.3,1.4,.3,1) both;
        }
        @keyframes ckPop { from { opacity:0; transform: translateY(-12px) scale(.97); } to { opacity:1; transform:none; } }
        .ck-head{
          display:flex; align-items:center; gap:12px; padding: 16px 18px;
          border-bottom: 1px solid var(--line);
        }
        .ck-icon{ font-size:20px; color: var(--c-about); }
        .ck-input{
          flex:1; background:transparent; border:0; outline:none; color:var(--paper);
          font: 500 16px/1.3 var(--body); letter-spacing:-.01em;
        }
        .ck-input::placeholder{ color: var(--paper-faint); }
        .ck-kbd, .ck-foot kbd{
          font:700 10px/1 var(--mono); padding:4px 7px; border-radius:5px;
          background: rgba(244,241,232,.08); color: var(--paper-dim);
          border:1px solid var(--line);
        }
        .ck-list{
          overflow-y:auto; flex:1; padding: 6px;
          scrollbar-width:thin;
        }
        .ck-empty{
          padding: 24px; text-align:center; color:var(--paper-faint);
          font: 500 13px/1.4 var(--body);
        }
        .ck-row{
          display:flex; align-items:center; gap:12px; width:100%;
          padding: 10px 12px; border-radius: 10px; text-align:left;
          color: var(--paper);
          transition: background .12s ease;
        }
        .ck-row.is-cursor{ background: rgba(79, 142, 255, .12); }
        .ck-dot{
          width:10px; height:10px; border-radius:50%; flex-shrink:0;
          box-shadow: 0 0 10px currentColor;
        }
        .ck-main{ display:flex; flex-direction:column; gap:2px; flex:1; min-width:0; }
        .ck-row-title{ font: 600 14px/1.2 var(--body); }
        .ck-row-sub{
          font: 500 12px/1.3 var(--body); color: var(--paper-dim);
          white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
        }
        .ck-tag{
          font: 700 10px/1 var(--mono); letter-spacing:.16em; text-transform:uppercase;
          padding: 5px 8px; border-radius: 99px;
          border: 1px solid; background: rgba(4,6,26,.6);
        }
        .ck-foot{
          display:flex; gap:18px; padding: 10px 18px;
          border-top: 1px solid var(--line);
          font: 500 11px/1 var(--mono); color: var(--paper-faint);
        }
        .ck-foot kbd{ margin-right: 4px; }

        .ck-hit{ color: var(--c-about); font-weight:700; }
      `}</style>
    </div>
  );
}

function highlight(text, q) {
  if (!q) return text;
  const i = text.toLowerCase().indexOf(q.toLowerCase());
  if (i < 0) return text;
  return (
    <>
      {text.slice(0, i)}
      <span className="ck-hit">{text.slice(i, i + q.length)}</span>
      {text.slice(i + q.length)}
    </>
  );
}

window.CmdK = CmdK;
