// ViG Command Center — War Room 3.0: Alliance Intelligence (threat matrix, momentum heatmap, AI prediction)
const { useState: useStateWI, useMemo: useMemoWI } = React;

function wiActivity(al) {
  if (!al.players.length) return 0;
  const active = al.players.filter(p => (p.add || 0) > 0).length;
  return Math.round(active / al.players.length * 100);
}
function wiThreat(al, ctx) {
  const pPow = ctx.maxPower ? al.power / ctx.maxPower : 0;
  const pMom = ctx.maxMom ? Math.max(0, ALCALC.momentum(al)) / ctx.maxMom : 0;
  const pEff = ctx.maxEff ? ALCALC.avgPower(al) / ctx.maxEff : 0;
  const k49 = ALCALC.k49share(al) / 100;
  const act = wiActivity(al) / 100;
  return Math.round(100 * (0.42 * pPow + 0.22 * pMom + 0.16 * pEff + 0.12 * k49 + 0.08 * act));
}

function WiMetric({ label, value, sub, bar, color }) {
  return (
    <div className="px-3 py-2.5">
      <div className="text-[10px] font-semibold uppercase tracking-wide" style={{ color: 'var(--wr-faint)' }}>{label}</div>
      <div className="mt-0.5 text-[16px] font-bold wr-mono" style={{ color: color || '#e7e9ef' }}>{value}</div>
      {bar != null && <div className="mt-1.5 h-1 overflow-hidden rounded-full" style={{ background: '#0d0f15' }}><div className="h-full rounded-full" style={{ width: Math.max(3, bar) + '%', background: color }}></div></div>}
      {sub && <div className="mt-1 text-[10.5px]" style={{ color: 'var(--wr-faint)' }}>{sub}</div>}
    </div>
  );
}

