// ViG Command Center — Building Cost calculator (Calculator hub)
// Powered by the real ViG K40→K50 building tables in construction-data.js
const { useState: useStateBC, useMemo: useMemoBC, useEffect: useEffectBC } = React;

const BC_RES = [['Food', '#16a34a'], ['Wood', '#a16207'], ['Stone', '#64748b'], ['Ore', '#dc2626']];
const bcFmt = n => n >= 1e12 ? (n / 1e12).toFixed(2) + 'T' : n >= 1e9 ? (n / 1e9).toFixed(1) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : Math.round(n).toLocaleString();

/* parse construction-data building names into { building, step } */
function bcCatalog() {
  const byBuilding = {};
  (window.CONSTRUCTION.levels || []).forEach(lv => {
    lv.buildings.forEach(b => {
      if (!b.c || !b.c.some(x => x)) return;
      let name = b.name.replace(/\s*\(incl\. prereqs\)/i, '').trim();
      const prereqs = /incl\. prereqs/i.test(b.name);
      let m = name.match(/^(.*?)\s*(?:Lv\s*)?(\d+)\s*(?:→\s*(\d+))?$/i);
      let building = name, step = `K${lv.from}→K${lv.to}`;
      if (m) {
        building = m[1].trim().replace(/^Walls$/i, 'Wall');
        step = m[3] ? `Lv ${m[2]} → ${m[3]}` : `→ Lv ${m[2]}`;
      }
      if (!byBuilding[building]) byBuilding[building] = [];
      byBuilding[building].push({ id: building + '|' + b.name + '|' + lv.from, step, prereqs, keep: `K${lv.from}→${lv.to}`, c: b.c });
    });
  });
  return Object.entries(byBuilding)
    .map(([building, steps]) => ({ building, steps }))
    .sort((a, b) => b.steps.length - a.steps.length || a.building.localeCompare(b.building));
}

