// ViG Command Center — War Simulator (AI + stat-based outcome prediction)
const { useState: useStateWS, useMemo: useMemoWS, useEffect: useEffectWS } = React;

const WS_METRICS = [
  ['power', 'Total power (B)', 1, 5000],
  ['members', 'Active members', 1, 300],
  ['k49pct', 'K49+ share (%)', 0, 100],
  ['momentum', 'Growth momentum (%)', -50, 100],
  ['rally', 'Rally capacity (B)', 0, 100],
];

function wsScore(a) {
  const p = (a.power || 0) / 5000;
  const m = (a.members || 0) / 300;
  const k = (a.k49pct || 0) / 100;
  const mo = Math.max(0, (a.momentum || 0)) / 100;
  const r = (a.rally || 0) / 100;
  return 0.40 * p + 0.15 * m + 0.20 * k + 0.15 * mo + 0.10 * r;
}

const WS_SEED_TEAMS = [
  { id: 'VIG', name: 'VIG', color: '#FF6B00', power: 1891, members: 120, k49pct: 58, momentum: 6.3, rally: 42 },
  { id: 'RSP', name: 'RSP', color: '#3B82F6', power: 1764, members: 105, k49pct: 48, momentum: 4.1, rally: 36 },
  { id: 'NEF', name: 'NEF', color: '#A855F7', power: 1750, members: 115, k49pct: 44, momentum: 5.8, rally: 30 },
];

function WsTeamCard({ team, onChange }) {
  return (
    <div className="rounded-xl border border-zinc-200 p-4 dark:border-zinc-700" style={{ borderTop: `3px solid ${team.color}` }}>
      <div className="mb-3 flex items-center gap-2">
        <span className="flex h-7 w-7 items-center justify-center rounded-lg text-[13px] font-extrabold text-white" style={{ background: team.color }}>{team.id}</span>
        <span className="text-[14px] font-bold text-zinc-900 dark:text-white">{team.name}</span>
      </div>
      <div className="space-y-2.5">
        {WS_METRICS.map(([key, label, min, max]) => (
          <div key={key}>
            <div className="mb-1 flex items-center justify-between text-[11px]">
              <span className="font-semibold uppercase tracking-wide text-zinc-400">{label}</span>
              <span className="tabular-nums font-bold" style={{ color: team.color }}>{team[key]}{key === 'power' ? 'B' : key === 'members' ? '' : '%'}</span>
            </div>
            <input type="range" min={min} max={max} step={key === 'power' ? 10 : key === 'members' ? 5 : 1} value={team[key]}
              onChange={e => onChange(key, +e.target.value)}
              className="w-full" style={{ accentColor: team.color }} />
          </div>
        ))}
      </div>
    </div>
  );
}