function IntelligenceView({ data }) {
  const alliances = data.alliances;
  const ctx = useMemoWI(() => ({
    maxPower: Math.max(...alliances.map(a => a.power)),
    maxMom: Math.max(0.1, ...alliances.map(a => Math.max(0, ALCALC.momentum(a)))),
    maxEff: Math.max(...alliances.map(a => ALCALC.avgPower(a))),
  }), [alliances]);
  const ranked = [...alliances].map(a => ({ a, threat: wiThreat(a, ctx) })).sort((x, y) => y.threat - x.threat);
  const maxThreat = Math.max(...ranked.map(r => r.threat));

  const [pred, setPred] = useStateWI(() => LS.get('vig2_wi_pred', null));
  const [busy, setBusy] = useStateWI(false);
  const [perr, setPerr] = useStateWI('');

  const predict = async () => {
    setBusy(true); setPerr('');
    try {
      const lines = ranked.map(r => {
        const a = r.a;
        return `${a.id}: ${a.power.toFixed(0)}B power, ${a.memberCount || a.players.length} members, cycle gain ${ALCALC.momentum(a)}%, avg keep K${ALCALC.avgKeep(a)}, K49+ ${ALCALC.k49share(a)}%, activity ${wiActivity(a)}%, threat ${r.threat}`;
      }).join('\n');
      const prompt = `You are an Evony alliance war analyst. Three alliances are competing on Server 428.\n\n${lines}\n\nGive a tight prediction. Use EXACTLY this structure, one short line each, no preamble:\nWINNER: <alliance> — <one-line why>\nRISING: <alliance catching up> — <why>\nAT RISK: <alliance stalling> — <why>\nOUTLOOK: <one line on the next few cycles>\nCONFIDENCE: <High/Medium/Low>`;
      const reply = await window.claude.complete(prompt);
      const text = (reply || '').trim();
      setPred({ text, ts: Date.now() }); LS.set('vig2_wi_pred', { text, ts: Date.now() });
    } catch (e) { setPerr('AI unavailable — needs internet and may be rate-limited.'); }
    finally { setBusy(false); }
  };

  const predLines = pred ? pred.text.split('\n').map(l => l.trim()).filter(Boolean) : [];

  return (
    <div className="space-y-5">
      {/* threat matrix */}
      <WarPanel title="Threat matrix" sub="Composite strength from power, momentum, efficiency, K49 share & activity">
        <div className="grid grid-cols-1 gap-px md:grid-cols-3" style={{ background: 'var(--wr-line)' }}>
          {ranked.map((r, i) => {
            const a = r.a;
            return (
              <div key={a.id} className="p-4" style={{ background: 'var(--wr-bg)' }}>
                <div className="flex items-center gap-2">
                  <span className="flex h-6 w-6 items-center justify-center rounded-md text-[12px] font-extrabold" style={{ background: a.accent + '22', color: a.accent }}>{i + 1}</span>
                  <WrTag id={a.id} />
                  <div className="ml-auto text-right">
                    <div className="text-[24px] font-bold leading-none wr-mono" style={{ color: a.accent }}>{r.threat}</div>
                    <div className="text-[9px] uppercase tracking-wider" style={{ color: 'var(--wr-faint)' }}>Threat</div>
                  </div>
                </div>
                <div className="mt-2 h-1.5 overflow-hidden rounded-full" style={{ background: '#0d0f15' }}><div className="h-full rounded-full" style={{ width: (r.threat / maxThreat * 100) + '%', background: a.accent, boxShadow: `0 0 10px ${a.accent}99` }}></div></div>
                <div className="mt-2 grid grid-cols-2 gap-x-2">
                  <WiMetric label="Growth velocity" value={ALCALC.momentum(a) + '%'} color="#34d399" />
                  <WiMetric label="Power delta" value={fmtAdd(a.add) + 'B'} color={a.add >= 0 ? '#34d399' : '#fb7185'} />
                  <WiMetric label="Member efficiency" value={fmtB(ALCALC.avgPower(a))} sub="avg power / member" color="#cfd2dc" />
                  <WiMetric label="Activity rating" value={wiActivity(a) + '%'} sub="members gaining" color="#cfd2dc" />
                </div>
              </div>
            );
          })}
        </div>
      </WarPanel>

      {/* AI prediction engine */}
      <WarPanel title="AI prediction engine" sub="Live model forecast across the three alliances" action={
        <button onClick={predict} disabled={busy} className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-semibold text-white transition-all hover:brightness-110 disabled:opacity-50" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}>
          <Icon name={busy ? 'reset' : 'sparkle'} size={13} className={busy ? 'animate-spin' : ''} />{busy ? 'Analyzing…' : pred ? 'Re-run' : 'Predict'}
        </button>
      }>
        <div className="p-4">
          {perr && <div className="text-[12.5px] text-rose-400">{perr}</div>}
          {!pred && !perr && <div className="text-[12.5px]" style={{ color: 'var(--wr-dim)' }}>Run the prediction engine to forecast the winner, who's catching up, who's stalling, and the outlook — generated from the live threat data above.</div>}
          {pred && (
            <div className="space-y-2">
              {predLines.map((l, i) => {
                const [k, ...rest] = l.split(':');
                const v = rest.join(':').trim();
                const isKey = /^(WINNER|RISING|AT RISK|OUTLOOK|CONFIDENCE)$/i.test(k.trim());
                if (!isKey) return <p key={i} className="text-[13px]" style={{ color: '#cfd2dc' }}>{l}</p>;
                const tone = { winner: '#34d399', rising: '#60a5fa', 'at risk': '#fb7185', outlook: '#cfd2dc', confidence: '#FF6B00' }[k.trim().toLowerCase()];
                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]" style={{ color: '#e7e9ef' }}>{v}</span>
                  </div>
                );
              })}
              <div className="pt-1 text-[10.5px]" style={{ color: 'var(--wr-faint)' }}>Generated {syncTimeAgo ? syncTimeAgo(pred.ts) : ''} · AI estimate, verify before acting</div>
            </div>
          )}
        </div>
      </WarPanel>

      {/* momentum heatmap */}
      <WarPanel title="Momentum heatmap" sub="Each member shaded by power gained this cycle — brighter = bigger mover">
        <div className="space-y-4 p-4">
          {ranked.map(r => {
            const a = r.a;
            const maxAdd = Math.max(0.1, ...a.players.map(p => p.add || 0));
            const sorted = [...a.players].sort((x, y) => (y.add || 0) - (x.add || 0));
            return (
              <div key={a.id}>
                <div className="mb-1.5 flex items-center gap-2"><WrTag id={a.id} /><span className="text-[11px]" style={{ color: 'var(--wr-faint)' }}>{a.players.length} tracked · top mover +{fmtB(maxAdd)}</span></div>
                <div className="flex flex-wrap gap-1">
                  {sorted.map(p => {
                    const t = Math.max(0, (p.add || 0)) / maxAdd;
                    const accentRGB = { VIG: '#FF6B00', RSP: '#3B82F6', NEF: '#A855F7' }[a.id] || a.accent;
                    return (
                      <div key={p.name} title={`${p.name} · ${p.keep} · +${fmtB(p.add || 0)} this cycle`}
                        className="h-6 w-6 rounded" style={{ background: t > 0 ? accentRGB : '#1a1f2e', opacity: t > 0 ? 0.25 + t * 0.75 : 0.5, border: '1px solid rgba(255,255,255,.04)' }}></div>
                    );
                  })}
                </div>
              </div>
            );
          })}
          <div className="flex items-center gap-2 pt-1 text-[10.5px]" style={{ color: 'var(--wr-faint)' }}>
            <span>Lower</span>
            <div className="h-2 w-24 rounded-full" style={{ background: 'linear-gradient(90deg,#1a1f2e,#FF6B00)' }}></div>
            <span>Bigger gain</span>
          </div>
        </div>
      </WarPanel>
    </div>
  );
}
window.IntelligenceView = IntelligenceView;
