// ViG Command Center — Resource Gathering calculator
// March load + gathering speed buffs → fill time, RSS/hour, and runs to a goal.
const { useState: useStateGA, useEffect: useEffectGA } = React;

const GA_RES = [
  ['Food', '#16a34a', 'vig/assets/icons/food.png'],
  ['Lumber', '#a16207', 'vig/assets/icons/lumber.png'],
  ['Stone', '#64748b', 'vig/assets/icons/stone.png'],
  ['Ore', '#dc2626', 'vig/assets/icons/ore.png'],
  ['Gold', '#ca8a04', 'vig/assets/icons/gold.png'],
];
// base gather rate per troop per hour (in-game baseline, level-15 tiles)
const GA_BASE_RATE = 30;
// preset gathering buff bundles (additive %)
const GA_PRESETS = [
  ['None', 0],
  ['Light (research only)', 120],
  ['Solid (research + gear)', 300],
  ['Strong (+ pets/buffs)', 600],
  ['Max (full gather build)', 1200],
];

const gaFmt = n => n >= 1e9 ? (n / 1e9).toFixed(2) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(2) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'K' : Math.round(n).toLocaleString();
function gaTime(hours) {
  if (!isFinite(hours) || hours <= 0) return '—';
  const total = Math.round(hours * 60);
  const d = Math.floor(total / 1440), h = Math.floor((total % 1440) / 60), m = total % 60;
  return [d ? d + 'd' : '', h ? h + 'h' : '', m ? m + 'm' : ''].filter(Boolean).join(' ') || '0m';
}

