// ViG Command Center — Everything Gear (loadout comparator)
const { useState: useStateG, useMemo: useMemoG, useEffect: useEffectG } = React;

const G = window.GEAR;
const GEAR_KEY = 'vig2_gear_v1';
const TROOPS = G.legend.troops;   // Ground, Ranged, Mounted, Siege
const STATS = G.legend.stats;     // Atk, Def, HP
const TROOP_COLOR = { Ground: '#2563eb', Ranged: '#16a34a', Mounted: '#dc2626', Siege: '#9333ea' };

function emptyBuild() { const b = {}; G.slots.forEach(s => b[s] = null); return b; }
function slotSets(slot) { return Object.keys(G.catalog[slot] || {}); }
function pieceAt(slot, set, star) { const arr = (G.catalog[slot] || {})[set] || []; return arr.find(v => v.star === star) || arr[arr.length - 1]; }
function addVec(t, v, sign = 1) { for (let i = 0; i < 12; i++) t[i] += (v[i] || 0) * sign; }

function computeBuild(build, withDebuffs) {
  const buffs = Array(12).fill(0), debuffs = Array(12).fill(0), march = [0, 0, 0];
  const setCounts = {};
  const notes = [];
  G.slots.forEach(slot => {
    const sel = build[slot]; if (!sel) return;
    const p = pieceAt(slot, sel.set, sel.star); if (!p) return;
    addVec(buffs, p.buffs); if (withDebuffs) addVec(debuffs, p.debuffs);
    march[0] += p.march[0] || 0; march[1] += p.march[1] || 0; march[2] += p.march[2] || 0;
    setCounts[sel.set] = (setCounts[sel.set] || 0) + 1;
    if (p.other) notes.push(p.other.trim());
  });
  const activeSets = [];
  Object.entries(setCounts).forEach(([set, count]) => {
    if (count < 2) return;
    const tiers = (G.setBonuses[set] || []).filter(t => t.pieces <= count).sort((a, b) => a.pieces - b.pieces);
    tiers.forEach(t => { addVec(buffs, t.buffs); if (withDebuffs) addVec(debuffs, t.debuffs); march[0] += t.march[0] || 0; march[1] += t.march[1] || 0; march[2] += t.march[2] || 0; });
    if (tiers.length) activeSets.push({ set, count, tier: Math.max(...tiers.map(t => t.pieces)) });
  });
  return { buffs, debuffs, march, activeSets, notes: [...new Set(notes)] };
}

function GearSelect({ slot, value, onChange, accent }) {
  const sets = slotSets(slot);
  const stars = value ? [...new Set((G.catalog[slot][value.set] || []).map(v => v.star))] : [];
  return (
    <div className="flex items-center gap-2 border-b border-zinc-50 px-3 py-2 last:border-0 dark:border-zinc-800/60">
      <span className="w-14 shrink-0 text-[11px] font-semibold uppercase tracking-wide text-zinc-400">{slot}</span>
      <select value={value ? value.set : ''} onChange={e => { const set = e.target.value; if (!set) return onChange(null); const arr = G.catalog[slot][set]; onChange({ set, star: arr[arr.length - 1].star }); }}
        className="h-8 min-w-0 flex-1 rounded-lg border border-zinc-200 bg-white px-2 text-[12.5px] outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900">
        <option value="">— empty —</option>
        {sets.map(s => <option key={s} value={s}>{s}</option>)}
      </select>
      {value && stars.length > 1 && (
        <select value={value.star} onChange={e => onChange({ ...value, star: +e.target.value })}
          className="h-8 w-16 shrink-0 rounded-lg border border-zinc-200 bg-white px-1.5 text-[12.5px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900">
          {stars.map(st => <option key={st} value={st}>{st}★</option>)}
        </select>
      )}
    </div>
  );
}

