// ViG Command Center — Ideal Land (decoration / prosperity planner)
const { useState: useStateL, useMemo: useMemoL, useEffect: useEffectL } = React;

const LAND_KEY = 'vig2_land_v1';
const L = window.LAND;

function landLevelVals(category) {
  return category === 'champion'
    ? { pts: L.tables.PointsC, march: L.tables.MarchC }
    : { pts: L.tables.PointsL, march: L.tables.MarchL };
}
function coinCum(level) { let s = 0; for (let i = 0; i < level; i++) s += L.tables.Coin[i]; return s; }
function valAt(arr, level) { return level <= 0 ? 0 : arr[Math.min(level, 10) - 1]; }

function Stepper({ value, onChange, max = 10, accent }) {
  return (
    <div className="inline-flex items-center gap-1">
      <button onClick={() => onChange(Math.max(0, value - 1))} className="flex h-6 w-6 items-center justify-center rounded-md border border-zinc-200 text-[15px] leading-none text-zinc-500 transition-colors hover:border-zinc-300 hover:text-zinc-800 disabled:opacity-30 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800" disabled={value <= 0}>−</button>
      <span className="w-6 text-center text-[13px] font-semibold tabular-nums" style={accent && value > 0 ? { color: accent } : {}}>{value}</span>
      <button onClick={() => onChange(Math.min(max, value + 1))} className="flex h-6 w-6 items-center justify-center rounded-md border border-zinc-200 text-zinc-500 transition-colors hover:border-zinc-300 hover:text-zinc-800 disabled:opacity-30 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800" disabled={value >= max}>
        <Icon name="plus" size={11} />
      </button>
    </div>
  );
}

