// ViG Command Center — Battle Report Analyzer (paste report → AI analysis)
const { useState: useStateBR, useEffect: useEffectBR, useRef: useRefBR } = React;

const BR_EXAMPLES = [
  {
    label: 'Lost rally (example)',
    text: `Battle Report — Attack
General: Bertrand du Guesclin T16 Ground
March size: 1,200,000
Troop composition: T16 Ground 800K, T15 Ground 200K, T14 Ground 200K
Dragon: Mengzhang
Gear: Ground attack set (Varan)
Result: DEFEAT
Losses: 180,000 troops killed, 95,000 wounded
Enemy: K48 defender, ground wall general, 2.1B power
Notes: Enemy had full trap load. We sent without a trap-buster first.`,
  },
  {
    label: 'Monster hunt (example)',
    text: `Battle Report — Monster Hunt
General: Minamoto no Yoshitsune
March: 900,000 ranged
Dragon: Ziz
Gear: Monster hunting gear
Target: Level 15 Dragon
Result: WIN but low score
Notes: Score was 40% lower than expected. No Monarch gear equipped. Forgot to switch to attack title.`,
  },
];

const BR_QUICK = [
  'What did I do wrong?',
  'What buffs am I missing?',
  'How do I fix this for next time?',
  'What general / dragon should I use instead?',
  'What is the best troop composition for this?',
];

