// ViG Command Center — Tools hub (calculator suite v2)
const { useState: useStateT, useMemo: useMemoT, useEffect: useEffectT } = React;

const fmtNum = n => Math.round(n).toLocaleString();
const fmtBig = n => n >= 1e12 ? (n / 1e12).toFixed(2) + 'T' : n >= 1e9 ? (n / 1e9).toFixed(2) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'K' : fmtNum(n);
function fmtDur(mins) {
  const d = Math.floor(mins / 1440), h = Math.floor((mins % 1440) / 60), m = Math.round(mins % 60);
  return `${d}d ${h}h ${m}m`;
}
function NumIn({ value, onChange, w = 'w-24', placeholder = '0' }) {
  return <input type="number" min="0" value={value || ''} onChange={e => onChange(Math.max(0, +e.target.value || 0))} placeholder={placeholder}
    className={`h-9 ${w} rounded-lg border border-zinc-200 bg-white px-2.5 text-right text-[13px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900`} />;
}

/* ================= Speedup Calculator (categories like in-game inventory) ================= */
const SPEEDUPS = [['1m', 1], ['5m', 5], ['10m', 10], ['15m', 15], ['30m', 30], ['60m', 60], ['3h', 180], ['8h', 480], ['24h', 1440], ['3d', 4320], ['7d', 10080], ['30d', 43200]];
const SPEED_CATS = [['universal', 'Universal', 'bolt'], ['construction', 'Construction', 'grid'], ['research', 'Research', 'star'], ['training', 'Training', 'target'], ['healing', 'Healing', 'shield']];
function SpeedupCalc() {
  const [data, setData] = useStateT(() => LS.get('vig2_tool_speed_v2', {}));
  const [cat, setCat] = useStateT('universal');
  const [target, setTarget] = useStateT(() => LS.get('vig2_tool_speed_tgt', 0));
  useEffectT(() => { LS.set('vig2_tool_speed_v2', data); }, [data]);
  useEffectT(() => { LS.set('vig2_tool_speed_tgt', target); }, [target]);
  const counts = data[cat] || {};
  const setCount = (k, v) => setData(d => ({ ...d, [cat]: { ...(d[cat] || {}), [k]: v } }));
  const catTotal = c => SPEEDUPS.reduce((s, [k, m]) => s + ((data[c] || {})[k] || 0) * m, 0);
  const total = catTotal(cat);
  const grand = SPEED_CATS.reduce((s, [c]) => s + catTotal(c), 0);
  const usable = cat === 'universal' ? total : total + catTotal('universal');
  const targetMin = (+target || 0) * 1440;
  const diff = usable - targetMin;
  return (
    <div className="space-y-4">
      <div className="flex flex-wrap gap-1.5">
        {SPEED_CATS.map(([id, label, icon]) => (
          <button key={id} onClick={() => setCat(id)} className={`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-[12.5px] font-semibold transition-all ${cat === id ? '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'}`}>
            <Icon name={icon} size={13} />{label}
            <span className="tabular-nums text-[11px] opacity-70">{(catTotal(id) / 1440).toFixed(1)}d</span>
          </button>
        ))}
      </div>
      <Card className="p-4">
        <div className="grid grid-cols-2 gap-2.5 sm:grid-cols-3 lg:grid-cols-4">
          {SPEEDUPS.map(([k]) => (
            <div key={k} className="flex items-center justify-between gap-2 rounded-lg border border-zinc-100 px-3 py-2 dark:border-zinc-800">
              <span className="text-[13px] font-semibold text-zinc-700 dark:text-zinc-200"><Icon name="bolt" size={12} className="mr-1 inline text-brand" />{k}</span>
              <NumIn value={counts[k]} onChange={v => setCount(k, v)} w="w-20" />
            </div>
          ))}
        </div>
      </Card>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">{SPEED_CATS.find(c => c[0] === cat)[1]} total</div><div className="mt-1 text-[24px] font-bold tabular-nums text-brand">{fmtDur(total)}</div><div className="text-[11px] text-zinc-400">{(total / 1440).toFixed(1)} days</div></Card>
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">All categories</div><div className="mt-1 text-[24px] font-bold tabular-nums text-zinc-900 dark:text-white">{fmtDur(grand)}</div><div className="text-[11px] text-zinc-400">{(grand / 1440).toFixed(1)} days total inventory</div></Card>
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Target (days)</div><div className="mt-1.5"><NumIn value={target} onChange={setTarget} w="w-full" /></div><div className="mt-1 text-[11px] text-zinc-400">vs {cat === 'universal' ? 'universal' : cat + ' + universal'}</div></Card>
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">{diff >= 0 ? 'Surplus' : 'Shortfall'}</div><div className={`mt-1 text-[24px] font-bold tabular-nums ${diff >= 0 ? 'text-emerald-500' : 'text-rose-500'}`}>{targetMin ? fmtDur(Math.abs(diff)) : '—'}</div></Card>
      </div>
      <div className="flex justify-end"><Btn variant="ghost" size="sm" onClick={() => { setData(d => ({ ...d, [cat]: {} })); }}>Clear {SPEED_CATS.find(c => c[0] === cat)[1]}</Btn></div>
    </div>
  );
}