function LandPage() {
  const [state, setState] = useStateL(() => LS.get(LAND_KEY, null) || {});
  const [tab, setTab] = useStateL('limited');
  const [others, setOthers] = useStateL(() => LS.get('vig2_land_others', {}));
  const [customPts, setCustomPts] = useStateL(() => LS.get('vig2_land_custom', 0));
  useEffectL(() => { LS.set(LAND_KEY, state); }, [state]);
  useEffectL(() => { LS.set('vig2_land_others', others); }, [others]);
  useEffectL(() => { LS.set('vig2_land_custom', customPts); }, [customPts]);

  const get = (name) => state[name] || { now: 0, target: 0 };
  const setBuilding = (name, patch) => setState(s => {
    const cur = s[name] || { now: 0, target: 0 };
    const next = { ...cur, ...patch };
    if (next.target < next.now) { if (patch.now != null) next.target = next.now; else next.now = next.target; }
    return { ...s, [name]: next };
  });

  const buildings = useMemoL(() => [
    ...L.champions.map(n => ({ name: n, category: 'champion' })),
    ...L.limited.map(n => ({ name: n, category: 'limited' })),
  ], []);

  const totals = useMemoL(() => {
    let pNow = 0, pTgt = 0, mNow = 0, mTgt = 0, coin = 0;
    buildings.forEach(b => {
      const { now, target } = get(b.name);
      const v = landLevelVals(b.category);
      pNow += valAt(v.pts, now); pTgt += valAt(v.pts, target);
      mNow += valAt(v.march, now); mTgt += valAt(v.march, target);
      coin += coinCum(target) - coinCum(now);
    });
    let othPts = 0, othMarch = 0;
    L.others.forEach(o => { if (o.custom) { othPts += +customPts || 0; } else if (others[o.name]) { othPts += Math.round(L.otherTotals.prosperity / (L.others.length - 1)); othMarch += Math.round(L.otherTotals.march / (L.others.length - 1)); } });
    return { pNow, pTgt, mNow, mTgt, coin, othPts, othMarch };
  }, [state, others, customPts, buildings]);

  const maxPros = L.champions.length * L.tables.PointsC[9] + L.limited.length * L.tables.PointsL[9];
  const maxMarch = L.champions.length * L.tables.MarchC[9] + L.limited.length * L.tables.MarchL[9];
  const prosTotal = totals.pTgt + totals.othPts;
  const marchTotal = totals.mTgt + totals.othMarch;

  const allTo = (lvl, which) => setState(s => { const n = { ...s }; buildings.forEach(b => { const cur = n[b.name] || { now: 0, target: 0 }; n[b.name] = { ...cur, [which]: lvl, ...(which === 'now' && lvl > cur.target ? { target: lvl } : {}) }; }); return n; });
  const reset = () => { setState({}); setOthers({}); setCustomPts(0); };

  const list = buildings.filter(b => b.category === tab);
  const fmt = n => Math.round(n).toLocaleString();

  return (
    <div className="space-y-4">
      {/* summary */}
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
        <Card className="relative overflow-hidden p-4">
          <div className="text-[11px] uppercase tracking-wide text-zinc-400">Prosperity Points</div>
          <div className="mt-1 text-[28px] font-semibold tabular-nums text-brand">{fmt(prosTotal)}</div>
          <Progress value={prosTotal / (maxPros + L.otherTotals.prosperity) * 100} className="mt-2" />
          <div className="mt-1 text-[11px] text-zinc-400">{fmt(totals.pNow + totals.othPts)} now · target {fmt(prosTotal)} of {fmt(maxPros + L.otherTotals.prosperity)} max</div>
        </Card>
        <Card className="p-4">
          <div className="text-[11px] uppercase tracking-wide text-zinc-400">March Size Increase</div>
          <div className="mt-1 text-[28px] font-semibold tabular-nums text-zinc-900 dark:text-white">{fmt(marchTotal)}</div>
          <Progress value={marchTotal / (maxMarch + L.otherTotals.march) * 100} tone="blue" className="mt-2" />
          <div className="mt-1 text-[11px] text-zinc-400">+{fmt(marchTotal - totals.mNow - 0)} from current build</div>
        </Card>
        <Card className="p-4">
          <div className="text-[11px] uppercase tracking-wide text-zinc-400">Coin Cost (now → target)</div>
          <div className="mt-1 text-[28px] font-semibold tabular-nums text-zinc-900 dark:text-white">{fmt(totals.coin)}</div>
          <div className="mt-2 flex gap-1.5">
            <Btn variant="outline" size="sm" onClick={() => allTo(10, 'target')}>All → max</Btn>
            <Btn variant="ghost" size="sm" onClick={reset}>Reset</Btn>
          </div>
        </Card>
      </div>

      {/* tabs */}
      <div className="flex flex-wrap items-center gap-2.5">
        <Segmented options={[{ value: 'limited', label: `Limited (${L.limited.length})` }, { value: 'champion', label: `Champion (${L.champions.length})` }, { value: 'others', label: `Others (${L.others.length})` }]} value={tab} onChange={setTab} />
        {tab !== 'others' && <div className="ml-auto flex gap-1.5">
          <Btn variant="ghost" size="sm" onClick={() => allTo(0, 'now')}>Now → 0</Btn>
          <Btn variant="ghost" size="sm" onClick={() => allTo(10, 'now')}>Now → max</Btn>
        </div>}
      </div>

      {tab === 'others' ? (
        <Card className="p-2">
          {L.others.map(o => (
            <div key={o.name} className="flex items-center gap-3 border-b border-zinc-50 px-3 py-2.5 last:border-0 dark:border-zinc-800/60">
              <span className="flex-1 text-[13px] font-medium text-zinc-800 dark:text-zinc-100">{o.name}</span>
              {o.custom ? (
                <input type="number" value={customPts} onChange={e => setCustomPts(+e.target.value || 0)} placeholder="points" className="h-8 w-28 rounded-lg border border-zinc-200 bg-white px-2.5 text-[13px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />
              ) : (
                <Toggle on={!!others[o.name]} onClick={() => setOthers(s => ({ ...s, [o.name]: !s[o.name] }))} />
              )}
            </div>
          ))}
          <p className="px-3 py-2 text-[11.5px] text-zinc-400">Fixed decorations contribute a combined {L.otherTotals.prosperity} prosperity and {L.otherTotals.march} march at full; toggles split that evenly. Use Basic Shrubbery to enter an exact point value.</p>
        </Card>
      ) : (
        <Card className="overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left 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 font-semibold">Building</th>
                  <th className="px-3 py-2.5 text-center font-semibold">Now</th>
                  <th className="px-3 py-2.5 text-center font-semibold">Target</th>
                  <th className="px-4 py-2.5 text-right font-semibold">Prosperity</th>
                  <th className="px-4 py-2.5 text-right font-semibold">March</th>
                  <th className="px-4 py-2.5 text-right font-semibold">Coin</th>
                </tr>
              </thead>
              <tbody>
                {list.map(b => {
                  const { now, target } = get(b.name);
                  const v = landLevelVals(b.category);
                  const pros = valAt(v.pts, target), march = valAt(v.march, target);
                  const coin = coinCum(target) - coinCum(now);
                  const active = target > 0;
                  return (
                    <tr key={b.name} className={`border-b border-zinc-50 transition-colors hover:bg-zinc-50 dark:border-zinc-800/50 dark:hover:bg-zinc-800/40 ${active ? '' : 'opacity-60'}`}>
                      <td className="px-4 py-2 font-medium text-zinc-900 dark:text-white">{b.name}</td>
                      <td className="px-3 py-2 text-center"><Stepper value={now} onChange={n => setBuilding(b.name, { now: n })} /></td>
                      <td className="px-3 py-2 text-center"><Stepper value={target} onChange={n => setBuilding(b.name, { target: n })} accent="#FF6B00" /></td>
                      <td className="px-4 py-2 text-right tabular-nums text-brand">{pros ? fmt(pros) : '—'}</td>
                      <td className="px-4 py-2 text-right tabular-nums text-zinc-600 dark:text-zinc-300">{march ? fmt(march) : '—'}</td>
                      <td className="px-4 py-2 text-right tabular-nums text-zinc-500">{coin ? fmt(coin) : '—'}</td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr className="border-t-2 border-zinc-100 font-semibold dark:border-zinc-800">
                  <td className="px-4 py-2.5 text-zinc-900 dark:text-white">{tab === 'champion' ? 'Champion' : 'Limited'} subtotal</td>
                  <td></td><td></td>
                  <td className="px-4 py-2.5 text-right tabular-nums text-brand">{fmt(list.reduce((s, b) => s + valAt(landLevelVals(b.category).pts, get(b.name).target), 0))}</td>
                  <td className="px-4 py-2.5 text-right tabular-nums text-zinc-700 dark:text-zinc-200">{fmt(list.reduce((s, b) => s + valAt(landLevelVals(b.category).march, get(b.name).target), 0))}</td>
                  <td className="px-4 py-2.5 text-right tabular-nums text-zinc-500">{fmt(list.reduce((s, b) => { const g = get(b.name); return s + coinCum(g.target) - coinCum(g.now); }, 0))}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </Card>
      )}
      <p className="px-1 text-[11.5px] text-zinc-400">Prosperity & March values are exact (validated against the sheet: {fmt(maxPros)} prosperity / {fmt(maxMarch)} march at full max). Coin cost is summed from the per-level cost table.</p>
    </div>
  );
}
window.LandPage = LandPage;