function BattleReportPage() {
  const [report, setReport] = useStateBR(() => LS.get('vig2_br_text', ''));
  const [analysis, setAnalysis] = useStateBR(() => LS.get('vig2_br_result', null));
  const [followup, setFollowup] = useStateBR('');
  const [busy, setBusy] = useStateBR(false);
  const [err, setErr] = useStateBR('');
  const [tab, setTab] = useStateBR('analyze'); // 'analyze' | 'chat'
  const [chat, setChat] = useStateBR(() => LS.get('vig2_br_chat', []));
  const chatRef = useRefBR(null);
  useEffectBR(() => { LS.set('vig2_br_text', report); }, [report]);
  useEffectBR(() => { LS.set('vig2_br_result', analysis); }, [analysis]);
  useEffectBR(() => { LS.set('vig2_br_chat', chat.slice(-20)); }, [chat]);
  useEffectBR(() => { if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight; }, [chat, busy]);

  const ctx = () => {
    const V = window.VIG;
    let own = '';
    try { const owned = (V?.generals||[]).filter(g => {const k=g.type+'|'+g.name; return (LS.get('vig2_ownership',{})||{})[k];}); own = `Player owns ${owned.length} generals including: ${owned.slice(0,8).map(g=>g.name).join(', ')}.`; } catch(e){}
    return own;
  };

  const analyze = async () => {
    if (!report.trim()) { setErr('Paste a battle report first.'); return; }
    setBusy(true); setErr('');
    try {
      const prompt = `You are an expert Evony battle analyst. Analyze this battle report and give structured, actionable feedback.\n\n${ctx()}\n\nBATTLE REPORT:\n${report}\n\nRespond in exactly this structure:\n**OUTCOME SUMMARY** (1 line: what happened and why in plain English)\n\n**MISTAKES** (numbered list, be specific)\n\n**BUFF GAPS** (what buffs were missing or underoptimized — gear, dragon, general, title, research)\n\n**FIX FOR NEXT TIME** (3 specific action steps to improve this exact scenario)\n\n**GENERAL / DRAGON RECOMMENDATION** (better picks if applicable, and why)`;
      const reply = await window.claude.complete(prompt);
      const text = (reply || '').trim();
      setAnalysis({ text, ts: Date.now(), report: report.slice(0, 80) + '…' });
      setChat([]); setTab('analyze');
    } catch (e) { setErr('AI unavailable — needs internet and may be rate-limited.'); }
    finally { setBusy(false); }
  };

  const ask = async (q) => {
    const question = (q || followup).trim();
    if (!question || busy) return;
    setFollowup('');
    const next = [...chat, { role: 'user', content: question }];
    setChat(next); setBusy(true);
    try {
      const history = next.slice(-6).map(m => `${m.role === 'user' ? 'Player' : 'Analyst'}: ${m.content}`).join('\n\n');
      const prompt = `You are an Evony battle analyst. The player shared this battle report and your initial analysis is below. Answer their follow-up question directly and concisely.\n\nBATTLE REPORT:\n${report}\n\nINITIAL ANALYSIS:\n${analysis?.text || 'No analysis yet.'}\n\nCONVERSATION:\n${history}\n\nAnalyst:`;
      const reply = await window.claude.complete(prompt);
      setChat(c => [...c, { role: 'assistant', content: (reply || '').trim() }]);
    } catch (e) { setChat(c => [...c.slice(0, -1), { ...c[c.length - 1], failed: true }]); }
    finally { setBusy(false); }
  };

  const fmt = (s) => s.split('\n').map((line, i) => {
    const t = line.trim();
    if (!t) return <div key={i} className="h-1.5"></div>;
    const parts = t.split(/(\*\*[^*]+\*\*)/g).map((p, j) => p.startsWith('**') && p.endsWith('**') ? <strong key={j} className="font-semibold text-zinc-900 dark:text-white">{p.slice(2, -2)}</strong> : p);
    if (/^\d+\./.test(t)) return <div key={i} className="flex gap-2 py-0.5"><span className="shrink-0 text-brand">{t.match(/^\d+/)[0]}.</span><span className="flex-1">{parts}</span></div>;
    if (/^[-•*]/.test(t)) return <div key={i} className="flex gap-2 py-0.5"><span className="mt-2 h-1 w-1 shrink-0 rounded-full bg-brand"></span><span className="flex-1">{parts}</span></div>;
    return <p key={i} className="py-0.5">{parts}</p>;
  });

  return (
    <div className="space-y-4">
      {/* input */}
      <Card className="overflow-hidden">
        <div className="flex flex-wrap items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <Icon name="database" size={16} className="text-brand" />
          <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Battle report</span>
          <span className="text-[11.5px] text-zinc-400">Paste your battle report text — include generals, troops, dragon, gear, result and any notes</span>
          <div className="ml-auto flex gap-1.5">
            {BR_EXAMPLES.map(e => <button key={e.label} onClick={() => setReport(e.text)} className="rounded-md border border-zinc-200 px-2 py-1 text-[11.5px] font-semibold text-zinc-500 hover:border-brand hover:text-brand dark:border-zinc-700 dark:text-zinc-400">{e.label}</button>)}
          </div>
        </div>
        <div className="p-4">
          <textarea value={report} onChange={e => { setReport(e.target.value); setErr(''); }} rows={7} placeholder={'Paste your battle report here…\n\nInclude:\n• General used + troop composition\n• March size and dragon\n• Gear set\n• Battle result (win/loss)\n• Losses + enemy details\n• Any notes about what happened'} className="w-full resize-none rounded-lg border border-zinc-200 bg-white px-4 py-3 font-mono text-[12.5px] leading-relaxed text-zinc-700 outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200" />
          {err && <div className="mt-1.5 text-[12px] text-rose-500">{err}</div>}
          <div className="mt-3 flex items-center gap-2">
            <button onClick={analyze} disabled={busy || !report.trim()} className="inline-flex items-center gap-1.5 rounded-lg px-4 py-2.5 text-[13.5px] font-bold text-white transition-all hover:brightness-110 disabled:opacity-40" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)', boxShadow: '0 8px 22px -10px rgba(255,107,0,.7)' }}>
              <Icon name={busy && tab === 'analyze' ? 'reset' : 'sparkle'} size={16} className={busy && tab === 'analyze' ? 'animate-spin' : ''} />{busy && tab === 'analyze' ? 'Analyzing…' : 'Analyze report'}
            </button>
            {report.trim() && <button onClick={() => { setReport(''); setAnalysis(null); setChat([]); setErr(''); }} className="rounded-lg border border-zinc-200 px-3 py-2 text-[12.5px] font-semibold text-zinc-500 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800"><Icon name="x" size={13} className="inline mr-1" />Clear</button>}
          </div>
        </div>
      </Card>

      {/* results */}
      {analysis && (
        <Card className="overflow-hidden border-brand/20">
          <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800">
            <div className="flex gap-0.5">
              {[['analyze', '📋 Analysis'], ['chat', '💬 Follow-up']].map(([id, label]) => (
                <button key={id} onClick={() => setTab(id)} className={`-mb-px rounded-t-lg border-b-2 px-3 py-1.5 text-[12.5px] font-semibold transition-colors ${tab === id ? 'border-brand text-brand' : 'border-transparent text-zinc-400 hover:text-zinc-600'}`}>{label}</button>
              ))}
            </div>
            <span className="ml-auto text-[10.5px] text-zinc-400">{analysis.report}</span>
          </div>

          {tab === 'analyze' && (
            <div className="p-5 text-[13px] leading-relaxed text-zinc-700 dark:text-zinc-200">
              {fmt(analysis.text)}
            </div>
          )}

          {tab === 'chat' && (
            <div className="flex flex-col">
              {/* quick prompts */}
              {chat.length === 0 && (
                <div className="flex flex-wrap gap-2 p-4">
                  {BR_QUICK.map(q => <button key={q} onClick={() => ask(q)} className="rounded-lg border border-zinc-200 px-3 py-2 text-[12px] font-medium text-zinc-600 transition-colors hover:border-brand hover:text-brand dark:border-zinc-700 dark:text-zinc-300">{q}</button>)}
                </div>
              )}
              {/* chat */}
              {chat.length > 0 && (
                <div ref={chatRef} className="max-h-72 space-y-3 overflow-y-auto p-4">
                  {chat.map((m, i) => (
                    <div key={i} className={`flex gap-2.5 ${m.role === 'user' ? 'justify-end' : ''}`}>
                      {m.role === 'assistant' && <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="sparkle" size={14} className="text-white" /></div>}
                      <div className={`max-w-[80%] rounded-2xl px-3.5 py-2.5 text-[13px] leading-relaxed ${m.role === 'user' ? 'bg-brand text-white' : 'bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-200'} ${m.failed ? 'opacity-50' : ''}`}>
                        {m.role === 'assistant' ? <div>{fmt(m.content)}</div> : m.content}
                      </div>
                    </div>
                  ))}
                  {busy && tab === 'chat' && <div className="flex gap-2.5"><div className="flex h-7 w-7 items-center justify-center rounded-lg" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="sparkle" size={14} className="text-white" /></div><div className="flex items-center gap-1 rounded-2xl bg-zinc-100 px-4 py-3 dark:bg-zinc-800"><span className="ai-dot"></span><span className="ai-dot" style={{ animationDelay: '.15s' }}></span><span className="ai-dot" style={{ animationDelay: '.3s' }}></span></div></div>}
                </div>
              )}
              {/* input */}
              <div className="flex items-end gap-2 border-t border-zinc-100 p-3 dark:border-zinc-800">
                <textarea value={followup} onChange={e => setFollowup(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); ask(); } }} rows={1} placeholder="Ask a follow-up…" className="max-h-20 flex-1 resize-none bg-transparent px-2 py-1.5 text-[13px] outline-none placeholder:text-zinc-400" />
                <button onClick={() => ask()} disabled={busy || !followup.trim()} className="flex h-8 w-8 items-center justify-center rounded-xl text-white disabled:opacity-40" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="arrow" size={16} className="-rotate-90" /></button>
              </div>
            </div>
          )}
        </Card>
      )}

      {!analysis && !busy && <Card className="py-10 text-center"><div className="text-3xl">🛡️</div><div className="mt-2 text-[13px] font-semibold text-zinc-700 dark:text-zinc-200">Paste a battle report above</div><div className="mt-1 text-[12px] text-zinc-400">The AI will identify mistakes, buff gaps, and give specific fixes for your next battle.</div></Card>}
      <p className="px-1 text-[11.5px] text-zinc-400">Paste any battle report text — the more detail you include (general, troops, gear, dragon, result, losses, enemy details), the more precise the analysis. Use "Follow-up" to ask specific questions about the report or how to improve.</p>
    </div>
  );
}
window.BattleReportPage = BattleReportPage;