/* ================= Resource Calculator (incl. Gold) ================= */
const RES_DENOMS = [['1K', 1e3], ['10K', 1e4], ['100K', 1e5], ['1M', 1e6], ['10M', 1e7], ['100M', 1e8]];
const RES_TYPES5 = [['Food', '#16a34a'], ['Wood', '#a16207'], ['Stone', '#64748b'], ['Ore', '#dc2626'], ['Gold', '#ca8a04']];
function ResourceCalc() {
  const [counts, setCounts] = useStateT(() => LS.get('vig2_tool_res', {}));
  const [goal, setGoal] = useStateT(() => LS.get('vig2_tool_res_goal', {}));
  useEffectT(() => { LS.set('vig2_tool_res', counts); }, [counts]);
  useEffectT(() => { LS.set('vig2_tool_res_goal', goal); }, [goal]);
  const totals = RES_TYPES5.map(([r]) => RES_DENOMS.reduce((s, [d, v]) => s + (counts[r + d] || 0) * v, 0));
  return (
    <div className="space-y-4">
      <Card className="overflow-x-auto p-0">
        <table className="w-full text-[13px]">
          <thead><tr className="border-b border-zinc-100 text-[10.5px] uppercase tracking-wide text-zinc-400 dark:border-zinc-800"><th className="px-4 py-2.5 text-left font-semibold">Item</th>{RES_TYPES5.map(([r, c]) => <th key={r} className="px-3 py-2.5 text-right font-semibold" style={{ color: c }}>{r}</th>)}</tr></thead>
          <tbody>
            {RES_DENOMS.map(([d]) => (
              <tr key={d} className="border-b border-zinc-50 dark:border-zinc-800/50">
                <td className="px-4 py-2 font-semibold text-zinc-700 dark:text-zinc-200">{d} box</td>
                {RES_TYPES5.map(([r]) => <td key={r} className="px-3 py-2 text-right"><NumIn value={counts[r + d]} onChange={v => setCounts(c => ({ ...c, [r + d]: v }))} w="w-20" /></td>)}
              </tr>
            ))}
          </tbody>
          <tfoot><tr className="border-t-2 border-zinc-100 dark:border-zinc-800"><td className="px-4 py-2.5 font-bold text-zinc-900 dark:text-white">Total</td>{totals.map((t, i) => <td key={i} className="px-3 py-2.5 text-right font-bold tabular-nums" style={{ color: RES_TYPES5[i][1] }}>{fmtBig(t)}</td>)}</tr></tfoot>
        </table>
      </Card>
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-5">
        {RES_TYPES5.map(([r, c], i) => {
          const g = (+goal[r] || 0) * 1e9; const diff = totals[i] - g;
          return (
            <Card key={r} className="p-4">
              <div className="text-[11px] uppercase tracking-wide" style={{ color: c }}>{r}</div>
              <div className="mt-1 text-[22px] font-bold tabular-nums text-zinc-900 dark:text-white">{fmtBig(totals[i])}</div>
              <div className="mt-2 flex items-center gap-2"><span className="text-[11px] text-zinc-400">Goal (B)</span><NumIn value={goal[r]} onChange={v => setGoal(s => ({ ...s, [r]: v }))} w="w-16" /></div>
              {g > 0 && <div className={`mt-1 text-[12px] font-semibold tabular-nums ${diff >= 0 ? 'text-emerald-500' : 'text-rose-500'}`}>{diff >= 0 ? '✓ covered' : fmtBig(Math.abs(diff)) + ' short'}</div>}
            </Card>
          );
        })}
      </div>
      <p className="px-1 text-[11.5px] text-zinc-400">Goals are entered in billions (B) to match the Construction planner totals. Item boxes count what's in your inventory.</p>
    </div>
  );
}