function BuildColumn({ build, setBuild, accent, emoji, label, total }) {
  const sum = total.buffs.reduce((a, b) => a + b, 0);
  return (
    <Card className="overflow-hidden">
      <div className="flex items-center justify-between border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800" style={{ background: accent + '0d' }}>
        <div className="flex items-center gap-2"><span className="text-[16px]">{emoji}</span><span className="text-[13px] font-semibold text-zinc-900 dark:text-white">{label}</span></div>
        <span className="text-[12px] font-semibold tabular-nums" style={{ color: accent }}>{sum > 0 ? '+' + sum + '% total' : '—'}</span>
      </div>
      <div>{G.slots.map(slot => <GearSelect key={slot} slot={slot} accent={accent} value={build[slot]} onChange={v => setBuild(b => ({ ...b, [slot]: v }))} />)}</div>
      {total.activeSets.length > 0 && (
        <div className="flex flex-wrap gap-1.5 border-t border-zinc-100 px-3 py-2 dark:border-zinc-800">
          {total.activeSets.map(s => <span key={s.set} className="rounded-md px-1.5 py-0.5 text-[10.5px] font-medium" style={{ background: accent + '18', color: accent }}>{s.set} {s.tier}/6</span>)}
        </div>
      )}
    </Card>
  );
}