function WarSimulatorPage() {
  const A = window.ALLIANCE;
  const seed = useMemoWS(() => {
    if (!A || !A.alliances) return WS_SEED_TEAMS;
    return A.alliances.map((al, i) => ({
      id: al.id, name: al.id, color: al.accent,
      power: Math.round(al.power), members: al.memberCount || al.players.length,
      k49pct: Math.round(ALCALC ? ALCALC.k49share(al) : 50),
      momentum: ALCALC ? Math.round(ALCALC.momentum(al) * 10) / 10 : 5,
      rally: Math.round(al.power * 0.022),
    }));
  }, [A]);

  const [teams, setTeams] = useStateWS(() => LS.get('vig2_ws_teams', null) || seed);
  const [aiPred, setAiPred] = useStateWS(() => LS.get('vig2_ws_pred', null));
  const [busy, setBusy] = useStateWS(false);
  const [err, setErr] = useStateWS('');
  const [scenario, setScenario] = useStateWS('svs');
  const SCENARIOS = [['svs', '⚔️ Server vs Server'], ['boc', '🏛️ Battle of Constantinople'], ['bog', '🌲 Battle of Gaul']];
  useEffectWS(() => { LS.set('vig2_ws_teams', teams); }, [teams]);

  const update = (i, key, val) => setTeams(ts => ts.map((t, j) => j === i ? { ...t, [key]: val } : t));
  const reset = () => { setTeams(seed); LS.set('vig2_ws_teams', seed); };

  const scores = useMemoWS(() => {
    const raw = teams.map(t => ({ id: t.id, color: t.color, s: wsScore(t) }));
    const max = Math.max(...raw.map(r => r.s));
    return raw.map(r => ({ ...r, pct: Math.round(r.s / max * 100) })).sort((a, b) => b.s - a.s);
  }, [teams]);
  const leader = scores[0];
  const gap = scores.length >= 2 ? Math.round((scores[0].s - scores[1].s) / scores[1].s * 100) : 0;

  const simulate = async () => {
    setBusy(true); setErr('');
    try {
      const lines = teams.map((t, i) => `${t.id} (rank #${i + 1} before sim): ${t.power}B power, ${t.members} active members, ${t.k49pct}% K49+, momentum ${t.momentum}%, rally cap ${t.rally}B, sim score ${Math.round(wsScore(t) * 100)}`).join('\n');
      const prompt = `You are an Evony war analyst. Three alliances are entering a ${SCENARIOS.find(s => s[0] === scenario)[1]}.\n\n${lines}\n\nGive a crisp simulation result in EXACTLY this format, one line each:\nWINNER: <alliance> — <one sharp reason>\nMARGIN: <Decisive/Close/Coin flip>\nTURNING POINT: <the key factor that decides it>\nOVERTAKE RISK: <which second-place alliance could surprise, and under what condition>\nCONFIDENCE: <High/Medium/Low>`;
      const reply = await window.claude.complete(prompt);
      const text = (reply || '').trim();
      setAiPred({ text, ts: Date.now(), scenario });
      LS.set('vig2_ws_pred', { text, ts: Date.now(), scenario });
    } catch (e) { setErr('AI unavailable — needs internet and may be rate-limited.'); }
    finally { setBusy(false); }
  };

  const predLines = aiPred ? aiPred.text.split('\n').map(l => l.trim()).filter(Boolean) : [];
  const PRED_COLORS = { winner: '#34d399', margin: '#60a5fa', 'turning point': '#fbbf24', 'overtake risk': '#fb7185', confidence: '#FF6B00' };

  return (
    <div className="space-y-4">
      {/* stat bar */}
      <Card className="overflow-hidden">
        <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <Icon name="target" size={16} className="text-brand" />
          <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Strength comparison</span>
          <div className="ml-auto flex gap-1.5">
            {SCENARIOS.map(([id, label]) => <button key={id} onClick={() => setScenario(id)} className={`rounded-md border px-2.5 py-1 text-[11.5px] font-semibold transition-colors ${scenario === id ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-500 dark:border-zinc-700 dark:text-zinc-400'}`}>{label}</button>)}
          </div>
        </div>
        <div className="space-y-3 p-4">
          {scores.map((s, i) => (
            <div key={s.id} className="flex items-center gap-3">
              <span className={`w-5 text-center text-[13px] font-bold tabular-nums ${i === 0 ? 'text-brand' : 'text-zinc-400'}`}>{i + 1}</span>
              <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-[12px] font-bold text-white" style={{ background: s.color }}>{s.id}</span>
              <div className="h-2.5 flex-1 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="h-full rounded-full" style={{ width: s.pct + '%', background: s.color, boxShadow: `0 0 10px ${s.color}88` }}></div></div>
              <span className="w-10 text-right text-[13px] font-bold tabular-nums" style={{ color: s.color }}>{s.pct}</span>
            </div>
          ))}
          <div className="flex flex-wrap items-center gap-2 pt-1 text-[12px]">
            <span className="font-bold" style={{ color: leader.color }}>{leader.id}</span><span className="text-zinc-500 dark:text-zinc-400">leads by <b className="text-zinc-700 dark:text-zinc-200">{gap}%</b> · simulate below for AI analysis</span>
          </div>
        </div>
      </Card>

      {/* team sliders */}
      <div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
        {teams.map((t, i) => <WsTeamCard key={t.id} team={t} onChange={(key, val) => update(i, key, val)} />)}
      </div>

      {/* simulate button */}
      <div className="flex flex-wrap items-center gap-3">
        <button onClick={simulate} disabled={busy} 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-50" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)', boxShadow: '0 8px 22px -10px rgba(255,107,0,.7)' }}>
          <Icon name={busy ? 'reset' : 'sparkle'} size={16} className={busy ? 'animate-spin' : ''} />{busy ? 'Simulating…' : 'Run AI simulation'}
        </button>
        <button onClick={reset} className="rounded-lg border border-zinc-200 px-3.5 py-2 text-[12.5px] font-semibold text-zinc-600 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800"><Icon name="reset" size={13} className="inline mr-1" />Reset to live data</button>
        {err && <div className="text-[12px] text-rose-500">{err}</div>}
      </div>

      {/* AI result */}
      {aiPred && (
        <Card className="overflow-hidden border-brand/30">
          <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800">
            <Icon name="sparkle" size={15} className="text-brand" />
            <span className="text-[12.5px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Simulation result · {SCENARIOS.find(s => s[0] === aiPred.scenario)?.[1] || aiPred.scenario}</span>
            <span className="text-[10.5px] text-zinc-400">{syncTimeAgo ? syncTimeAgo(aiPred.ts) : ''}</span>
            <button onClick={() => { setAiPred(null); LS.set('vig2_ws_pred', null); }} className="ml-auto text-[11.5px] text-zinc-400 hover:text-brand">Dismiss</button>
          </div>
          <div className="space-y-2.5 p-4">
            {predLines.map((l, i) => {
              const [k, ...rest] = l.split(':'); const v = rest.join(':').trim();
              const key = k.trim().toLowerCase();
              const tone = PRED_COLORS[key];
              if (!tone) return <p key={i} className="text-[13px] text-zinc-600 dark:text-zinc-300">{l}</p>;
              return (
                <div key={i} className="flex flex-wrap items-baseline gap-2">
                  <span className="rounded px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide" style={{ background: tone + '22', color: tone }}>{k.trim()}</span>
                  <span className="flex-1 text-[13px] font-medium text-zinc-800 dark:text-zinc-100">{v}</span>
                </div>
              );
            })}
          </div>
        </Card>
      )}
      <p className="px-1 text-[11.5px] text-zinc-400">Adjust each alliance's stats with the sliders to model "what if" scenarios — e.g. what happens if RSP gains 200B power before SvS. The stat score feeds the AI simulation for a written outcome. Click <b>Reset to live data</b> to restore the current alliance standings.</p>
    </div>
  );
}
window.WarSimulatorPage = WarSimulatorPage;