function BuildingCostCalc({ go }) {
  const catalog = useMemoBC(bcCatalog, []);
  const [sel, setSel] = useStateBC(() => catalog[0]?.building || '');
  const [checked, setChecked] = useStateBC({});
  const [plan, setPlan] = useStateBC(() => LS.get('vig2_bcost_plan', []));
  const [stock, setStock] = useStateBC(() => LS.get('vig2_bcost_stock', {}));
  const [buffs, setBuffs] = useStateBC(() => LS.get('vig2_cn_buffs', {}));
  const [buffsOpen, setBuffsOpen] = useStateBC(false);
  useEffectBC(() => { LS.set('vig2_bcost_plan', plan); }, [plan]);
  useEffectBC(() => { LS.set('vig2_bcost_stock', stock); }, [stock]);
  useEffectBC(() => { LS.set('vig2_cn_buffs', buffs); }, [buffs]);
  const checklist = window.CONSTRUCTION.buffChecklist || [];
  const buffDone = checklist.filter((_, i) => buffs[i]).length;

  const cur = catalog.find(c => c.building === sel);
  const curChecked = cur ? cur.steps.filter(s => checked[s.id]) : [];
  const inPlan = id => plan.some(p => p.id === id);

  const addToPlan = () => {
    const adds = curChecked.filter(s => !inPlan(s.id)).map(s => ({ id: s.id, building: sel, step: s.step, prereqs: s.prereqs, keep: s.keep, c: s.c }));
    if (adds.length) setPlan(p => [...p, ...adds]);
    setChecked({});
  };
  const totals = [0, 1, 2, 3].map(i => plan.reduce((s, p) => s + p.c[i], 0));
  const grand = totals.reduce((a, b) => a + b, 0);

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 gap-4 lg:grid-cols-5">
        {/* left: picker + speed buffs */}
        <div className="space-y-4 lg:col-span-3">
        <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-9 w-9 items-center justify-center rounded-lg bg-brand/10 text-[18px]">🧱</span>
            <div>
              <div className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Pick upgrades</div>
              <div className="text-[11px] text-zinc-400">Real ViG K40→K50 tables · costs include each step's full RSS</div>
            </div>
          </div>
          <div className="space-y-3 p-4">
            <div className="flex flex-wrap gap-1.5">
              {catalog.map(c => (
                <button key={c.building} onClick={() => setSel(c.building)}
                  className={`rounded-lg border px-2.5 py-1.5 text-[12px] font-semibold transition-colors ${sel === c.building ? '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'}`}>
                  {c.building}<span className="ml-1 text-[10px] opacity-60">{c.steps.length}</span>
                </button>
              ))}
            </div>
            {cur && (
              <div className="overflow-x-auto overflow-y-hidden rounded-xl border border-zinc-100 dark:border-zinc-800">
                <table className="w-full min-w-[480px] text-[12.5px]">
                  <thead><tr className="border-b border-zinc-100 bg-zinc-50/60 text-[10px] uppercase tracking-wide text-zinc-400 dark:border-zinc-800 dark:bg-zinc-800/40">
                    <th className="px-3 py-2 text-left font-semibold">Upgrade</th>
                    {BC_RES.map(([r, c]) => <th key={r} className="px-2 py-2 text-right font-semibold" style={{ color: c }}>{r}</th>)}
                    <th className="px-3 py-2"></th>
                  </tr></thead>
                  <tbody>
                    {cur.steps.map(s => {
                      const added = inPlan(s.id);
                      return (
                        <tr key={s.id} onClick={() => !added && setChecked(ch => ({ ...ch, [s.id]: !ch[s.id] }))}
                          className={`border-b border-zinc-50 last:border-0 dark:border-zinc-800/50 ${added ? 'opacity-45' : 'cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-800/40'}`}>
                          <td className="px-3 py-2">
                            <div className="flex items-center gap-2">
                              <span className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${checked[s.id] && !added ? 'border-brand bg-brand text-white' : 'border-zinc-300 dark:border-zinc-600'}`}>{(checked[s.id] && !added) && <Icon name="check" size={11} stroke={3} />}{added && <Icon name="check" size={11} className="text-zinc-400" />}</span>
                              <span className="font-medium text-zinc-800 dark:text-zinc-100">{s.step}</span>
                              {s.prereqs && <Pill tone="zinc">incl. prereqs</Pill>}
                              <span className="ml-auto text-[10.5px] text-zinc-400">{s.keep}</span>
                            </div>
                          </td>
                          {s.c.map((v, i) => <td key={i} className="px-2 py-2 text-right tabular-nums text-zinc-600 dark:text-zinc-300">{bcFmt(v)}</td>)}
                          <td className="px-3 py-2 text-right text-[11px] tabular-nums text-zinc-400">{added ? 'in plan' : ''}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
            <div className="flex items-center justify-between">
              <span className="text-[11.5px] text-zinc-400">{curChecked.length ? `${curChecked.length} selected · ${bcFmt(curChecked.reduce((s, x) => s + x.c.reduce((a, b) => a + b, 0), 0))} total RSS` : 'Tap rows to select upgrades'}</span>
              <Btn variant="brand" size="sm" onClick={addToPlan} disabled={!curChecked.length}><Icon name="plus" size={14} />Add to plan</Btn>
            </div>
          </div>
        </Card>

        {/* speed buffs — shared with the full K40→K50 planner */}
        <Card className="overflow-hidden">
          <button onClick={() => setBuffsOpen(o => !o)} className="flex w-full items-center gap-2.5 px-4 py-3 text-left">
            <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-brand/10 text-[18px]">⚡</span>
            <div className="min-w-0 flex-1">
              <div className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Speed buffs <span className="ml-1 tabular-nums text-zinc-400">({buffDone}/{checklist.length})</span></div>
              <div className="truncate text-[11px] text-zinc-400">Stack these before building — less time, fewer speedups, same RSS saved</div>
            </div>
            <div className="hidden h-1.5 w-24 overflow-hidden rounded-full bg-zinc-100 sm:block dark:bg-zinc-800"><div className="h-full rounded-full bg-brand transition-all" style={{ width: (buffDone / Math.max(checklist.length, 1) * 100) + '%' }}></div></div>
            <Icon name="chevron" size={15} className={`shrink-0 text-zinc-400 transition-transform ${buffsOpen ? 'rotate-90' : ''}`} />
          </button>
          {buffsOpen && (
            <div className="grid grid-cols-1 gap-1.5 border-t border-zinc-100 p-4 sm:grid-cols-2 dark:border-zinc-800">
              {checklist.map((b, i) => {
                const on = !!buffs[i];
                return (
                  <button key={i} onClick={() => setBuffs(bf => ({ ...bf, [i]: !bf[i] }))}
                    className={`flex items-center gap-2 rounded-lg border px-2.5 py-2 text-left text-[12px] transition-colors ${on ? 'border-brand/40 bg-brand/5 text-zinc-800 dark:text-zinc-100' : 'border-zinc-100 text-zinc-500 hover:bg-zinc-50 dark:border-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-800/40'}`}>
                    <span className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${on ? 'border-brand bg-brand text-white' : 'border-zinc-300 dark:border-zinc-600'}`}>{on && <Icon name="check" size={11} stroke={3} />}</span>
                    <span className="leading-snug">{b}</span>
                  </button>
                );
              })}
              {go && (
                <button onClick={() => go('construction')} className="flex items-center justify-center gap-1.5 rounded-lg border border-dashed border-zinc-200 px-2.5 py-2 text-[12px] font-medium text-brand hover:bg-brand/5 dark:border-zinc-700">
                  Full K40→K50 planner & timelines<Icon name="chevron" size={13} />
                </button>
              )}
            </div>
          )}
        </Card>
        </div>

        {/* plan */}
        <Card className="overflow-hidden lg:col-span-2">
          <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 rounded-lg bg-brand/10 text-brand"><Icon name="layers" size={17} /></span>
              <div>
                <div className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Build plan</div>
                <div className="text-[11px] text-zinc-400">{plan.length ? plan.length + ' upgrades queued' : 'Nothing queued yet'}</div>
              </div>
            </div>
            {plan.length > 0 && <Btn variant="ghost" size="sm" onClick={() => setPlan([])}>Clear</Btn>}
          </div>
          {plan.length === 0 ? (
            <div className="px-6 py-12 text-center text-[12.5px] text-zinc-400">Select upgrades on the left and add them — totals appear here.</div>
          ) : (
            <>
              <div className="max-h-72 divide-y divide-zinc-50 overflow-y-auto dark:divide-zinc-800/50">
                {plan.map(p => (
                  <div key={p.id} className="flex items-center gap-2 px-4 py-2">
                    <div className="min-w-0 flex-1">
                      <div className="truncate text-[12.5px] font-medium text-zinc-800 dark:text-zinc-100">{p.building} <span className="text-zinc-400">{p.step}</span></div>
                      <div className="text-[10.5px] tabular-nums text-zinc-400">{bcFmt(p.c.reduce((a, b) => a + b, 0))} RSS</div>
                    </div>
                    <button onClick={() => setPlan(pl => pl.filter(x => x.id !== p.id))} className="rounded-md p-1 text-zinc-400 hover:text-rose-500"><Icon name="x" size={13} /></button>
                  </div>
                ))}
              </div>
              <div className="space-y-1.5 border-t border-zinc-100 p-4 dark:border-zinc-800">
                {BC_RES.map(([r, color], i) => {
                  const have = (+stock[r] || 0) * 1e9;
                  const diff = have - totals[i];
                  return (
                    <div key={r} className="flex items-center gap-2">
                      <span className="w-12 text-[11.5px] font-semibold" style={{ color }}>{r}</span>
                      <span className="flex-1 text-right text-[14px] font-bold tabular-nums text-zinc-900 dark:text-white">{bcFmt(totals[i])}</span>
                      <input type="number" min="0" value={stock[r] || ''} placeholder="have (B)"
                        onChange={e => setStock(s => ({ ...s, [r]: Math.max(0, +e.target.value || 0) }))}
                        className="h-8 w-20 rounded-lg border border-zinc-200 bg-white px-2 text-right text-[12px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />
                      <span className={`w-16 text-right text-[11px] font-semibold tabular-nums ${!stock[r] ? 'text-zinc-300 dark:text-zinc-600' : diff >= 0 ? 'text-emerald-500' : 'text-rose-500'}`}>{!stock[r] ? '—' : diff >= 0 ? '✓ ok' : bcFmt(-diff)}</span>
                    </div>
                  );
                })}
                <div className="mt-2 flex items-baseline justify-between border-t border-zinc-100 pt-2.5 dark:border-zinc-800">
                  <span className="text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Grand total</span>
                  <span className="text-[20px] font-bold tabular-nums text-brand">{bcFmt(grand)}</span>
                </div>
              </div>
            </>
          )}
        </Card>
      </div>
      <p className="px-1 text-[11.5px] text-zinc-400">Costs come from the ViG K40→K50 building tables. "Have" is entered in billions; shortfalls show in red. The speed-buff checklist is shared with the full Construction planner. Steps marked "incl. prereqs" bundle the prerequisite buildings for that keep level.</p>
    </div>
  );
}
window.BuildingCostCalc = BuildingCostCalc;