function GearPage() {
  const [buildA, setBuildA] = useStateG(() => LS.get(GEAR_KEY + '_a', null) || emptyBuild());
  const [buildB, setBuildB] = useStateG(() => LS.get(GEAR_KEY + '_b', null) || emptyBuild());
  const [scenario, setScenario] = useStateG(() => LS.get(GEAR_KEY + '_sc', 'attacking'));
  useEffectG(() => { LS.set(GEAR_KEY + '_a', buildA); }, [buildA]);
  useEffectG(() => { LS.set(GEAR_KEY + '_b', buildB); }, [buildB]);
  useEffectG(() => { LS.set(GEAR_KEY + '_sc', scenario); }, [scenario]);

  const withDebuffs = scenario !== 'defending';
  const tA = useMemoG(() => computeBuild(buildA, withDebuffs), [buildA, withDebuffs]);
  const tB = useMemoG(() => computeBuild(buildB, withDebuffs), [buildB, withDebuffs]);

  const rows = useMemoG(() => TROOPS.flatMap(tr => STATS.map(st => {
    const idx = TROOPS.indexOf(tr) * 3 + STATS.indexOf(st);
    return { tr, st, idx, a: tA.buffs[idx], b: tB.buffs[idx] };
  })).filter(r => r.a || r.b), [tA, tB]);

  const debuffRows = useMemoG(() => (withDebuffs ? TROOPS.flatMap(tr => STATS.map(st => {
    const idx = TROOPS.indexOf(tr) * 3 + STATS.indexOf(st);
    return { tr, st, idx, a: tA.debuffs[idx], b: tB.debuffs[idx] };
  })).filter(r => r.a || r.b) : []), [tA, tB, withDebuffs]);

  const winA = rows.filter(r => r.a > r.b).length, winB = rows.filter(r => r.b > r.a).length;
  const maxRow = Math.max(1, ...rows.map(r => Math.max(r.a, r.b)));

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-2.5">
        <Segmented options={[{ value: 'attacking', label: 'Attacking' }, { value: 'defending', label: 'Defending' }, { value: 'monster', label: 'Monsters' }]} value={scenario} onChange={setScenario} />
        <span className="text-[12px] text-zinc-400">{withDebuffs ? 'buffs + enemy debuffs' : 'buffs only'}</span>
        <div className="ml-auto flex gap-1.5">
          <Btn variant="outline" size="sm" onClick={() => setBuildB({ ...buildA })}>Copy 🥝 → 🍓</Btn>
          <Btn variant="ghost" size="sm" onClick={() => { setBuildA(emptyBuild()); setBuildB(emptyBuild()); }}>Reset</Btn>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <BuildColumn build={buildA} setBuild={setBuildA} accent="#16a34a" emoji="🥝" label="Build A" total={tA} />
        <BuildColumn build={buildB} setBuild={setBuildB} accent="#e11d48" emoji="🍓" label="Build B" total={tB} />
      </div>

      <Card className="overflow-hidden">
        <div className="flex items-center justify-between border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800">
          <h3 className="text-[12px] font-semibold uppercase tracking-wide text-zinc-500">Buff comparison</h3>
          <span className="text-[12px] tabular-nums text-zinc-400"><span className="text-emerald-600">🥝 {winA}</span> · <span className="text-rose-500">🍓 {winB}</span></span>
        </div>
        {rows.length === 0 ? (
          <div className="py-10 text-center text-[13px] text-zinc-400">Pick gear for each build to compare buffs.</div>
        ) : (
          <div className="divide-y divide-zinc-50 dark:divide-zinc-800/50">
            {rows.map(r => {
              const wa = r.a > r.b, wb = r.b > r.a;
              return (
                <div key={r.idx} className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 px-4 py-2">
                  <div className="flex items-center justify-end gap-2">
                    <span className={`w-12 text-right text-[13px] tabular-nums ${wa ? 'font-bold text-emerald-600' : 'text-zinc-500'}`}>{r.a ? '+' + r.a : '·'}</span>
                    <div className="h-1.5 w-20 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="ml-auto h-full rounded-full" style={{ width: (r.a / maxRow * 100) + '%', background: wa ? '#16a34a' : '#a3a3a3', float: 'right' }}></div></div>
                  </div>
                  <div className="w-28 text-center">
                    <span className="text-[11px] font-medium" style={{ color: TROOP_COLOR[r.tr] }}>{r.tr}</span>
                    <span className="ml-1 text-[11px] text-zinc-400">{r.st}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="h-1.5 w-20 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="h-full rounded-full" style={{ width: (r.b / maxRow * 100) + '%', background: wb ? '#e11d48' : '#a3a3a3' }}></div></div>
                    <span className={`w-12 text-[13px] tabular-nums ${wb ? 'font-bold text-rose-500' : 'text-zinc-500'}`}>{r.b ? '+' + r.b : '·'}</span>
                  </div>
                </div>
              );
            })}
          </div>
        )}
        {debuffRows.length > 0 && (
          <div className="border-t border-zinc-100 dark:border-zinc-800">
            <div className="px-4 py-2 text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Enemy debuffs</div>
            <div className="divide-y divide-zinc-50 dark:divide-zinc-800/50">
              {debuffRows.map(r => (
                <div key={r.idx} className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 px-4 py-1.5">
                  <span className="text-right text-[12.5px] tabular-nums text-zinc-500">{r.a ? '−' + r.a : '·'}</span>
                  <div className="w-28 text-center text-[11px] text-zinc-400">{r.tr} {r.st}</div>
                  <span className="text-[12.5px] tabular-nums text-zinc-500">{r.b ? '−' + r.b : '·'}</span>
                </div>
              ))}
            </div>
          </div>
        )}
        {(tA.march.some(x => x) || tB.march.some(x => x)) && (
          <div className="flex items-center justify-between border-t border-zinc-100 px-4 py-2.5 text-[12.5px] dark:border-zinc-800">
            <span className="tabular-nums text-emerald-600">March +{tA.march[0]} size</span>
            <span className="text-[11px] uppercase tracking-wide text-zinc-400">March size</span>
            <span className="tabular-nums text-rose-500">March +{tB.march[0]} size</span>
          </div>
        )}
      </Card>

      {(tA.notes.length > 0 || tB.notes.length > 0) && (
        <p className="px-1 text-[11.5px] text-zinc-400">Notes: {[...new Set([...tA.notes, ...tB.notes])].join(' · ')}</p>
      )}
    </div>
  );
}
window.GearPage = GearPage;
