// views/agent.jsx — WorldCupAI. A chat assistant grounded in the app's data,
// powered by window.claude.complete.
function AgentView({ onRoute }) {
  const [messages, setMessages] = React.useState([
    { role: 'bot', text: "I'm WorldCupAI — ask me anything about the 2026 tournament, any edition since 1930, records, teams, or how this app's model works." },
  ]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

  const suggestions = [
    'Who are the favourites for 2026?',
    'Which nations have won the most World Cups?',
    'What\u2019s new about the 2026 format?',
    'Tell me about the 1950 Maracanazo',
  ];

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, busy]);

  function buildContext() {
    const A = window.WCL_ALLTIME, M = window.WCL_2026.meta;
    const champs = A.championsByNation.map(c => `${window.WCL_TEAMS[c.team]?.name || c.team} (${c.titles})`).join(', ');
    const odds = window.WCL_TROPHY_ODDS.slice(0, 6).map(o => `${window.WCL_TEAMS[o.team]?.name || o.team} ${(o.model*100).toFixed(1)}%`).join(', ');
    return [
      'You are WorldCupAI, the assistant inside "World Cup Live", a football stats app. Answer concisely (2-4 short paragraphs max), knowledgeably and warmly. Use only well-established football facts.',
      `2026 tournament: hosts ${M.hosts.join(', ')}; ${M.teams} teams, ${M.matches} matches, ${M.days} days (${M.startDate} to ${M.endDate}); format: ${M.format}; defending champions Argentina.`,
      `All-time champions by titles: ${champs}.`,
      `This app's model currently favours, to win 2026: ${odds}.`,
    ].join('\n');
  }

  async function send(text) {
    const q = (text != null ? text : input).trim();
    if (!q || busy) return;
    setInput('');
    const next = [...messages, { role: 'user', text: q }];
    setMessages(next);
    setBusy(true);
    try {
      const history = next.filter(m => m.role !== 'bot' || m.text !== messages[0].text)
        .map(m => `${m.role === 'user' ? 'User' : 'WorldCupAI'}: ${m.text}`).join('\n');
      const prompt = `${buildContext()}\n\nConversation so far:\n${history}\n\nWrite WorldCupAI's next reply (plain text, no preamble):`;
      const reply = await window.claude.complete(prompt);
      setMessages(m => [...m, { role: 'bot', text: (reply || '').trim() || 'Sorry — I couldn\u2019t generate a reply just then. Try rephrasing?' }]);
    } catch (e) {
      setMessages(m => [...m, { role: 'bot', text: 'I hit an error reaching the model. This assistant runs live in the browser — try again in a moment.' }]);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="breadcrumb" style={{ display: 'flex', gap: 6, color: 'var(--foreground-muted)', fontSize: 12, marginBottom: 8 }}>
            <a className="link" onClick={() => onRoute('home')}>Home</a><I.ChevR size={12} /><span>Agent</span>
          </div>
          <h1 className="type-h1" style={{ margin: 0, display: 'flex', alignItems: 'center', gap: 12 }}>
            WorldCupAI
            <span className="hd-pulse" style={{ background: 'color-mix(in oklch, var(--pitch) 18%, transparent)', borderColor: 'color-mix(in oklch, var(--pitch) 40%, transparent)', color: 'var(--pitch)' }}><span className="dot" style={{ background: 'var(--pitch)' }} /> ONLINE</span>
          </h1>
          <div className="sub">Grounded in this app&rsquo;s data — 2026, every past edition, and the model.</div>
        </div>
      </div>

      <section className="panel" style={{ display: 'flex', flexDirection: 'column' }}>
        <div className="chat-wrap">
          <div className="chat-scroll" ref={scrollRef}>
            {messages.map((m, i) => (
              <div key={i} className={'chat-msg ' + (m.role === 'user' ? 'user' : 'bot')}>
                <div className={'chat-av ' + (m.role === 'user' ? 'user' : 'bot')}>
                  {m.role === 'user' ? 'You' : <SoccerBall size={18} />}
                </div>
                <div className="chat-bubble">{m.text}</div>
              </div>
            ))}
            {busy && (
              <div className="chat-msg bot">
                <div className="chat-av bot"><SoccerBall size={18} /></div>
                <div className="chat-bubble typing"><span /><span /><span /></div>
              </div>
            )}
          </div>

          {messages.length <= 1 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, padding: '4px 2px 14px' }}>
              {suggestions.map(s => (
                <button key={s} className="chat-suggest" onClick={() => send(s)}><I.Sparkle size={13} /> {s}</button>
              ))}
            </div>
          )}

          <form className="chat-input" onSubmit={e => { e.preventDefault(); send(); }}>
            <input
              className="input"
              style={{ flex: 1, height: 40 }}
              placeholder="Ask about teams, matches, history, records…"
              value={input}
              onChange={e => setInput(e.target.value)}
              disabled={busy}
            />
            <button className="btn btn-primary" type="submit" disabled={busy || !input.trim()} style={{ height: 40, paddingInline: 16 }}>
              <I.Send size={15} /> Send
            </button>
          </form>
        </div>
      </section>

      <div className="subtle" style={{ fontSize: 11, marginTop: 10, textAlign: 'center' }}>
        WorldCupAI can make mistakes. Verify critical facts on the <a className="link" onClick={() => onRoute('stats')}>statistics</a> and <a className="link" onClick={() => onRoute('guide')}>guide</a> pages.
      </div>
    </div>
  );
}
Object.assign(window, { AgentView });
