// ViG Command Center — March Presets (rally calculator)
// Distributions transcribed from "Rally Gear & March Setup Guide" (Server 428).
const { useState: useStatePr, useMemo: useMemoPr, useEffect: useEffectPr } = React;

const TIER_OPTS = [
  { value: 't11', label: 'T11' },
  { value: 't12', label: 'T12' },
  { value: 't13', label: 'T13' },
  { value: 'noT15', label: 'T14' },
  { value: 't15', label: 'T15' },
  { value: 't16', label: 'T16' },
  { value: 't17', label: 'T17' },
];

const PRESETS = {
  Ranged: {
    guideName: 'Range Rally',
    gear: ['Plantagenet Weapon', 'Plantagenet Ring', 'Thebes Boots', 'Thebes Leg Armor', 'Plantagenet Armor', 'Abbas Helmet'],
    dist: {
      t11: { T11: 100 },
      t12: { T12: 60, T11: 40 },
      t13: { T13: 40, T12: 45, T11: 15 },
      noT15: { T14: 20, T13: 30, T12: 40, T11: 5 },
      t15: { T15: 15, T14: 20, T13: 30, T12: 30 },
      t16: { T16: 10, T15: 15, T14: 20, T13: 25, T12: 25 },
      t17: { T17: 5, T16: 10, T15: 20, T14: 20, T13: 40 },
    },
  },
  Mounted: {
    guideName: 'Cavalry Rally',
    gear: ['Bourbon Weapon', 'Bourbon Ring', 'Plantagenet Boots', 'Bourbon Leg Armor', 'Han Armor', 'Plantagenet Helmet'],
    note: 'Keep Han Leg Armor on your Sub-City General for the Siege HP debuff.',
    dist: {
      t11: { T11: 100 },
      t12: { T12: 60, T11: 40 },
      t13: { T13: 45, T12: 40, T11: 15 },
      noT15: { T14: 20, T13: 35, T12: 40 },
      t15: { T15: 15, T14: 15, T13: 30, T12: 35 },
      t16: { T16: 15, T15: 20, T14: 25, T13: 25 },
      t17: { T17: 5, T16: 20, T15: 25, T14: 25, T13: 20 },
    },
  },
  Siege: {
    guideName: 'Siege Rally',
    gear: ['Full Heinan Set'],
    dist: {
      noT15: { T14: 25, T13: 70 },
      t15: { T15: 10, T14: 25, T13: 60 },
      t16: { T16: 5, T15: 15, T14: 20, T13: 55 },
      t17: { T17: 5, T16: 5, T15: 10, T14: 20, T13: 55 },
    },
  },
  Ground: {
    guideName: 'Ground Rally',
    gear: ['Aztec Weapon', 'Furin Ring', 'Furin Boots', 'Antoine Leg Armor', 'Freedom / Aztec Armor', 'Aztec Helmet'],
    dist: {
      t11: { T11: 100 },
      t12: { T12: 65, T11: 35 },
      t13: { T13: 50, T12: 35, T11: 15 },
      noT15: { T14: 40, T13: 40, T12: 15 },
      t15: { T15: 30, T14: 35, T13: 30 },
      t16: { T16: 25, T15: 35, T14: 35 },
      t17: { T17: 5, T16: 30, T15: 30, T14: 30 },
    },
  },
};
const TIER_ORDER = ['T17', 'T16', 'T15', 'T14', 'T13', 'T12', 'T11'];
const KINGDOM_LAYERS = [
  { range: 'K40 – K44', size: '1,000 – 5,000' },
  { range: 'K45 – K47', size: '5,000 – 10,000' },
  { range: 'K47 – K49', size: '10,000 – 20,000' },
  { range: 'K49 – K50', size: '20,000 – 25,000' },
];
const fmt = (n) => n.toLocaleString('en-US');

