// ViG Command Center — Construction Command Center (K40→K50)
const { useState: useStateCN, useMemo: useMemoCN, useEffect: useEffectCN } = React;
const CN = window.CONSTRUCTION;
const RSS = ['Food', 'Wood', 'Stone', 'Ore'];
const RSS_COLOR = ['#16a34a', '#a16207', '#64748b', '#dc2626'];
const RSS_ICON = ['flame', 'shield', 'grid', 'bolt'];

function fmtB(n) {
  if (n >= 1e12) return (n / 1e12).toFixed(2) + 'T';
  if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';
  if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
  return Math.round(n).toLocaleString();
}
const fmtFull = n => Math.round(n).toLocaleString();

function ConstructionPage() {
  const [from, setFrom] = useStateCN(() => LS.get('vig2_cn_from', 40));
  const [to, setTo] = useStateCN(() => LS.get('vig2_cn_to', 50));
  const [prod, setProd] = useStateCN(() => LS.get('vig2_cn_prod', [0, 0, 0, 0]));
  const [stock, setStock] = useStateCN(() => LS.get('vig2_cn_stock', [0, 0, 0, 0]));
  const [doneLevels, setDoneLevels] = useStateCN(() => LS.get('vig2_cn_done', {}));
  const [buffs, setBuffs] = useStateCN(() => LS.get('vig2_cn_buffs', {}));
  const [expanded, setExpanded] = useStateCN(null);
  const [tab, setTab] = useStateCN('plan');
  useEffectCN(() => { LS.set('vig2_cn_from', from); }, [from]);
  useEffectCN(() => { LS.set('vig2_cn_to', to); }, [to]);
  useEffectCN(() => { LS.set('vig2_cn_prod', prod); }, [prod]);
  useEffectCN(() => { LS.set('vig2_cn_stock', stock); }, [stock]);
  useEffectCN(() => { LS.set('vig2_cn_done', doneLevels); }, [doneLevels]);
  useEffectCN(() => { LS.set('vig2_cn_buffs', buffs); }, [buffs]);

  const path = useMemoCN(() => CN.levels.filter(l => l.from >= from && l.to <= to), [from, to]);
  const totals = useMemoCN(() => {
    const t = [0, 0, 0, 0];
    path.forEach(l => l.total.forEach((v, i) => t[i] += v));
    return t;
  }, [path]);
  const grand = totals.reduce((a, b) => a + b, 0);

  // timeline: per resource, (need - stock) / dailyProd
  const timeline = useMemoCN(() => totals.map((need, i) => {
    const remain = Math.max(0, need - (+stock[i] || 0));
    const daily = +prod[i] || 0;
    return daily > 0 ? Math.ceil(remain / daily) : null;
  }), [totals, prod, stock]);
  const maxDays = Math.max(0, ...timeline.filter(d => d != null));

  const buffDone = Object.values(buffs).filter(Boolean).length;
  const lvlDone = path.filter(l => doneLevels[l.from + '_' + l.to]).length;

  const setProdV = (i, v) => setProd(p => p.map((x, j) => j === i ? v : x));
  const setStockV = (i, v) => setStock(p => p.map((x, j) => j === i ? v : x));

  return (
    <div className="space-y-4">
      {/* path selector */}
      <Card className="p-5">
        <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
          {[['From keep', from, setFrom, 40, 49], ['Target keep', to, setTo, 41, 50]].map(([label, val, set, lo, hi], i) => (
            <div key={i}>
              <div className="mb-1.5 flex items-center justify-between"><span className="text-[12px] font-semibold uppercase tracking-wide text-zinc-400">{label}</span><span className="text-[18px] font-bold tabular-nums" style={{ color: i ? '#FF6B00' : '#71717a' }}>K{val}</span></div>
              <input type="range" min={lo} max={hi} value={val} onChange={e => { const v = +e.target.value; if (i === 0) { set(v); if (v >= to) setTo(Math.min(50, v + 1)); } else { set(v); if (v <= from) setFrom(Math.max(40, v - 1)); } }} className="w-full" style={{ accentColor: i ? '#FF6B00' : '#a1a1aa' }} />
            </div>
          ))}
        </div>
      </Card>

      {/* RSS totals */}
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        {RSS.map((r, i) => (
          <Card key={r} className="p-4">
            <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wide" style={{ color: RSS_COLOR[i] }}><Icon name={RSS_ICON[i]} size={13} />{r}</div>
            <div className="mt-1 text-[22px] font-bold tabular-nums text-zinc-900 dark:text-white">{fmtB(totals[i])}</div>
            {timeline[i] != null && <div className="text-[11px] text-zinc-400">{timeline[i].toLocaleString()} days @ your rate</div>}
          </Card>
        ))}
      </div>
      <Card className="flex flex-wrap items-center justify-between gap-3 p-4">
        <div><div className="text-[11px] uppercase tracking-wide text-zinc-400">Total RSS · K{from} → K{to}</div><div className="text-[24px] font-bold tabular-nums text-brand">{fmtB(grand)}</div></div>
        {maxDays > 0 && <div className="text-right"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Est. completion</div><div className="text-[20px] font-bold tabular-nums text-zinc-900 dark:text-white">{maxDays.toLocaleString()} days</div></div>}
        <div className="text-right"><div className="text-[11px] uppercase tracking-wide text-zinc-400">Levels done</div><div className="text-[20px] font-bold tabular-nums text-zinc-900 dark:text-white">{lvlDone}/{path.length}</div></div>
      </Card>

      <div className="flex flex-wrap items-center gap-2.5">
        <Segmented options={[{ value: 'plan', label: 'LEVEL BREAKDOWN' }, { value: 'rss', label: 'RSS PLANNER' }, { value: 'buffs', label: `SPEED BUFFS (${buffDone}/${CN.buffChecklist.length})` }]} value={tab} onChange={setTab} />
      </div>

      {tab === 'plan' && (
        <div className="space-y-2.5">
          {path.map(l => {
            const key = l.from + '_' + l.to; const done = !!doneLevels[key]; const open = expanded === key;
            const lt = l.total.reduce((a, b) => a + b, 0);
            return (
              <Card key={key} className={`overflow-hidden ${done ? 'opacity-70' : ''}`}>
                <div className="flex items-center gap-3 px-4 py-3">
                  <button onClick={() => setDoneLevels(d => ({ ...d, [key]: !d[key] }))} className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-md ${done ? 'bg-brand text-white' : 'border border-zinc-300 dark:border-zinc-600'}`}>{done && <Icon name="check" size={14} stroke={3} />}</button>
                  <button onClick={() => setExpanded(open ? null : key)} className="flex flex-1 items-center gap-3 text-left">
                    <span className="flex h-9 w-16 shrink-0 items-center justify-center rounded-lg bg-zinc-900 text-[13px] font-bold text-white dark:bg-white dark:text-zinc-900">K{l.from}→{l.to}</span>
                    <div className="hidden flex-1 gap-4 sm:flex">
                      {RSS.map((r, i) => <div key={r} className="flex items-center gap-1"><span className="h-2 w-2 rounded-sm" style={{ background: RSS_COLOR[i] }}></span><span className="text-[12.5px] tabular-nums text-zinc-600 dark:text-zinc-300">{fmtB(l.total[i])}</span></div>)}
                    </div>
                    <span className="ml-auto text-[13px] font-bold tabular-nums text-brand">{fmtB(lt)}</span>
                    <Icon name="chevron" size={16} className={`text-zinc-300 transition-transform ${open ? 'rotate-90' : ''}`} />
                  </button>
                </div>
                {open && (
                  <div className="overflow-x-auto border-t border-zinc-100 dark:border-zinc-800">
                    <table className="w-full min-w-[520px] text-[12.5px]">
                      <thead><tr className="text-[10.5px] uppercase tracking-wide text-zinc-400"><th className="px-4 py-2 text-left font-semibold">Building</th>{RSS.map((r, i) => <th key={r} className="px-3 py-2 text-right font-semibold" style={{ color: RSS_COLOR[i] }}>{r}</th>)}</tr></thead>
                      <tbody>
                        {l.buildings.map((b, j) => (
                          <tr key={j} className="border-t border-zinc-50 dark:border-zinc-800/50">
                            <td className="px-4 py-1.5 font-medium text-zinc-800 dark:text-zinc-100">{b.name}</td>
                            {b.c.map((v, i) => <td key={i} className="px-3 py-1.5 text-right tabular-nums text-zinc-600 dark:text-zinc-300">{v ? fmtFull(v) : '—'}</td>)}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </Card>
            );
          })}
        </div>
      )}

      {tab === 'rss' && (
        <Card className="p-5">
          <h3 className="text-[13px] font-semibold text-zinc-900 dark:text-white">Your resources</h3>
          <p className="text-[12px] text-zinc-400">Enter your stockpile and daily gathering rate per resource to estimate timeline.</p>
          <div className="mt-4 overflow-x-auto">
            <table className="w-full text-[13px]">
              <thead><tr className="text-[10.5px] uppercase tracking-wide text-zinc-400"><th className="py-2 text-left font-semibold">Resource</th><th className="py-2 text-right font-semibold">Needed</th><th className="py-2 text-right font-semibold">Stockpile</th><th className="py-2 text-right font-semibold">Daily rate</th><th className="py-2 text-right font-semibold">Days left</th></tr></thead>
              <tbody>
                {RSS.map((r, i) => (
                  <tr key={r} className="border-t border-zinc-100 dark:border-zinc-800">
                    <td className="py-2.5"><div className="flex items-center gap-1.5" style={{ color: RSS_COLOR[i] }}><Icon name={RSS_ICON[i]} size={14} /><span className="font-medium text-zinc-800 dark:text-zinc-100">{r}</span></div></td>
                    <td className="py-2.5 text-right tabular-nums text-zinc-600 dark:text-zinc-300">{fmtB(totals[i])}</td>
                    <td className="py-2.5 text-right"><input type="number" value={stock[i] || ''} onChange={e => setStockV(i, +e.target.value || 0)} placeholder="0" className="h-8 w-28 rounded-lg border border-zinc-200 bg-white px-2 text-right text-[12.5px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" /></td>
                    <td className="py-2.5 text-right"><input type="number" value={prod[i] || ''} onChange={e => setProdV(i, +e.target.value || 0)} placeholder="0" className="h-8 w-28 rounded-lg border border-zinc-200 bg-white px-2 text-right text-[12.5px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" /></td>
                    <td className="py-2.5 text-right font-bold tabular-nums" style={{ color: timeline[i] == null ? '#a1a1aa' : timeline[i] === 0 ? '#16a34a' : '#FF6B00' }}>{timeline[i] == null ? '—' : timeline[i] === 0 ? 'Ready' : timeline[i].toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {maxDays > 0 && <div className="mt-4 rounded-lg bg-brand/5 px-4 py-3 text-[13px] dark:bg-brand/10"><span className="text-zinc-500">Bottleneck:</span> <span className="font-bold text-brand">{RSS[timeline.indexOf(maxDays)]}</span> — full K{from}→K{to} path takes <span className="font-bold text-zinc-900 dark:text-white">{maxDays.toLocaleString()} days</span> at your current rate.</div>}
        </Card>
      )}

      {tab === 'buffs' && (
        <Card className="p-4">
          <div className="mb-3 flex items-center justify-between">
            <h3 className="text-[13px] font-semibold text-zinc-900 dark:text-white">Construction speed checklist</h3>
            <span className="text-[12px] tabular-nums text-zinc-400">{buffDone}/{CN.buffChecklist.length}</span>
          </div>
          <Progress value={buffDone / CN.buffChecklist.length * 100} className="mb-3" />
          <div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2">
            {CN.buffChecklist.map((b, i) => {
              const on = !!buffs[i];
              return (
                <button key={i} onClick={() => setBuffs(s => ({ ...s, [i]: !s[i] }))} className={`flex items-start gap-2.5 rounded-lg border px-3 py-2 text-left transition-all ${on ? 'border-brand bg-brand/5 dark:bg-brand/10' : 'border-zinc-200 hover:bg-zinc-50 dark:border-zinc-700 dark:hover:bg-zinc-800'}`}>
                  <span className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded ${on ? 'bg-brand text-white' : 'border border-zinc-300 dark:border-zinc-600'}`}>{on && <Icon name="check" size={11} stroke={3} />}</span>
                  <span className={`text-[12.5px] ${on ? 'text-zinc-800 dark:text-zinc-100' : 'text-zinc-600 dark:text-zinc-300'}`}>{b}</span>
                </button>
              );
            })}
          </div>
          <p className="mt-3 text-[11px] text-zinc-400">Checklist by Purge · C5 Library. Stacking these construction-speed sources dramatically cuts build times on the K40→K50 grind.</p>
        </Card>
      )}
    </div>
  );
}
window.ConstructionPage = ConstructionPage;
