// Scout — recommendations on YOUR terms. Nothing is pushed into the feed;
// you open this box, you say what you're looking for, you get a short list,
// you close the box. The opposite of an algorithmic rabbit hole.

const { useState: useStateSc } = React;

const SCOUT_MODES = [
  { id: 'similar', label: 'More like my feed', hint: 'closest to what I already follow' },
  { id: 'adjacent', label: 'Adjacent but new', hint: 'a step sideways from my usual' },
  { id: 'specific', label: 'Something specific', hint: 'I will describe it myself' },
];

function Scout({ state, dispatch }) {
  const [mode, setMode] = useStateSc('similar');
  const [query, setQuery] = useStateSc('');
  const [status, setStatus] = useStateSc('idle'); // idle | loading | ready | error
  const [items, setItems] = useStateSc([]);
  const [error, setError] = useStateSc(null);

  const close = () => dispatch({ type: 'close-scout' });

  const run = async () => {
    if (status === 'loading') return;
    if (mode === 'specific' && !query.trim()) return;
    setStatus('loading');
    setError(null);
    try {
      const channels = state.channels
        .filter(c => c.id !== 'c-singles')
        .map(c => ({ name: c.name, handle: c.handle, desc: (c.desc || '').slice(0, 140), tags: c.tags || [] }));
      const watchedTitles = state.videos
        .filter(v => state.watched.has(v.id) || v.watched)
        .sort((a, b) => b.publishedAt - a.publishedAt)
        .slice(0, 20)
        .map(v => v.title);
      const r = await fetch('/api/recommend', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode, query: query.trim(), channels, watchedTitles }),
      });
      const body = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(body?.error || `Scout failed (${r.status})`);
      setItems(body.items || []);
      setStatus('ready');
    } catch (e) {
      setError(String(e?.message || e));
      setStatus('error');
    }
  };

  const follow = (it) => {
    dispatch({ type: 'close-scout' });
    if (it.type === 'video' && it.youtubeId) {
      dispatch({ type: 'open-add', url: `https://www.youtube.com/watch?v=${it.youtubeId}`, intent: 'single' });
    } else {
      const handle = (it.handle || '').trim();
      if (!handle) return;
      dispatch({ type: 'open-add', url: handle.startsWith('@') ? handle : '@' + handle });
    }
  };

  return (
    <div className="modal-back" onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className="modal modal-scout">
        <div className="modal-head">
          <span>◢ SCOUT · RECOMMENDATIONS ON YOUR TERMS</span>
          <button className="x" onClick={close}>✕</button>
        </div>
        <div className="modal-body">
          <div className="modal-step-label">YOU ASK. IT ANSWERS. THEN IT'S GONE.</div>
          <h2 className="modal-title">What are you looking for?</h2>
          <p className="modal-desc">
            Scout reads your channels and watch history only when you press the button.
            It suggests, you decide, nothing enters your feed by itself.
          </p>

          <div className="scout-modes">
            {SCOUT_MODES.map(m => (
              <button
                key={m.id}
                className={`scout-mode ${mode === m.id ? 'on' : ''}`}
                onClick={() => setMode(m.id)}
              >
                <span className="scout-mode-label">{m.label}</span>
                <span className="scout-mode-hint">{m.hint}</span>
              </button>
            ))}
          </div>

          <input
            className="url"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') run(); }}
            placeholder={mode === 'specific'
              ? 'e.g. patient explanations of analog electronics'
              : 'Optional: narrow it down…'}
          />

          {status === 'loading' && (
            <div className="scout-loading">
              <span className="brief-spinner"></span>
              <span>Scouting — reading your channels, looking sideways…</span>
            </div>
          )}

          {status === 'error' && (
            <div className="brief-error" style={{ marginTop: 16 }}>
              Couldn't scout right now — {error}
            </div>
          )}

          {status === 'ready' && (
            <div className="scout-results">
              {items.length === 0 && (
                <div className="scout-empty">Nothing confident enough to suggest. Try a different angle.</div>
              )}
              {items.map((it, i) => (
                <div key={i} className={`scout-item ${it.type === 'video' ? 'scout-item-is-video' : ''}`}>
                  <div className="scout-item-idx">{String(i + 1).padStart(2, '0')}</div>
                  <div className="scout-item-body">
                    <div className="scout-item-name">
                      {it.type === 'video' ? it.title : it.name}
                      {it.type === 'video'
                        ? <span className="scout-item-handle">{it.channelHandle || it.channelName}</span>
                        : it.handle && <span className="scout-item-handle">{it.handle}</span>
                      }
                    </div>
                    {it.type === 'video' && <span className="scout-item-type">video</span>}
                    <div className="scout-item-why">{it.why}</div>
                  </div>
                  <button className="scout-item-add" onClick={() => follow(it)}>
                    {it.type === 'video' ? 'save →' : 'follow →'}
                  </button>
                </div>
              ))}
              <div className="scout-disclaimer">
                AI suggestions — verify channels and video IDs before adding.
              </div>
            </div>
          )}
        </div>
        <div className="modal-foot">
          <span>ESC to close · nothing is saved unless you follow</span>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn-ghost" onClick={close}>Close</button>
            <button className="btn-primary" disabled={status === 'loading' || (mode === 'specific' && !query.trim())} onClick={run}>
              {status === 'ready' ? 'Scout again' : 'Scout'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Scout = Scout;
