// fantasy/src/manager.jsx — the manager chat.
//
// One conversation with the fantasy manager, shared with Telegram's /ff:
// the transcript lives in users/{uid}/fantasy/chat (the server appends both
// turns; this page only reads it and sends the next message through the
// `fantasyChat` callable). The manager answers from the LIVE STATE block
// the server renders from the snapshot — the same numbers the Dashboard
// shows — so it can quote a pick's certainty but never invent one. There
// is no write path: a recommended move ends with what to do on ESPN or
// Sleeper by hand.

const { useState, useEffect, useRef, useContext } = React;
const { DataContext, useToast, timeAgo } = window.FantasyShared;

const QUICK_PROMPTS = [
  'Set my lineups for this week — every league, slot by slot, and say where you disagree with the app.',
  'What is worth $5 on the wire this week, and what is the claim tree?',
  'Which of my starters are at risk (injury, weather, bye) and who is the pivot?',
  'Recap last week: what did the picks get right and wrong, and what did I leave on the bench?',
];

function Bubble({ m }) {
  const mine = m.role === 'user';
  return (
    <div style={{ display: 'flex', justifyContent: mine ? 'flex-end' : 'flex-start' }}>
      <div style={{
        maxWidth: '82%', padding: '10px 14px', borderRadius: 12, fontSize: 13, lineHeight: 1.5, whiteSpace: 'pre-wrap',
        background: mine ? 'rgba(139,92,246,0.18)' : '#161b22', border: `1px solid ${mine ? 'rgba(139,92,246,0.4)' : '#1e2a3a'}`,
      }}>
        {m.content}
        <div className="muted" style={{ fontSize: 10, marginTop: 6, textAlign: mine ? 'right' : 'left' }}>
          {mine ? 'you' : 'manager'}{m.surface === 'telegram' ? ' · Telegram' : ''}{m.at ? ` · ${timeAgo(m.at)}` : ''}
        </div>
      </div>
    </div>
  );
}

function Manager({ uid, setTab }) {
  const { config, snapshot } = useContext(DataContext);
  const toast = useToast();
  const [messages, setMessages] = useState([]);
  const [draft, setDraft] = useState('');
  const [busy, setBusy] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const endRef = useRef(null);

  const load = async () => {
    try {
      const doc = await db.collection('users').doc(uid).collection('fantasy').doc('chat').get();
      setMessages(doc.exists && Array.isArray(doc.data().messages) ? doc.data().messages : []);
    } catch (e) { toast(e.message || String(e), 'error'); }
    setLoaded(true);
  };
  useEffect(() => { load(); }, [uid]);
  useEffect(() => { if (endRef.current) endRef.current.scrollIntoView({ block: 'end' }); }, [messages.length, busy]);

  const send = async (text) => {
    const message = (text || draft).trim();
    if (!message || busy) return;
    setDraft('');
    setBusy(true);
    setMessages(m => [...m, { role: 'user', content: message, at: Date.now(), surface: 'web' }]);
    try {
      const r = await fns.httpsCallable('fantasyChat')({ message });
      setMessages(m => [...m, { role: 'assistant', content: r.data.reply, at: Date.now(), surface: 'web' }]);
    } catch (e) {
      toast(e.message || String(e), 'error');
      setMessages(m => m.slice(0, -1));
      setDraft(message);
    } finally { setBusy(false); }
  };

  const clear = async () => {
    if (!window.confirm('Clear the manager conversation? The Telegram side shares it.')) return;
    try { await fns.httpsCallable('fantasyChat')({ clear: true }); setMessages([]); toast('Conversation cleared'); }
    catch (e) { toast(e.message || String(e), 'error'); }
  };

  const linked = config && (config.sleeper || (config.espn && config.espn.leagueIds && config.espn.leagueIds.length));
  if (!linked) return (
    <div className="page">
      <div className="empty-state">
        <h3>No platform linked yet</h3>
        <div>The manager answers from your leagues' live state. Link Sleeper or ESPN first.</div>
        <button className="btn-primary" style={{ marginTop: 16 }} onClick={() => setTab('Settings')}>Open Settings</button>
      </div>
    </div>
  );

  return (
    <div className="page">
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
        <div className="page-title" style={{ margin: 0 }}>Manager</div>
        <span className="muted" style={{ fontSize: 12 }}>
          {snapshot ? `answers from the week ${snapshot.week} snapshot, built ${timeAgo(snapshot.builtAt)}` : 'no snapshot yet — sync from Settings first'} · also on Telegram as /ff
        </span>
        <span style={{ flex: 1 }} />
        {messages.length > 0 && <button className="btn-secondary" style={{ fontSize: 11, padding: '4px 10px' }} onClick={clear}>Clear</button>}
      </div>

      <div className="card" style={{ padding: 0, display: 'flex', flexDirection: 'column', minHeight: '60vh' }}>
        <div style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'grid', gap: 10, alignContent: 'start', maxHeight: '62vh' }}>
          {!loaded && <div className="muted" style={{ fontSize: 12 }}>Loading the conversation…</div>}
          {loaded && messages.length === 0 && (
            <div className="muted" style={{ fontSize: 12, lineHeight: 1.6 }}>
              The manager runs on your own doctrine — the $5 rule, the fall-through claim tree, the news tiers — and reads every number from the app: projections under each league's scoring, the three-opinion picks, the wire plan, the news wire and the picks' scored record. It never makes a move; it tells you what to do on the platform.
            </div>
          )}
          {messages.map((m, i) => <Bubble key={i} m={m} />)}
          {busy && <div className="muted" style={{ fontSize: 12, display: 'flex', gap: 8, alignItems: 'center' }}><div className="spinner" style={{ width: 14, height: 14 }} /> thinking…</div>}
          <div ref={endRef} />
        </div>
        <div style={{ borderTop: '1px solid #1e2a3a', padding: 12, display: 'grid', gap: 8 }}>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {QUICK_PROMPTS.map(q => (
              <button key={q} className="btn-secondary" style={{ fontSize: 11, padding: '4px 10px' }} disabled={busy} onClick={() => send(q)}>{q.split(/[—,:]/)[0].trim()}</button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end' }}>
            <textarea
              value={draft}
              onChange={e => setDraft(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder="Who do I start at FLEX? Is Allgeier worth $5? Paste a news item…"
              rows={2}
              style={{ resize: 'vertical', minHeight: 44 }}
              disabled={busy}
            />
            <button className="btn-primary" style={{ flexShrink: 0 }} disabled={busy || !draft.trim()} onClick={() => send()}>Send</button>
          </div>
          <div className="muted" style={{ fontSize: 10 }}>Enter sends, Shift+Enter for a new line. Every recommendation ends with what to do on ESPN or Sleeper yourself — nothing here writes to a platform.</div>
        </div>
      </div>
    </div>
  );
}

window.FantasyViews = Object.assign(window.FantasyViews || {}, { Manager });