/* ================= Troop Resource Calculator (layer rows, like Theria) ================= */
const TROOP_TYPES = ['Ground', 'Mounted', 'Ranged', 'Siege'];
const TROOP_TYPE_COLOR = { Ground: '#2563eb', Mounted: '#dc2626', Ranged: '#16a34a', Siege: '#9333ea' };
const TIERS_ALL = Array.from({ length: 17 }, (_, i) => 'T' + (i + 1));
function TroopCalc() {
  const [rows, setRows] = useStateT(() => LS.get('vig2_tool_troop_rows', [{ type: 'Ranged', tier: 'T16', count: 0 }]));
  const [profiles, setProfiles] = useStateT(() => LS.get('vig2_tool_troop_prof', {}));
  const [disc, setDisc] = useStateT(() => LS.get('vig2_tool_troop_disc', 0));
  const [editing, setEditing] = useStateT(null);
  useEffectT(() => { LS.set('vig2_tool_troop_rows', rows); }, [rows]);
  useEffectT(() => { LS.set('vig2_tool_troop_prof', profiles); }, [profiles]);
  useEffectT(() => { LS.set('vig2_tool_troop_disc', disc); }, [disc]);

  const profKey = r => r.type + '_' + r.tier;
  const prof = r => profiles[profKey(r)] || [0, 0, 0, 0, 0];
  const setProf = (r, i, v) => setProfiles(p => { const cur = [...(p[profKey(r)] || [0, 0, 0, 0, 0])]; cur[i] = v; return { ...p, [profKey(r)]: cur }; });
  const mult = 1 - Math.min(99, +disc || 0) / 100;
  const totals = [0, 1, 2, 3, 4].map(i => rows.reduce((s, r) => s + (r.count || 0) * prof(r)[i], 0) * mult);
  const totalTroops = rows.reduce((s, r) => s + (r.count || 0), 0);
  const setRow = (idx, patch) => setRows(rs => rs.map((r, i) => i === idx ? { ...r, ...patch } : r));

  return (
    <div className="space-y-4">
      <Card className="p-0">
        <div className="divide-y divide-zinc-50 dark:divide-zinc-800/50">
          {rows.map((r, i) => {
            const p = prof(r); const hasCost = p.some(x => x);
            const rowTotal = (r.count || 0) * p.reduce((a, b) => a + b, 0) * mult;
            return (
              <div key={i}>
                <div className="flex flex-wrap items-center gap-2 px-3.5 py-2.5">
                  <span className="h-2.5 w-2.5 shrink-0 rounded-sm" style={{ background: TROOP_TYPE_COLOR[r.type] }}></span>
                  <select value={r.type} onChange={e => setRow(i, { type: e.target.value })} className="h-9 rounded-lg border border-zinc-200 bg-white px-2 text-[12.5px] font-medium outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900">
                    {TROOP_TYPES.map(t => <option key={t}>{t}</option>)}
                  </select>
                  <select value={r.tier} onChange={e => setRow(i, { tier: e.target.value })} className="h-9 rounded-lg border border-zinc-200 bg-white px-2 text-[12.5px] font-medium outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900">
                    {TIERS_ALL.map(t => <option key={t}>{t}</option>)}
                  </select>
                  <NumIn value={r.count} onChange={v => setRow(i, { count: v })} w="w-28" placeholder="troops" />
                  <button onClick={() => setEditing(editing === i ? null : i)} className={`flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[11.5px] font-semibold transition-colors ${hasCost ? 'border-zinc-200 text-zinc-500 dark:border-zinc-700 dark:text-zinc-400' : 'border-amber-400/50 text-amber-500'}`}>
                    <Icon name="bolt" size={12} />{hasCost ? 'Unit costs' : 'Set unit costs'}
                  </button>
                  <span className="ml-auto text-[13px] font-bold tabular-nums text-zinc-700 dark:text-zinc-200">{rowTotal ? fmtBig(rowTotal) : '—'}</span>
                  <button onClick={() => setRows(rs => rs.filter((_, j) => j !== i))} className="rounded-md p-1 text-zinc-400 hover:text-rose-500" disabled={rows.length === 1}><Icon name="x" size={14} /></button>
                </div>
                {editing === i && (
                  <div className="flex flex-wrap items-center gap-3 border-t border-zinc-50 bg-zinc-50/60 px-4 py-2.5 dark:border-zinc-800/50 dark:bg-zinc-800/30">
                    <span className="text-[11px] font-semibold uppercase tracking-wide text-zinc-400">{r.type} {r.tier} per-unit:</span>
                    {RES_TYPES5.map(([name, color], k) => (
                      <label key={name} className="flex items-center gap-1.5"><span className="text-[11px] font-medium" style={{ color }}>{name}</span><NumIn value={p[k]} onChange={v => setProf(r, k, v)} w="w-20" /></label>
                    ))}
                    <span className="text-[11px] text-zinc-400">from your in-game training screen — saved per type+tier</span>
                  </div>
                )}
              </div>
            );
          })}
        </div>
        <div className="flex items-center justify-between border-t border-zinc-100 px-3.5 py-2.5 dark:border-zinc-800">
          <Btn variant="outline" size="sm" onClick={() => setRows(rs => [...rs, { type: 'Ground', tier: 'T1', count: 0 }])}><Icon name="plus" size={14} />Add layer</Btn>
          <label className="flex items-center gap-2 text-[12px] text-zinc-500">Training cost reduction <NumIn value={disc} onChange={setDisc} w="w-16" /> %</label>
        </div>
      </Card>
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-6">
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Troops</div><div className="mt-1 text-[22px] font-bold tabular-nums text-brand">{fmtNum(totalTroops)}</div></Card>
        {RES_TYPES5.map(([r, c], i) => (
          <Card key={r} className="p-4"><div className="text-[11px] uppercase tracking-wide" style={{ color: c }}>{r}</div><div className="mt-1 text-[22px] font-bold tabular-nums text-zinc-900 dark:text-white">{fmtBig(totals[i])}</div></Card>
        ))}
      </div>
      <p className="px-1 text-[11.5px] text-zinc-400">Layer-based like the in-game march screen: one row per troop type + tier. Unit costs vary with your research & buffs, so copy them once from your training screen — they're remembered per type+tier. The reduction % applies your training-cost buffs to all totals.</p>
    </div>
  );
}

