// ViG Command Center — Senate Buff & Cost calculator
const { useState: useStateSN, useMemo: useMemoSN, useEffect: useEffectSN } = React;
const SEN = window.SENATE;
const SEN_TROOP_COLOR = { Ground: '#2563eb', Ranged: '#16a34a', Mounted: '#dc2626', Siege: '#9333ea' };
const SEN_TIERS = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII'];

// dedupe positions (sheet had duplicate blocks) and clean names
const SEN_POSITIONS = (() => {
  const seen = {}; const out = [];
  SEN.positions.forEach(p => { const name = p.name.replace(/\s*\n\s*/g, ' ').trim(); if (seen[name]) return; seen[name] = 1; out.push({ ...p, name }); });
  return out;
})();

function SenatePage() {
  const [pi, setPi] = useStateSN(() => LS.get('vig2_sen_pos', 0));
  const [tier, setTier] = useStateSN(() => LS.get('vig2_sen_tier', 7));
  useEffectSN(() => { LS.set('vig2_sen_pos', pi); }, [pi]);
  useEffectSN(() => { LS.set('vig2_sen_tier', tier); }, [tier]);
  const pos = SEN_POSITIONS[pi];
  const costName = Object.keys(SEN.cost).find(k => pos.name.toLowerCase().includes(k.toLowerCase().split(' ')[0])) || 'Governor';

  // cumulative buffs up to selected tier
  const buffs = useMemoSN(() => {
    const v = Array(24).fill(0);
    pos.tiers.slice(0, tier).forEach(t => t.buffs.forEach((x, i) => v[i] += x));
    return v;
  }, [pi, tier]);

  const cost = useMemoSN(() => {
    const rows = (SEN.cost[costName] || []).slice(0, tier * 8); // ~8 levels per promotion tier
    return { jade: rows.reduce((s, r) => s + r.jade, 0), twig: rows.reduce((s, r) => s + r.twig, 0) };
  }, [costName, tier]);

  const troops = SEN.labels.troops, stats = SEN.labels.stats;
  const buffRows = troops.flatMap((tr, ti) => stats.map((st, si) => ({ tr, st, buff: buffs[ti * 3 + si], debuff: buffs[12 + ti * 3 + si] }))).filter(r => r.buff || r.debuff);
  const fmt = n => n.toLocaleString();

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap gap-1.5">
        {SEN_POSITIONS.map((p, i) => (
          <button key={p.name} onClick={() => setPi(i)} className={`rounded-lg border px-3 py-1.5 text-[12.5px] font-semibold transition-all ${pi === i ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-600 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800'}`}>{p.name}</button>
        ))}
      </div>

      <Card className="p-5">
        <div className="mb-2 flex items-center justify-between">
          <span className="text-[12px] font-semibold uppercase tracking-wide text-zinc-400">Promotion tier</span>
          <span className="text-[16px] font-bold text-brand">{SEN_TIERS[tier - 1]}</span>
        </div>
        <div className="flex gap-1.5">
          {SEN_TIERS.map((tn, i) => (
            <button key={tn} onClick={() => setTier(i + 1)} className={`h-9 flex-1 rounded-lg text-[13px] font-bold transition-all ${tier >= i + 1 ? 'bg-brand text-white' : 'bg-zinc-100 text-zinc-400 dark:bg-zinc-800'}`}>{tn}</button>
          ))}
        </div>
      </Card>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        <Card className="p-5">
          <h3 className="text-[12px] font-semibold uppercase tracking-wide text-zinc-500">Leveling cost</h3>
          <div className="mt-3 space-y-3">
            <div className="flex items-center justify-between rounded-lg border border-zinc-100 px-3 py-2.5 dark:border-zinc-800">
              <span className="flex items-center gap-2 text-[13px] text-zinc-600 dark:text-zinc-300"><span className="h-3 w-3 rounded-full bg-emerald-400"></span>Jade</span>
              <span className="text-[15px] font-bold tabular-nums text-zinc-900 dark:text-white">{fmt(cost.jade)}</span>
            </div>
            <div className="flex items-center justify-between rounded-lg border border-zinc-100 px-3 py-2.5 dark:border-zinc-800">
              <span className="flex items-center gap-2 text-[13px] text-zinc-600 dark:text-zinc-300"><span className="h-3 w-3 rounded-full bg-amber-500"></span>Twig</span>
              <span className="text-[15px] font-bold tabular-nums text-zinc-900 dark:text-white">{fmt(cost.twig)}</span>
            </div>
            <p className="text-[11px] text-zinc-400">{pos.name} · cumulative cost through promotion {SEN_TIERS[tier - 1]}.</p>
          </div>
        </Card>

        <Card className="overflow-hidden lg:col-span-2">
          <div className="border-b border-zinc-100 px-4 py-2.5 text-[12px] font-semibold uppercase tracking-wide text-zinc-500 dark:border-zinc-800">Cumulative troop buffs</div>
          {buffRows.length === 0 ? (
            <div className="py-10 text-center text-[13px] text-zinc-400">No buffs at this tier.</div>
          ) : (
            <div className="grid grid-cols-2 gap-px bg-zinc-100 p-px dark:bg-zinc-800 sm:grid-cols-3">
              {buffRows.map((r, i) => (
                <div key={i} className="bg-white p-3 dark:bg-zinc-900">
                  <div className="text-[11px] font-medium" style={{ color: SEN_TROOP_COLOR[r.tr] }}>{r.tr} {r.st}</div>
                  {r.buff > 0 && <div className="text-[16px] font-bold tabular-nums text-zinc-900 dark:text-white">+{r.buff.toFixed(2)}%</div>}
                  {r.debuff > 0 && <div className="text-[13px] font-semibold tabular-nums text-rose-500">enemy −{r.debuff.toFixed(2)}%</div>}
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}
window.SenatePage = SenatePage;