function PresetCard({ type, march, tier }) {
  const [showGear, setShowGear] = useStatePr(false);
  const p = PRESETS[type];
  const dist = p.dist[tier];
  const tiers = TIER_ORDER.filter(t => dist[t] != null);
  const totalPct = tiers.reduce((a, t) => a + dist[t], 0);
  const color = TYPE_COLOR[type];

  return (
    <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-8 w-8 items-center justify-center rounded-lg" style={{ background: color + '14', color }}><Icon name={TYPE_ICON[type]} size={17} /></span>
          <div>
            <div className="text-[14px] font-semibold text-zinc-900 dark:text-white">{p.guideName}</div>
            <div className="text-[11px] text-zinc-400">{tiers.length} tiers · {totalPct}% allocated</div>
          </div>
        </div>
        <TypeTag type={type} />
      </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(march * 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>
      <button onClick={() => setShowGear(s => !s)} className="flex w-full items-center gap-1.5 border-t border-zinc-100 px-4 py-2.5 text-left text-[12px] font-medium text-zinc-500 hover:bg-zinc-50 dark:border-zinc-800 dark:hover:bg-zinc-800/40">
        <Icon name="shield" size={13} />Recommended gear
        <Icon name="chevron" size={13} className={`ml-auto transition-transform ${showGear ? 'rotate-90' : ''}`} />
      </button>
      {showGear && (
        <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="flex flex-wrap gap-1.5">
            {p.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>
          {p.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" />{p.note}</p>}
        </div>
      )}
    </Card>
  );
}

function PresetsPage() {
  const [march, setMarch] = useStatePr(() => LS.get('vig2_march_size_v2', 5000000));
  const [tier, setTier] = useStatePr(() => LS.get('vig2_march_tier', 't16'));
  const [kIdx, setKIdx] = useStatePr(() => LS.get('vig2_kingdom', 2));
  useEffectPr(() => { LS.set('vig2_march_size_v2', march); }, [march]);
  useEffectPr(() => { LS.set('vig2_march_tier', tier); }, [tier]);
  useEffectPr(() => { LS.set('vig2_kingdom', kIdx); }, [kIdx]);

  const trap = useMemoPr(() => ['T16', 'T15', 'T14', 'T13', 'T12', 'T11'].map(t => ({ t, qty: 1000000 })), []);

  return (
    <div className="mx-auto max-w-[960px] space-y-5">
      {/* control bar */}
      <Card className="p-5">
        <div className="flex flex-col gap-5 sm:flex-row sm:items-end">
          <div className="flex-1">
            <label className="mb-1.5 block text-[12px] font-semibold uppercase tracking-wide text-zinc-400">Your march size</label>
            <div className="flex items-center gap-2 rounded-lg border border-zinc-200 bg-white px-3 focus-within:border-brand focus-within:ring-2 focus-within:ring-brand/15 dark:border-zinc-700 dark:bg-zinc-900">
              <Icon name="flame" size={18} className="text-brand" />
              <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-12 w-full bg-transparent text-[22px] font-semibold tabular-nums text-zinc-900 outline-none dark:text-white" />
              <span className="shrink-0 text-[12px] text-zinc-400">troops</span>
            </div>
            <div className="mt-2 flex flex-wrap gap-1.5">
              {[5000000, 7500000, 10000000, 12500000, 15000000].map(v => (
                <button key={v} onClick={() => setMarch(v)} className={`rounded-md border px-2 py-1 text-[11.5px] 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).toString().replace(/\.0$/, '') + 'M'}</button>
              ))}
            </div>
          </div>
          <div>
            <label className="mb-1.5 block text-[12px] font-semibold uppercase tracking-wide text-zinc-400">Highest troop tier</label>
            <Segmented options={TIER_OPTS} value={tier} onChange={setTier} />
          </div>
        </div>
      </Card>

      {/* 4 rally presets */}
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        {['Ground', 'Mounted', 'Ranged', 'Siege'].map(t => <PresetCard key={t} type={t} march={march} tier={tier} />)}
      </div>

      {/* trap buster */}
      <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">
          <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-zinc-900 text-white dark:bg-white dark:text-zinc-900"><Icon name="trap" size={17} /></span>
          <div>
            <div className="text-[14px] font-semibold text-zinc-900 dark:text-white">Trap Buster March</div>
            <div className="text-[11px] text-zinc-400">Standard composition · fixed quantities</div>
          </div>
        </div>
        <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>
      </Card>

      <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.PresetsPage = PresetsPage;
Object.assign(window, { MARCH_PRESETS: PRESETS, MARCH_TIER_OPTS: TIER_OPTS, MARCH_TIER_ORDER: TIER_ORDER, MARCH_KINGDOM_LAYERS: KINGDOM_LAYERS, MARCH_FMT: fmt });