/* ================= Blood of Ares (red star ascension) ================= */
// Cost per star: 4 equal sub-steps + a bigger 5th step. [fragPerStep, fragLast, bloodPerStep, bloodLast]
const ARES_COSTS = [
  [4, 14, 80, 300],   // ★1
  [8, 28, 100, 350],  // ★2
  [12, 42, 110, 450], // ★3
  [16, 56, 130, 550], // ★4
  [20, 70, 150, 650], // ★5
];
const ARES_STEPS = [{ label: 'No upgrades', star: 0, subStep: 0 }];
ARES_COSTS.forEach((_, s) => { for (let i = 1; i <= 5; i++) ARES_STEPS.push({ label: '★' + (s + 1) + ' · cultivate ' + i, star: s + 1, subStep: i }); });
function aresStepCost(idx) { // cost to go from step idx-1 to idx (idx 1..25)
  const s = Math.floor((idx - 1) / 5), sub = (idx - 1) % 5;
  const [f, fl, b, bl] = ARES_COSTS[s];
  return sub === 4 ? [fl, bl] : [f, b];
}
function aresRange(from, to) {
  let frags = 0, blood = 0;
  for (let i = from + 1; i <= to; i++) { const [f, b] = aresStepCost(i); frags += f; blood += b; }
  return [frags, blood];
}
function AresStars({ n, size = 13 }) {
  return <span className="inline-flex gap-0.5">{[0, 1, 2, 3, 4].map(i => <span key={i} style={{ color: i < n ? '#ef4444' : 'var(--star-off, #d4d4d8)', fontSize: size }}>★</span>)}</span>;
}
const ARES_CSS = `
@keyframes aresPop { 0% { transform: scale(0) rotate(-30deg); opacity: 0; } 60% { transform: scale(1.35) rotate(8deg); } 100% { transform: scale(1) rotate(0); opacity: 1; } }
@keyframes aresFloat { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }
@keyframes aresPulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(239,68,68,.35); } 50% { box-shadow: 0 0 0 9px rgba(239,68,68,0); } }
@keyframes aresShimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
@media (prefers-reduced-motion: reduce) { .ares-anim, .ares-anim * { animation: none !important; } }
`;
function AresStarsAnim({ n, size = 26 }) {
  return (
    <div className="flex items-center gap-1">
      {[0, 1, 2, 3, 4].map(i => (
        <span key={n + '-' + i} style={{
          fontSize: size, lineHeight: 1,
          color: i < n ? '#ef4444' : 'var(--star-off, #d4d4d8)',
          textShadow: i < n ? '0 0 14px rgba(239,68,68,.55)' : 'none',
          animation: i < n ? `aresPop .45s ${i * 0.07}s cubic-bezier(.34,1.56,.64,1) both` : 'none',
          display: 'inline-block',
        }}>★</span>
      ))}
    </div>
  );
}
function AresStageDots({ sub }) {
  return (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map(i => (
        <span key={i} className="rounded-full transition-all duration-300" style={{
          height: 5, width: i <= sub ? 18 : 8,
          background: i <= sub ? 'linear-gradient(90deg,#ef4444,#f97316)' : 'var(--star-off, #e4e4e7)',
        }}></span>
      ))}
      <span className="ml-1.5 text-[11px] font-semibold tabular-nums text-zinc-400">stage {sub}/5</span>
    </div>
  );
}
function BloodOfAresCalc() {
  const [from, setFrom] = useStateT(() => LS.get('vig2_tool_ares_from', 0));
  const [to, setTo] = useStateT(() => LS.get('vig2_tool_ares_to', 25));
  const [lvl, setLvl] = useStateT(() => LS.get('vig2_tool_ares_lvl', 25)); // explorer scrubber
  const [invF, setInvF] = useStateT(() => LS.get('vig2_tool_ares_invf', 0));
  const [invB, setInvB] = useStateT(() => LS.get('vig2_tool_ares_invb', 0));
  const [showRef, setShowRef] = useStateT(false);
  useEffectT(() => { LS.set('vig2_tool_ares_from', from); }, [from]);
  useEffectT(() => { LS.set('vig2_tool_ares_to', to); }, [to]);
  useEffectT(() => { LS.set('vig2_tool_ares_lvl', lvl); }, [lvl]);
  useEffectT(() => { LS.set('vig2_tool_ares_invf', invF); }, [invF]);
  useEffectT(() => { LS.set('vig2_tool_ares_invb', invB); }, [invB]);
  const toC = Math.max(to, from);
  const [needF, needB] = aresRange(from, toC);
  const [nextF, nextB] = from < 25 ? aresStepCost(from + 1) : [0, 0];
  const dF = invF - needF, dB = invB - needB;
  const Sel = ({ value, onChange, min }) => (
    <select value={value} onChange={e => onChange(+e.target.value)} className="h-10 w-full rounded-lg border border-zinc-200 bg-white px-2.5 text-[13px] font-medium outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900">
      {ARES_STEPS.map((s, i) => <option key={i} value={i} disabled={min != null && i < min}>{s.label}</option>)}
    </select>
  );
  return (
    <div className="space-y-4">
      {/* ---- ascension explorer ---- */}
      {(() => {
        const st = ARES_STEPS[lvl];
        const copies = st.star === 0 ? 0 : [1, 3, 6, 10, 15][st.star - 1];
        const [accF, accB] = aresRange(0, lvl);
        const [nxF, nxB] = lvl < 25 ? aresStepCost(lvl + 1) : null || [null, null];
        const marks = [{ label: 'No upgrades', at: 0 }, { label: '★1', at: 5 }, { label: '★2', at: 10 }, { label: '★3', at: 15 }, { label: '★4', at: 20 }, { label: '★5', at: 25 }];
        return (
          <Card className="ares-anim p-4 sm:p-5">
            <div className="flex flex-col gap-5 sm:flex-row">
              <div className="relative mx-auto shrink-0 sm:mx-0" style={{ animation: 'aresFloat 5.5s ease-in-out infinite' }}>
                <img src="vig/assets/ares-general.png" alt="Ares general" className="h-40 w-40 rounded-2xl object-cover" style={{ boxShadow: '0 10px 30px -8px rgba(239,68,68,.45), 0 0 0 1px rgba(239,68,68,.25)' }} />
                <div className="absolute inset-x-0 -bottom-2.5 flex justify-center">
                  <div className="rounded-full border border-red-500/30 bg-zinc-950/90 px-2.5 py-1" style={{ animation: 'aresPulse 2.6s ease-in-out infinite' }}>
                    <AresStarsAnim n={st.star} size={13} />
                  </div>
                </div>
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-baseline justify-between gap-2">
                  <div>
                    <div className="text-[16px] font-bold text-zinc-900 dark:text-white">{st.star === 0 ? 'No upgrades' : `Star ${st.star} — Stage ${st.subStep}`}</div>
                    <div className="mt-0.5 text-[12px] text-zinc-400">{copies} general {copies === 1 ? 'copy' : 'copies'}</div>
                  </div>
                  <AresStageDots sub={st.subStep} />
                </div>
            <div className="mt-4">
              <input type="range" min="0" max="25" step="1" value={lvl} onChange={e => setLvl(+e.target.value)} className="w-full accent-[#ef4444]" />
              <div className="relative mt-1 h-9">
                {marks.map(m => (
                  <button key={m.at} onClick={() => setLvl(m.at)} style={{ left: (m.at / 25 * 100) + '%' }}
                    className={`absolute -translate-x-1/2 text-center transition-colors ${lvl >= m.at ? (m.at === 0 ? 'text-zinc-600 dark:text-zinc-300' : 'text-red-500') : 'text-zinc-400 dark:text-zinc-600'}`}>
                    <span className="block text-[11px] font-semibold leading-tight whitespace-nowrap">{m.label}</span>
                    <span className="block text-[10px] tabular-nums opacity-70">{m.at}</span>
                  </button>
                ))}
              </div>
            </div>
            <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
              <div className="rounded-xl border border-zinc-100 p-3.5 dark:border-zinc-800">
                <div className="text-[10.5px] font-semibold uppercase tracking-wide text-zinc-400">Next stage</div>
                <div className="mt-1.5 flex justify-between text-[13px]"><span className="text-zinc-500">Fragments</span><span className="font-bold tabular-nums text-zinc-900 dark:text-white">{nxF != null ? nxF : '—'}</span></div>
                <div className="mt-1 flex justify-between text-[13px]"><span className="text-zinc-500">Blood of Ares</span><span className="font-bold tabular-nums text-zinc-900 dark:text-white">{nxB != null ? fmtNum(nxB) : '—'}</span></div>
              </div>
              <div className="rounded-xl border border-brand/30 bg-brand/5 p-3.5">
                <div className="text-[10.5px] font-semibold uppercase tracking-wide text-brand">Accumulated total</div>
                <div className="mt-1.5 flex justify-between text-[13px]"><span className="text-zinc-500">Fragments</span><span className="font-bold tabular-nums text-zinc-900 dark:text-white">{fmtNum(accF)}</span></div>
                <div className="mt-1 flex justify-between text-[13px]"><span className="text-zinc-500">Blood of Ares</span><span className="font-bold tabular-nums text-zinc-900 dark:text-white">{fmtNum(accB)}</span></div>
              </div>
            </div>
              </div>
            </div>
          </Card>
        );
      })()}

      <style>{ARES_CSS}</style>
      {/* ---- current → target ---- */}
      <Card className="ares-anim p-4 sm:p-5">
        <div className="grid grid-cols-1 items-center gap-4 sm:grid-cols-[1fr_auto_1fr]">
          <div className="rounded-xl border border-zinc-100 p-4 dark:border-zinc-800">
            <div className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-400"><Icon name="shield" size={13} />Current</div>
            <AresStarsAnim n={ARES_STEPS[from].star} />
            <div className="mt-2"><AresStageDots sub={ARES_STEPS[from].subStep} /></div>
            <div className="mt-3"><Sel value={from} onChange={v => { setFrom(v); if (to < v) setTo(v); }} /></div>
          </div>
          <div className="flex justify-center">
            <div className="flex h-10 w-10 items-center justify-center rounded-full border border-red-500/30 bg-red-500/10 text-red-500" style={{ animation: 'aresPulse 2.4s ease-in-out infinite' }}>
              <Icon name="chevron" size={18} className="rotate-0 sm:rotate-0" />
            </div>
          </div>
          <div className="rounded-xl border border-red-500/25 bg-red-500/[.04] p-4">
            <div className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-red-500"><Icon name="target" size={13} />Target</div>
            <AresStarsAnim n={ARES_STEPS[toC].star} />
            <div className="mt-2"><AresStageDots sub={ARES_STEPS[toC].subStep} /></div>
            <div className="mt-3"><Sel value={toC} onChange={setTo} min={from} /></div>
          </div>
        </div>
      </Card>
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Fragments needed</div><div className="mt-1 text-[26px] font-bold tabular-nums text-brand">{fmtNum(needF)}</div><div className="text-[11px] text-zinc-400">{from < 25 ? `next step: ${nextF}` : 'maxed'}</div></Card>
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Blood of Ares</div><div className="mt-1 text-[26px] font-bold tabular-nums text-rose-500">{fmtNum(needB)}</div><div className="text-[11px] text-zinc-400">{from < 25 ? `next step: ${nextB}` : 'maxed'}</div></Card>
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Your fragments</div><div className="mt-1.5"><NumIn value={invF} onChange={setInvF} w="w-full" /></div>{needF > 0 && <div className={`mt-1 text-[12px] font-semibold tabular-nums ${dF >= 0 ? 'text-emerald-500' : 'text-rose-500'}`}>{dF >= 0 ? '✓ enough' : fmtNum(-dF) + ' short'}</div>}</Card>
        <Card className="p-4"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Your Blood of Ares</div><div className="mt-1.5"><NumIn value={invB} onChange={setInvB} w="w-full" /></div>{needB > 0 && <div className={`mt-1 text-[12px] font-semibold tabular-nums ${dB >= 0 ? 'text-emerald-500' : 'text-rose-500'}`}>{dB >= 0 ? '✓ enough' : fmtNum(-dB) + ' short'}</div>}</Card>
      </div>
      <Card className="p-0">
        <button onClick={() => setShowRef(s => !s)} className="flex w-full items-center justify-between px-4 py-3 text-left">
          <span className="text-[13px] font-semibold text-zinc-900 dark:text-white">Reference tables — cost per star</span>
          <Icon name="chevron" size={15} className={`text-zinc-400 transition-transform ${showRef ? 'rotate-90' : ''}`} />
        </button>
        {showRef && (
          <div className="grid grid-cols-1 gap-4 border-t border-zinc-100 p-4 sm:grid-cols-2 lg:grid-cols-3 dark:border-zinc-800">
            {ARES_COSTS.map(([f, fl, b, bl], s) => (
              <div key={s} className="rounded-xl border border-zinc-100 p-3.5 dark:border-zinc-800">
                <div className="mb-2 flex items-center justify-between"><AresStars n={s + 1} /><span className="text-[11px] text-zinc-400">{s + 1} {s === 0 ? 'copy' : 'copies'} of the general</span></div>
                <table className="w-full text-[12px] tabular-nums">
                  <thead><tr className="text-[10px] uppercase tracking-wide text-zinc-400"><th className="py-1 text-left font-semibold">Step</th><th className="py-1 text-right font-semibold">Fragments</th><th className="py-1 text-right font-semibold">Blood</th></tr></thead>
                  <tbody>
                    {[1, 2, 3, 4].map(i => <tr key={i} className="border-t border-zinc-50 dark:border-zinc-800/50"><td className="py-1 text-zinc-500">{i}</td><td className="py-1 text-right">{f}</td><td className="py-1 text-right">{b}</td></tr>)}
                    <tr className="border-t border-zinc-50 dark:border-zinc-800/50"><td className="py-1 text-zinc-500">5</td><td className="py-1 text-right">{fl}</td><td className="py-1 text-right">{bl}</td></tr>
                    <tr className="border-t border-zinc-200 font-bold dark:border-zinc-700"><td className="py-1">Total</td><td className="py-1 text-right">{f * 4 + fl}</td><td className="py-1 text-right">{fmtNum(b * 4 + bl)}</td></tr>
                  </tbody>
                </table>
              </div>
            ))}
            <div className="rounded-xl border border-brand/30 bg-brand/5 p-3.5">
              <div className="mb-2 text-[12px] font-bold text-brand">Full ★0 → ★5 (15 copies)</div>
              <table className="w-full text-[12px] tabular-nums">
                <tbody>
                  {ARES_COSTS.map(([f, fl, b, bl], s) => <tr key={s} className="border-t border-brand/10 first:border-0"><td className="py-1 text-zinc-500">★{s + 1}</td><td className="py-1 text-right">{f * 4 + fl}</td><td className="py-1 text-right">{fmtNum(b * 4 + bl)}</td></tr>)}
                  <tr className="border-t border-brand/30 font-bold"><td className="py-1">Total</td><td className="py-1 text-right">450</td><td className="py-1 text-right">4,580</td></tr>
                </tbody>
              </table>
            </div>
          </div>
        )}
      </Card>
      <p className="px-1 text-[11.5px] text-zinc-400">Red-star ascension for sub-city / Ares generals: each ★ has 5 steps — four equal ones and a bigger fifth. Fragments come from general copies (1 copy = the fragments for its star). Full ★5 needs 15 copies total.</p>
    </div>
  );
}