function GatheringCalc() {
  const [march, setMarch] = useStateGA(() => LS.get('vig2_ga_march', 1500000));
  const [load, setLoad] = useStateGA(() => LS.get('vig2_ga_load', 12000000));
  const [buff, setBuff] = useStateGA(() => LS.get('vig2_ga_buff', 300));
  const [nodes, setNodes] = useStateGA(() => LS.get('vig2_ga_nodes', 4));
  const [goal, setGoal] = useStateGA(() => LS.get('vig2_ga_goal', 0));
  useEffectGA(() => { LS.set('vig2_ga_march', march); }, [march]);
  useEffectGA(() => { LS.set('vig2_ga_load', load); }, [load]);
  useEffectGA(() => { LS.set('vig2_ga_buff', buff); }, [buff]);
  useEffectGA(() => { LS.set('vig2_ga_nodes', nodes); }, [nodes]);
  useEffectGA(() => { LS.set('vig2_ga_goal', goal); }, [goal]);

  const rate = march * GA_BASE_RATE * (1 + buff / 100); // per hour, one march
  const fillHours = load > 0 ? load / rate : 0;
  const perDayOneMarch = rate * 24;
  const perDayAll = perDayOneMarch * nodes;
  const runsToGoal = goal > 0 && load > 0 ? Math.ceil(goal / load) : 0;
  const goalHours = goal > 0 ? goal / (rate * nodes) : 0;

  const numInput = (val, set, w = 'w-40') => (
    <input type="text" inputMode="numeric" value={val ? val.toLocaleString() : ''} placeholder="0"
      onChange={e => set(Math.max(0, parseInt(e.target.value.replace(/[^\d]/g, '')) || 0))}
      className={`h-11 ${w} rounded-lg border border-zinc-200 bg-white px-3 text-[16px] font-bold tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900`} />
  );

  return (
    <div className="space-y-4">
      {/* config */}
      <Card className="space-y-4 p-4">
        <div className="flex flex-wrap items-end gap-x-6 gap-y-3">
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">March size (troops)</label>
            {numInput(march, setMarch)}
            <div className="mt-1 flex gap-1">{[500000, 1000000, 1500000, 2500000].map(q => (
              <button key={q} onClick={() => setMarch(q)} className={`rounded-md border px-2 py-1 text-[11px] font-semibold tabular-nums transition-colors ${march === q ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-400 hover:bg-zinc-50 dark:border-zinc-700 dark:hover:bg-zinc-800'}`}>{q / 1000000}M</button>
            ))}</div>
          </div>
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">March load (capacity)</label>
            {numInput(load, setLoad)}
            <div className="mt-1 text-[11px] text-zinc-400">Total RSS one march carries</div>
          </div>
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Gathering nodes / marches</label>
            <div className="flex h-11 items-center"><Segmented options={[1, 2, 3, 4, 5, 6].map(n => ({ value: n, label: String(n) }))} value={nodes} onChange={setNodes} /></div>
          </div>
        </div>
        <div>
          <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Gathering speed buff</label>
          <div className="flex flex-wrap items-center gap-1.5">
            {GA_PRESETS.map(([label, v]) => (
              <button key={label} onClick={() => setBuff(v)} className={`rounded-lg border px-2.5 py-1.5 text-[12px] font-semibold transition-colors ${buff === 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'}`}>{label}{v ? ` +${v}%` : ''}</button>
            ))}
            <label className="ml-1 flex items-center gap-1.5 text-[12px] text-zinc-500">custom
              <input type="number" min="0" value={buff || ''} onChange={e => setBuff(Math.max(0, +e.target.value || 0))} className="h-9 w-20 rounded-lg border border-zinc-200 bg-white px-2 text-right text-[13px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />%
            </label>
          </div>
        </div>
      </Card>

      {/* results */}
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <Card className="p-4">
          <div className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-400"><Icon name="bolt" size={13} className="text-brand" />Gather rate</div>
          <div className="mt-1 text-[22px] font-bold tabular-nums text-zinc-900 dark:text-white">{gaFmt(rate)}<span className="text-[13px] font-medium text-zinc-400">/hr</span></div>
          <div className="mt-0.5 text-[11px] text-zinc-400">per march at +{buff}%</div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-400"><Icon name="target" size={13} className="text-brand" />Time to fill</div>
          <div className="mt-1 text-[22px] font-bold tabular-nums text-brand">{gaTime(fillHours)}</div>
          <div className="mt-0.5 text-[11px] text-zinc-400">one full march load</div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-400"><Icon name="grid" size={13} className="text-brand" />Per day · 1 march</div>
          <div className="mt-1 text-[22px] font-bold tabular-nums text-zinc-900 dark:text-white">{gaFmt(perDayOneMarch)}</div>
          <div className="mt-0.5 text-[11px] text-zinc-400">24h continuous</div>
        </Card>
        <Card className="border-brand/30 p-4">
          <div className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-400"><Icon name="layers" size={13} className="text-brand" />Per day · {nodes} marches</div>
          <div className="mt-1 text-[22px] font-bold tabular-nums text-brand">{gaFmt(perDayAll)}</div>
          <div className="mt-0.5 text-[11px] text-zinc-400">all nodes running</div>
        </Card>
      </div>

      {/* goal planner */}
      <Card className="p-4">
        <div className="flex flex-wrap items-end gap-x-6 gap-y-3">
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">RSS goal</label>
            {numInput(goal, setGoal, 'w-44')}
          </div>
          {goal > 0 ? (
            <div className="flex flex-wrap gap-x-8 gap-y-2">
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Marches to fill</div>
                <div className="text-[20px] font-bold tabular-nums text-zinc-900 dark:text-white">{runsToGoal.toLocaleString()}</div>
              </div>
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Time · {nodes} marches</div>
                <div className="text-[20px] font-bold tabular-nums text-brand">{gaTime(goalHours)}</div>
              </div>
            </div>
          ) : <div className="pb-2 text-[12px] text-zinc-400">Enter a goal to see how long it takes to gather.</div>}
        </div>
      </Card>

      <p className="px-1 text-[11.5px] text-zinc-400">Estimates assume level-15 tiles ({GA_BASE_RATE}/troop/hr base) gathered continuously. Real rates vary with tile level and server; adjust the gathering-speed buff to match your build (research + gear + pets + statues). "Per day" figures assume marches never sit idle.</p>
    </div>
  );
}
window.GatheringCalc = GatheringCalc;
