// ViG Command Center — Unified March Center (builder + rally presets merged)
const { useState: useStateMC, useMemo: useMemoMC, useEffect: useEffectMC } = React;

function MarchCenterPage() {
  const V = window.VIG;
  const { isOwned } = useOwn();
  const PRESETS = window.MARCH_PRESETS, TIER_ORDER = window.MARCH_TIER_ORDER, fmt = window.MARCH_FMT;

  const [type, setType] = useStateMC(() => LS.get('vig2_mc_type', 'Ranged'));
  const [march, setMarch] = useStateMC(() => LS.get('vig2_march_size_v2', 5000000));
  const [tier, setTier] = useStateMC(() => LS.get('vig2_march_tier', 't16'));
  const [kIdx, setKIdx] = useStateMC(() => LS.get('vig2_kingdom', 2));
  const [layerSize, setLayerSize] = useStateMC(() => LS.get('vig2_mc_layersize', 1000));
  const [layerCount, setLayerCount] = useStateMC(() => LS.get('vig2_mc_layercount', 8));
  const [primaryName, setPrimaryName] = useStateMC(() => LS.get('vig2_mc_primary', null));
  const [assistName, setAssistName] = useStateMC(() => LS.get('vig2_mc_assist', null));
  const [dragonName, setDragonName] = useStateMC(() => LS.get('vig2_mc_dragon', null));
  const [reinfFill, setReinfFill] = useStateMC(() => LS.get('vig2_mc_reinf_fill', ['Archers', 'Cavalry']));
  const [prevSnap, setPrevSnap] = useStateMC(() => LS.get('vig2_mc_prev', null));
  useEffectMC(() => { LS.set('vig2_mc_type', type); }, [type]);
  useEffectMC(() => { LS.set('vig2_march_size_v2', march); }, [march]);
  useEffectMC(() => { LS.set('vig2_march_tier', tier); }, [tier]);
  useEffectMC(() => { LS.set('vig2_kingdom', kIdx); }, [kIdx]);
  useEffectMC(() => { LS.set('vig2_mc_layersize', layerSize); }, [layerSize]);
  useEffectMC(() => { LS.set('vig2_mc_layercount', layerCount); }, [layerCount]);
  useEffectMC(() => { LS.set('vig2_mc_primary', primaryName); }, [primaryName]);
  useEffectMC(() => { LS.set('vig2_mc_assist', assistName); }, [assistName]);
  useEffectMC(() => { LS.set('vig2_mc_dragon', dragonName); }, [dragonName]);
  useEffectMC(() => { LS.set('vig2_mc_reinf_fill', reinfFill); }, [reinfFill]);

  /* ---- reset / restore previous ---- */
  const MC_DEFAULTS = { type: 'Ranged', march: 5000000, tier: 't16', kIdx: 2, layerSize: 1000, layerCount: 8, primaryName: null, assistName: null, dragonName: null, reinfFill: ['Archers', 'Cavalry'] };
  const mcSnapshot = () => ({ type, march, tier, kIdx, layerSize, layerCount, primaryName, assistName, dragonName, reinfFill });
  const mcApply = s => { setType(s.type); setMarch(s.march); setTier(s.tier); setKIdx(s.kIdx); setLayerSize(s.layerSize); setLayerCount(s.layerCount); setPrimaryName(s.primaryName); setAssistName(s.assistName); setDragonName(s.dragonName); setReinfFill(s.reinfFill || ['Archers', 'Cavalry']); };
  const mcReset = () => { const s = mcSnapshot(); setPrevSnap(s); LS.set('vig2_mc_prev', s); mcApply(MC_DEFAULTS); };
  const mcRestore = () => { if (!prevSnap) return; const cur = mcSnapshot(); setPrevSnap(cur); LS.set('vig2_mc_prev', cur); mcApply(prevSnap); };

  const isTrap = type === 'Trap';
  const REINF_MAP = { Archers: 'Ranged', Ground: 'Ground', Cavalry: 'Mounted', 'Large Siege': 'Siege' };
  const battleType = isTrap ? 'Ground' : type === 'Reinforce' ? (REINF_MAP[reinfFill[0]] || 'Ground') : type === 'SmallSiege' ? 'Siege' : type;
  const typePool = useMemoMC(() => V.generals.filter(g => g.type === battleType), [battleType]);
  const primary = typePool.find(g => g.name === primaryName) || null;
  const assist = typePool.find(g => g.name === assistName) || null;
  const dragon = V.dragons.find(d => d.name === dragonName) || null;

  // clear picks that don't match the new type
  useEffectMC(() => {
    if (primaryName && !typePool.some(g => g.name === primaryName)) setPrimaryName(null);
    if (assistName && !typePool.some(g => g.name === assistName)) setAssistName(null);
  }, [battleType]);

  const stats = useMemoMC(() => CALC.marchStats({ primary, assist, dragon, type: battleType }), [primary, assist, dragon, battleType]);
  const compat = primary && assist ? CALC.compatScore(primary, assist) : null;
  const suggestedPrimary = typePool.find(isOwned) || typePool[0];
  const suggestedDragon = CALC.bestDragons(battleType, 1)[0];

  const MC_EXTRA_PRESETS = {
    Reinforce: {
      guideName: 'Reinforce March',
      gear: ['Defense / HP wall set on the keep\u2019s wall general', 'Han Armor & Leg Armor refines'],
      note: 'Reinforce with your strongest meat-shield tiers \u2014 coordinate composition with the keep owner\u2019s wall setup.',
      dist: {
        t11: { T11: 100 },
        t12: { T12: 60, T11: 40 },
        t13: { T13: 50, T12: 30, T11: 20 },
        noT15: { T14: 50, T13: 30, T12: 20 },
        t15: { T15: 40, T14: 30, T13: 30 },
        t16: { T16: 40, T15: 30, T14: 30 },
        t17: { T17: 30, T16: 30, T15: 20, T14: 20 },
      },
    },
    SmallSiege: {
      guideName: 'Small Siege Rally',
      gear: ['Full Heinan Set'],
      note: '95% T11 siege machines — the remaining 5% stays free for layers.',
      dist: {
        t11: { T11: 95 }, t12: { T11: 95 }, t13: { T11: 95 }, noT15: { T11: 95 },
        t15: { T11: 95 }, t16: { T11: 95 }, t17: { T11: 95 },
      },
    },
  };
  const preset = PRESETS[type] || MC_EXTRA_PRESETS[type];
  // tier options: Siege rallies only run T14/T15; Small Siege is fixed at 95% T11
  const TIER_LIMIT = { Siege: ['noT15', 't15'] };
  const tierOpts = TIER_LIMIT[type] ? window.MARCH_TIER_OPTS.filter(o => TIER_LIMIT[type].includes(o.value)) : window.MARCH_TIER_OPTS;
  const tierEff = tierOpts.some(o => o.value === tier) ? tier : tierOpts[tierOpts.length - 1].value;
  const showTier = !isTrap && type !== 'SmallSiege';
  const dist = preset ? preset.dist[tierEff] : null;
  const tiers = dist ? TIER_ORDER.filter(t => dist[t] != null) : [];
  const color = isTrap ? '#71717a' : (TYPE_COLOR[type] || (type === 'Reinforce' ? '#0891b2' : '#9333ea'));
  const trap = useMemoMC(() => ['T16', 'T15', 'T14', 'T13', 'T12', 'T11'].map(t => ({ t, qty: 1000000 })), []);
  const KINGDOM_LAYERS = window.MARCH_KINGDOM_LAYERS;

  const reserved = Math.min(march, (layerSize || 0) * (layerCount || 0));
  const mainTroops = Math.max(0, march - reserved);

  const TYPE_IMG = { Ground: 'vig/assets/icons/infantry.png', Mounted: 'vig/assets/icons/cavalry.png', Ranged: 'vig/assets/icons/ranged.png', Siege: 'vig/assets/icons/siege.png', Trap: 'vig/assets/icons/trap.png', Reinforce: 'vig/assets/icons/reinforce-icon.jpg', SmallSiege: 'vig/assets/icons/small-siege-icon.jpg' };
  const TYPE_LABEL = { SmallSiege: 'Small Siege' };

  const statCards = [
    { label: 'Attack', value: stats.atk, suffix: '%', color: '#dc2626' },
    { label: 'Defense', value: stats.def, suffix: '%', color: '#2563eb' },
    { label: 'HP / Leadership', value: stats.hp, suffix: '%', color: '#16a34a' },
    { label: 'March speed', value: stats.ms, suffix: '%', color: '#FF6B00' },
  ];
  const maxStat = Math.max(...statCards.map(s => s.value), 1);

  return (
    <div className="space-y-4">
      {/* ===== 1 · parameters ===== */}
      <Card className="overflow-hidden">
        <div className="flex items-center gap-2.5 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <img src="vig/assets/icons/current-march.png" alt="" className="h-9 w-9 rounded-lg" />
          <div className="min-w-0 flex-1">
            <div className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Parameters</div>
            <div className="truncate text-[11px] text-zinc-400">Rally type, march size & layers — everything below updates live</div>
          </div>
          <div className="flex shrink-0 gap-1.5">
            <Btn variant="ghost" size="sm" onClick={mcRestore} disabled={!prevSnap} title="Bring back the setup you had before the last reset"><Icon name="undo" size={14} />Restore previous</Btn>
            <Btn variant="outline" size="sm" onClick={mcReset} title="Back to defaults (your current setup is kept for Restore)"><Icon name="reset" size={14} />Reset</Btn>
          </div>
        </div>
        <div className="space-y-4 p-4">
          {/* rally type tiles */}
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Rally type</label>
            <div className="grid grid-cols-4 gap-2 sm:grid-cols-7">
              {[{ v: 'Ground' }, { v: 'Mounted' }, { v: 'Ranged' }, { v: 'Siege' }, { v: 'SmallSiege' }, { v: 'Reinforce' }, { v: 'Trap' }].map(({ v }) => (
                <button key={v} onClick={() => setType(v)}
                  className={`group flex flex-col items-center gap-1.5 rounded-xl border p-2.5 transition-all ${type === v ? 'border-brand bg-brand/[.07] shadow-[0_0_0_1px_var(--tw-shadow-color)] shadow-brand/40' : 'border-zinc-200 hover:border-zinc-300 hover:bg-zinc-50 dark:border-zinc-700 dark:hover:border-zinc-600 dark:hover:bg-zinc-800/60'}`}>
                  {TYPE_IMG[v]
                    ? <img src={TYPE_IMG[v]} alt="" className={`h-12 w-12 rounded-lg transition-transform group-hover:scale-105 ${type === v ? 'scale-105' : ''}`} />
                    : null}
                  <span className={`text-[11.5px] font-semibold ${type === v ? 'text-brand' : 'text-zinc-500 dark:text-zinc-400'}`}>{TYPE_LABEL[v] || v}</span>
                </button>
              ))}
            </div>
          </div>
          {/* filler troops — Reinforce only */}
          {type === 'Reinforce' && (
            <div>
              <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Filler troops <span className="normal-case text-zinc-400/80">(choose up to 2)</span></label>
              <div className="flex flex-wrap gap-2">
                {['Archers', 'Ground', 'Cavalry', 'Large Siege'].map(f => {
                  const on = reinfFill.includes(f);
                  const locked = !on && reinfFill.length >= 2;
                  return (
                    <button key={f} disabled={locked}
                      onClick={() => setReinfFill(on ? reinfFill.filter(x => x !== f) : [...reinfFill, f])}
                      className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-[12.5px] font-semibold transition-colors ${on ? 'border-emerald-400/60 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400' : locked ? 'cursor-not-allowed border-zinc-100 text-zinc-300 dark:border-zinc-800 dark:text-zinc-600' : 'border-zinc-200 text-zinc-600 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800'}`}>
                      <span className={`flex h-4 w-4 items-center justify-center rounded border transition-colors ${on ? 'border-emerald-500 bg-emerald-500 text-white' : 'border-zinc-300 dark:border-zinc-600'}`}>{on && <Icon name="check" size={11} stroke={3} />}</span>
                      {f}
                    </button>
                  );
                })}
              </div>
            </div>
          )}
          <div className="grid grid-cols-1 gap-4 md:grid-cols-[1.3fr_1.3fr_auto]">
            {/* march size */}
            <div>
              <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">March size</label>
              <div className="flex items-center gap-2 rounded-xl border border-zinc-200 bg-white px-2.5 py-1.5 focus-within:border-brand dark:border-zinc-700 dark:bg-zinc-900">
                <img src="vig/assets/icons/total-march.png" alt="" className="h-9 w-9 shrink-0 rounded-lg" />
                <input type="text" inputMode="numeric" value={fmt(march)}
                  onChange={e => { const n = parseInt(e.target.value.replace(/[^\d]/g, '')) || 0; setMarch(Math.min(n, 99000000)); }}
                  className="h-9 w-full min-w-0 bg-transparent text-[18px] font-semibold tabular-nums text-zinc-900 outline-none dark:text-white" />
                <div className="flex shrink-0 gap-1">
                  {[5000000, 10000000, 15000000].map(v => (
                    <button key={v} onClick={() => setMarch(v)} className={`rounded-md border px-1.5 py-1 text-[11px] font-medium tabular-nums transition-colors ${march === v ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-500 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800'}`}>{v / 1000000 + 'M'}</button>
                  ))}
                </div>
              </div>
            </div>
            {/* layer size */}
            {!isTrap && (
              <div>
                <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Layer size</label>
                <div className="flex items-center gap-2 rounded-xl border border-zinc-200 bg-white px-2.5 py-1.5 dark:border-zinc-700 dark:bg-zinc-900">
                  <img src="vig/assets/icons/max-march.png" alt="" className="h-9 w-9 shrink-0 rounded-lg" />
                  <input type="number" min="0" value={layerCount || ''} placeholder="0" onChange={e => setLayerCount(Math.max(0, +e.target.value || 0))} className="h-9 w-14 bg-transparent text-center text-[16px] font-semibold tabular-nums text-zinc-900 outline-none dark:text-white" />
                  <span className="shrink-0 whitespace-nowrap text-[12px] text-zinc-400">layers ×</span>
                  <input type="number" min="0" step="100" value={layerSize || ''} placeholder="0" onChange={e => setLayerSize(Math.max(0, +e.target.value || 0))} className="h-9 w-20 bg-transparent text-center text-[16px] font-semibold tabular-nums text-zinc-900 outline-none dark:text-white" />
                  <span className="ml-auto shrink-0 rounded-md bg-zinc-100 px-2 py-1 text-[11.5px] font-semibold tabular-nums text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400">−{fmt(reserved)}</span>
                </div>
                <p className="mt-1 text-[11px] text-zinc-400">Reserved for layering — the composition splits the remaining {fmt(mainTroops)}.</p>
              </div>
            )}
            {showTier && (
              <div>
                <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Highest tier</label>
                <div className="flex h-12 items-center"><Segmented options={tierOpts} value={tierEff} onChange={setTier} /></div>
              </div>
            )}
          </div>
        </div>
      </Card>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-5">
        <div className="space-y-4 lg:col-span-3">
          {/* ===== 2 · composition ===== */}
          <Card className="overflow-hidden">
            <div className="flex items-center justify-between border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
              <div className="flex items-center gap-2.5">
                <span className="flex h-9 w-9 items-center justify-center overflow-hidden rounded-lg"><img src={isTrap ? 'vig/assets/icons/trap.png' : TYPE_IMG[type]} alt="" className="h-9 w-9" /></span>
                <div>
                  <div className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">{isTrap ? 'Trap Buster March' : preset.guideName + ' composition'}</div>
                  <div className="text-[11px] text-zinc-400">{isTrap ? 'Standard fixed quantities' : `${tiers.length} tiers · for ${fmt(mainTroops)} main troops`}</div>
                </div>
              </div>
              {!isTrap && (TYPE_COLOR[type] ? <TypeTag type={type} /> : <Pill tone="zinc">{TYPE_LABEL[type] || type}</Pill>)}
            </div>
            {isTrap ? (
              <div className="grid grid-cols-1 gap-0 sm:grid-cols-2">
                <div className="border-b border-zinc-100 p-4 sm:border-b-0 sm:border-r dark:border-zinc-800">
                  <div className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Troop composition</div>
                  <div className="grid grid-cols-3 gap-1.5">
                    {trap.map(({ t, qty }) => (
                      <div key={t} className="rounded-lg border border-zinc-100 px-2.5 py-2 text-center dark:border-zinc-800">
                        <div className="text-[12px] font-semibold tabular-nums text-zinc-700 dark:text-zinc-200">{t}</div>
                        <div className="text-[11px] tabular-nums text-zinc-400">{fmt(qty)}</div>
                      </div>
                    ))}
                  </div>
                  <p className="mt-2.5 text-[11.5px] text-zinc-400">Layers: 100,000 – 150,000 each.</p>
                </div>
                <div className="p-4">
                  <div className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Recommended layer size</div>
                  <Segmented options={KINGDOM_LAYERS.map((k, i) => ({ value: i, label: k.range.replace(/K| /g, '') }))} value={kIdx} onChange={setKIdx} className="mb-3 flex-wrap" />
                  <div className="space-y-1">
                    {KINGDOM_LAYERS.map((k, i) => (
                      <div key={i} className={`flex items-center justify-between rounded-lg px-3 py-2 text-[13px] transition-colors ${i === kIdx ? 'bg-brand/10 text-brand' : 'text-zinc-500'}`}>
                        <span className="font-medium">{k.range}</span><span className="tabular-nums">{k.size}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            ) : (
              <>
                {type === 'Reinforce' && reinfFill.length > 0 && (
                  <div className="flex flex-wrap items-center gap-1.5 border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800">
                    <span className="text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Fill with</span>
                    {reinfFill.map(f => (
                      <span key={f} className="inline-flex items-center gap-1.5 rounded-md border border-emerald-400/40 bg-emerald-500/10 px-2 py-0.5 text-[11.5px] font-semibold text-emerald-600 dark:text-emerald-400">
                        {f}<span className="font-normal tabular-nums opacity-75">{fmt(Math.round(mainTroops / reinfFill.length))}</span>
                      </span>
                    ))}
                    <span className="text-[11px] text-zinc-400">— split each tier evenly between them</span>
                  </div>
                )}
                <div className="divide-y divide-zinc-50 px-4 dark:divide-zinc-800/60">
                  {tiers.map(t => {
                    const pct = dist[t]; const count = Math.round(mainTroops * pct / 100);
                    return (
                      <div key={t} className="flex items-center gap-3 py-2.5">
                        <span className="w-9 text-[12px] font-semibold tabular-nums text-zinc-400">{t}</span>
                        <div className="h-2 flex-1 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="h-full rounded-full transition-all duration-500" style={{ width: pct + '%', background: color }}></div></div>
                        <span className="w-10 text-right text-[12px] tabular-nums text-zinc-400">{pct}%</span>
                        <span className="w-20 text-right text-[13px] font-semibold tabular-nums text-zinc-900 dark:text-white">{fmt(count)}</span>
                      </div>
                    );
                  })}
                </div>
                <div className="border-t border-zinc-100 bg-zinc-50/60 px-4 py-3 dark:border-zinc-800 dark:bg-zinc-800/20">
                  <div className="mb-1.5 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-400"><Icon name="shield" size={12} />Recommended gear</div>
                  <div className="flex flex-wrap gap-1.5">
                    {preset.gear.map(g => <span key={g} className="rounded-md border border-zinc-200 bg-white px-2 py-0.5 text-[11.5px] text-zinc-600 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-300">{g}</span>)}
                  </div>
                  {preset.note && <p className="mt-2 flex items-start gap-1.5 text-[11.5px] text-amber-600 dark:text-amber-500"><Icon name="bolt" size={12} className="mt-0.5 shrink-0" />{preset.note}</p>}
                </div>
              </>
            )}
          </Card>

          {/* ===== 3 · commanders ===== */}
          {!isTrap && (
            <Card className="p-4">
              <div className="mb-3 flex items-center justify-between">
                <div className="flex items-center gap-2.5">
                  <img src="vig/assets/icons/commander.png" alt="" className="h-9 w-9 rounded-lg" />
                  <div>
                    <div className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Commanders</div>
                    <div className="text-[11px] text-zinc-400">Primary, assistant & dragon for this march</div>
                  </div>
                </div>
                {(!primary || !dragon) && suggestedPrimary && (
                  <Btn variant="ghost" size="sm" onClick={() => { setPrimaryName(suggestedPrimary.name); setDragonName(suggestedDragon?.d.name); }}><Icon name="bolt" size={14} />Auto-fill best</Btn>
                )}
              </div>
              <div className="space-y-3">
                <div>
                  <div className="mb-1 flex items-center gap-1.5 text-[11px] font-medium text-zinc-400"><span className="flex h-4 w-4 items-center justify-center rounded bg-brand text-[10px] text-white">1</span>Primary general</div>
                  <GeneralPicker value={primary} onChange={g => setPrimaryName(g ? g.name : null)} pool={typePool} placeholder={`Choose a ${battleType} general`} />
                </div>
                <div>
                  <div className="mb-1 flex items-center gap-1.5 text-[11px] font-medium text-zinc-400"><span className="flex h-4 w-4 items-center justify-center rounded bg-zinc-400 text-[10px] text-white">2</span>Assistant
                    {compat != null && <Pill tone={compat >= 75 ? 'green' : compat >= 55 ? 'brand' : 'zinc'} className="ml-auto">{compat}% synergy</Pill>}
                  </div>
                  <GeneralPicker value={assist} onChange={g => setAssistName(g ? g.name : null)} pool={typePool} placeholder="Choose an assistant" />
                  {primary && !assist && (
                    <div className="mt-2 flex flex-wrap gap-1.5">
                      <span className="self-center text-[11px] text-zinc-400">Suggested:</span>
                      {CALC.bestAssistants(primary, typePool, 3).map(({ g }) => (
                        <button key={g.name} onClick={() => setAssistName(g.name)} className="rounded-md border border-zinc-200 px-2 py-1 text-[12px] text-zinc-600 hover:border-brand/40 hover:text-brand dark:border-zinc-700 dark:text-zinc-300">{g.name}</button>
                      ))}
                    </div>
                  )}
                </div>
                <div>
                  <div className="mb-1 flex items-center gap-1.5 text-[11px] font-medium text-zinc-400"><span className="flex h-4 w-4 items-center justify-center rounded bg-zinc-400 text-[10px] text-white">3</span>Dragon</div>
                  <div className="flex flex-wrap gap-1.5">
                    {CALC.bestDragons(battleType, V.dragons.length).map(({ d, fit }) => (
                      <button key={d.name} onClick={() => setDragonName(dragonName === d.name ? null : d.name)}
                        className={`inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[12px] font-medium transition-colors ${dragonName === d.name ? '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="star" size={13} />{d.name}<span className="text-[10px] opacity-60">{fit}%</span>
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </Card>
          )}
        </div>

        {/* ===== summary ===== */}
        <div className="lg:col-span-2">
          <Card className="sticky top-4 p-5">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2.5">
                <img src="vig/assets/icons/march-summary.png" alt="" className="h-9 w-9 rounded-lg" />
                <h3 className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">March summary</h3>
              </div>
              {!isTrap ? (TYPE_COLOR[type] ? <TypeTag type={type} /> : <Pill tone="zinc">{TYPE_LABEL[type] || type}</Pill>) : <Pill tone="zinc">Trap</Pill>}
            </div>
            <div className="mt-3 space-y-1.5">
              <div className="flex items-center justify-between rounded-lg bg-zinc-50 px-3 py-2.5 dark:bg-zinc-800/50">
                <span className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wide text-zinc-400"><img src="vig/assets/icons/march-limit.png" alt="" className="h-6 w-6 rounded" />Total march</span>
                <span className="text-[17px] font-bold tabular-nums text-brand">{isTrap ? fmt(trap.reduce((s, x) => s + x.qty, 0)) : fmt(march)}</span>
              </div>
              {!isTrap && reserved > 0 && (
                <div className="flex items-center justify-between rounded-lg px-3 py-1.5">
                  <span className="flex items-center gap-2 text-[12px] text-zinc-400"><img src="vig/assets/icons/max-march.png" alt="" className="h-6 w-6 rounded" />Layers ({layerCount} × {fmt(layerSize)})</span>
                  <span className="text-[13px] font-semibold tabular-nums text-zinc-500">−{fmt(reserved)}</span>
                </div>
              )}
              {!isTrap && reserved > 0 && (
                <div className="flex items-center justify-between rounded-lg px-3 py-1.5">
                  <span className="flex items-center gap-2 text-[12px] text-zinc-400"><img src="vig/assets/icons/march-bonus.png" alt="" className="h-6 w-6 rounded" />Main troops</span>
                  <span className="text-[13px] font-semibold tabular-nums text-zinc-900 dark:text-white">{fmt(mainTroops)}</span>
                </div>
              )}
            </div>
            {isTrap ? (
              <p className="mt-4 text-[12.5px] leading-relaxed text-zinc-400">Trap busters use fixed 1M layers of T11–T16 — commanders and buffs are secondary; any spare general works.</p>
            ) : !primary ? (
              <div className="py-8 text-center text-[13px] text-zinc-400">Pick a primary general (or Auto-fill) to see live stats.</div>
            ) : (
              <>
                <div className="mt-4 space-y-3">
                  {statCards.map(s => (
                    <div key={s.label}>
                      <div className="mb-1 flex items-baseline justify-between"><span className="text-[12px] text-zinc-500">{s.label}</span><span className="text-[17px] font-semibold tabular-nums text-zinc-900 dark:text-white">+{s.value}{s.suffix}</span></div>
                      <div className="h-2 w-full overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="h-full rounded-full transition-all duration-500" style={{ width: (s.value / maxStat * 100) + '%', background: s.color }}></div></div>
                    </div>
                  ))}
                </div>
                <div className="mt-5 space-y-2 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                  <div className="flex items-center gap-2.5 text-[13px]"><Avatar name={primary.name} size={26} /><span className="flex-1 truncate text-zinc-700 dark:text-zinc-200">{primary.name}</span><Pill tone="brand">Primary</Pill></div>
                  {assist && <div className="flex items-center gap-2.5 text-[13px]"><Avatar name={assist.name} size={26} /><span className="flex-1 truncate text-zinc-700 dark:text-zinc-200">{assist.name}</span><Pill tone="zinc">Assist</Pill></div>}
                  {dragon && <div className="flex items-center gap-2.5 text-[13px]"><span className="flex h-[26px] w-[26px] items-center justify-center rounded-lg bg-gradient-to-br from-brand to-orange-600 text-white"><Icon name="star" size={14} /></span><span className="flex-1 truncate text-zinc-700 dark:text-zinc-200">{dragon.name}</span><Pill tone="brand">Dragon</Pill></div>}
                </div>
              </>
            )}
          </Card>
        </div>
      </div>
      <p className="px-1 text-center text-[11.5px] text-zinc-400">Distributions follow the ViG Rally Gear &amp; March Setup Guide. Always recheck final composition against your live march size and battlefield objective.</p>
    </div>
  );
}
window.MarchCenterPage = MarchCenterPage;