/* ================= Hub ================= */
const TOOL_CARDS = [
  { id: 'troop', icon: 'target', emoji: '🏹', title: 'Troop Training', desc: 'Exact T1–T17 training costs: Food, Lumber, Stone, Ore, Gold + power gain.', internal: true },
  { id: 'speedup', icon: 'bolt', emoji: '⚡', title: 'Speedups', desc: 'Inventory by category — universal, construction, research, training, healing — vs a target.', internal: true },
  { id: 'resource', icon: 'grid', emoji: '📦', title: 'Resources', desc: 'Total your RSS + gold item boxes and compare against savings goals.', internal: true },
  { id: 'ares', icon: 'flame', emoji: '🩸', title: 'Blood of Ares', desc: 'Red-star ascension: fragments & Blood of Ares from your level to target.', internal: true },
  { id: 'bcost', icon: 'grid', emoji: '🏰', title: 'Buildings', desc: 'Queue K40→K50 upgrades, total the Food/Wood/Stone/Ore bill & track speed buffs.', internal: true },
  { id: 'gather', icon: 'grid', emoji: '⛏️', title: 'Gathering', desc: 'March load + gathering buffs → fill time, RSS/hour & runs to a goal.', internal: true },
  { id: 'rallysize', icon: 'flame', emoji: '🚩', title: 'Rally Size', desc: 'War Hall, Arch, gear & senate buffs → total rally capacity.', page: 'rallysize' },
  { id: 'march', icon: 'shield', emoji: '⚔️', title: 'March Size', desc: 'Compose marches with generals & dragons, plus rally presets.', page: 'march' },
  { id: 'gear', icon: 'shield', emoji: '🛡️', title: 'Gear Calculator', desc: 'Compare two 6-slot loadouts — buffs, set bonuses, debuffs & march.', page: 'gear' },
];
function ToolsPage({ go }) {
  const [sub, setSub] = useStateT(() => LS.get('vig2_tools_sub', 'hub'));
  useEffectT(() => { LS.set('vig2_tools_sub', sub); }, [sub]);

  /* ---- reset / restore previous (per calculator, via localStorage + remount) ---- */
  const CALC_RR = {
    troop: { vig2_tt_type: 'Ranged', vig2_tt_tier: 15, vig2_tt_amount: 1000000, vig2_tt_disc: 0 },
    speedup: { vig2_tool_speed_v2: {}, vig2_tool_speed_tgt: 0 },
    resource: { vig2_tool_res: {}, vig2_tool_res_goal: {} },
    ares: { vig2_tool_ares_from: 0, vig2_tool_ares_to: 25, vig2_tool_ares_lvl: 25, vig2_tool_ares_invf: 0, vig2_tool_ares_invb: 0 },
    bcost: { vig2_bcost_plan: [], vig2_bcost_stock: {} },
    gather: { vig2_ga_march: 1500000, vig2_ga_load: 12000000, vig2_ga_buff: 300, vig2_ga_nodes: 4, vig2_ga_goal: 0 },
  };
  const [rrNonce, setRrNonce] = useStateT(0);
  const [rrPrev, setRrPrev] = useStateT(null);
  useEffectT(() => { setRrPrev(LS.get('vig2_rr_' + sub, null)); }, [sub]);
  const rrDefs = CALC_RR[sub];
  const rrCapture = () => { const s = {}; Object.keys(rrDefs).forEach(k => { s[k] = LS.get(k, rrDefs[k]); }); return s; };
  const rrApply = s => { Object.keys(rrDefs).forEach(k => LS.set(k, s[k] !== undefined ? s[k] : rrDefs[k])); setRrNonce(n => n + 1); };
  const rrReset = () => { const cur = rrCapture(); LS.set('vig2_rr_' + sub, cur); setRrPrev(cur); rrApply(rrDefs); };
  const rrRestore = () => { if (!rrPrev) return; const old = rrPrev; const cur = rrCapture(); LS.set('vig2_rr_' + sub, cur); setRrPrev(cur); rrApply(old); };

  useEffectT(() => {
    const h = e => setSub(e.detail);
    window.addEventListener('vig-tools-sub', h);
    return () => window.removeEventListener('vig-tools-sub', h);
  }, []);
  const active = TOOL_CARDS.find(c => c.id === sub && c.internal);
  if (active) {
    return (
      <div className="space-y-4">
        <div className="flex flex-wrap items-center gap-3">
          <Btn variant="outline" size="sm" onClick={() => setSub('hub')}><Icon name="chevron" size={14} className="rotate-180" />All tools</Btn>
          <div className="flex items-center gap-2"><span className="text-[18px]">{active.emoji}</span><span className="text-[15px] font-bold text-zinc-900 dark:text-white">{active.title} Calculator</span></div>
          {rrDefs && (
            <div className="ml-auto flex gap-1.5">
              <Btn variant="ghost" size="sm" onClick={rrRestore} disabled={!rrPrev} title="Bring back the values you had before the last reset"><Icon name="undo" size={14} />Restore previous</Btn>
              <Btn variant="outline" size="sm" onClick={rrReset} title="Clear this calculator back to defaults (current values are kept for Restore)"><Icon name="reset" size={14} />Reset</Btn>
            </div>
          )}
        </div>
        {sub === 'speedup' && <SpeedupCalc key={'c' + rrNonce} />}
        {sub === 'resource' && <ResourceCalc key={'c' + rrNonce} />}
        {sub === 'troop' && <TroopTrainingCalc key={'c' + rrNonce} />}
        {sub === 'ares' && <BloodOfAresCalc key={'c' + rrNonce} />}
        {sub === 'bcost' && <BuildingCostCalc key={'c' + rrNonce} go={go} />}
        {sub === 'gather' && <GatheringCalc key={'c' + rrNonce} />}
      </div>
    );
  }
  return (
    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
      {TOOL_CARDS.map(c => (
        <Card key={c.id} className="flex flex-col p-5 transition-all hover:-translate-y-0.5 hover:border-brand/40 hover:shadow-md">
          <div className="flex items-center gap-3">
            <span className="flex h-11 w-11 items-center justify-center rounded-xl bg-brand/10 text-[20px]">{c.emoji}</span>
            <h3 className="text-[15px] font-bold text-zinc-900 dark:text-white">{c.title}</h3>
          </div>
          <p className="mt-2.5 flex-1 text-[12.5px] leading-relaxed text-zinc-500 dark:text-zinc-400">{c.desc}</p>
          <Btn variant="brand" size="sm" className="mt-4 self-start" onClick={() => c.internal ? setSub(c.id) : go(c.page)}><Icon name={c.icon} size={14} />Open calculator</Btn>
        </Card>
      ))}
    </div>
  );
}
window.ToolsPage = ToolsPage;
