// ViG Command Center — Resource Planner (future RSS requirements tracker)
const { useState: useStateRP, useMemo: useMemoRP, useEffect: useEffectRP } = React;

const RP_RES = [
  { id: 'food', label: 'Food', color: '#16a34a', emoji: '🌾' },
  { id: 'lumber', label: 'Lumber', color: '#a16207', emoji: '🪵' },
  { id: 'stone', label: 'Stone', color: '#64748b', emoji: '🪨' },
  { id: 'ore', label: 'Ore', color: '#dc2626', emoji: '⚙️' },
  { id: 'gold', label: 'Gold', color: '#ca8a04', emoji: '💰' },
];

/* preset upgrade costs (in millions) per goal type */
const RP_PRESETS = [
  { id: 'keep43', label: 'Keep 43', tag: 'Building', food: 23400, lumber: 29700, stone: 30600, ore: 29700, gold: 0 },
  { id: 'keep45', label: 'Keep 45', tag: 'Building', food: 27200, lumber: 34600, stone: 35600, ore: 34500, gold: 0 },
  { id: 'keep50', label: 'Keep 50', tag: 'Building', food: 31000, lumber: 39400, stone: 40600, ore: 39400, gold: 0 },
  { id: 'acad43', label: 'Academy 43', tag: 'Research', food: 0, lumber: 0, stone: 159645, ore: 0, gold: 8980 },
  { id: 'acad45', label: 'Academy 45', tag: 'Research', food: 0, lumber: 0, stone: 238432, ore: 0, gold: 13411 },
  { id: 'milacad15', label: 'Military Academy L15', tag: 'Research', food: 0, lumber: 0, stone: 0, ore: 0, gold: 183400 },
  { id: 't16_1m', label: '1M T16 Ranged', tag: 'Training', food: 12200, lumber: 36600, stone: 12200, ore: 0, gold: 1300 },
  { id: 't17_500k', label: '500K T17 Ranged', tag: 'Training', food: 9750, lumber: 29300, stone: 9750, ore: 0, gold: 2500 },
];
const RP_TAGS = ['All', 'Building', 'Research', 'Training'];
const rpFmt = n => n >= 1e6 ? (n / 1e6).toFixed(1) + 'B' : n >= 1000 ? (n / 1000).toFixed(0) + 'M' : n > 0 ? n.toLocaleString() : '—';
const rpNum = n => n >= 1000 ? (n / 1000).toFixed(1) + 'K' : n > 0 ? n.toString() : '0';

function ResourcePlannerPage() {
  const [goals, setGoals] = useStateRP(() => LS.get('vig2_rp_goals', []));
  const [stock, setStock] = useStateRP(() => LS.get('vig2_rp_stock', { food: 0, lumber: 0, stone: 0, ore: 0, gold: 0 }));
  const [tag, setTag] = useStateRP('All');
  const [custom, setCustom] = useStateRP({ label: '', food: 0, lumber: 0, stone: 0, ore: 0, gold: 0 });
  const [showCustom, setShowCustom] = useStateRP(false);
  useEffectRP(() => { LS.set('vig2_rp_goals', goals); }, [goals]);
  useEffectRP(() => { LS.set('vig2_rp_stock', stock); }, [stock]);

  const toggleGoal = id => setGoals(g => g.includes(id) ? g.filter(x => x !== id) : [...g, id]);
  const addCustom = () => {
    if (!custom.label.trim()) return;
    const id = 'custom_' + Date.now();
    RP_PRESETS.push({ id, label: custom.label, tag: 'Custom', ...Object.fromEntries(RP_RES.map(r => [r.id, +custom[r.id] || 0])) });
    setGoals(g => [...g, id]); setCustom({ label: '', food: 0, lumber: 0, stone: 0, ore: 0, gold: 0 }); setShowCustom(false);
  };

  const totals = useMemoRP(() => {
    const out = { food: 0, lumber: 0, stone: 0, ore: 0, gold: 0 };
    goals.forEach(id => { const p = RP_PRESETS.find(x => x.id === id); if (p) RP_RES.forEach(r => { out[r.id] += p[r.id] || 0; }); });
    return out;
  }, [goals]);

  const gaps = useMemoRP(() => Object.fromEntries(RP_RES.map(r => [r.id, Math.max(0, totals[r.id] - (stock[r.id] || 0))])), [totals, stock]);
  const covered = RP_RES.filter(r => totals[r.id] > 0 && gaps[r.id] === 0).length;
  const total_cost = RP_RES.reduce((s, r) => s + totals[r.id], 0);

  const setStockVal = (id, v) => setStock(s => ({ ...s, [id]: Math.max(0, parseInt(v.replace(/[^\d]/g, '')) || 0) }));

  const presets = tag === 'All' ? RP_PRESETS : RP_PRESETS.filter(p => p.tag === tag);

  return (
    <div className="space-y-4">
      {/* stock */}
      <Card className="overflow-hidden">
        <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <Icon name="layers" size={16} className="text-brand" />
          <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Current stock</span>
          <span className="text-[11.5px] text-zinc-400">Enter what you have stockpiled (in millions)</span>
        </div>
        <div className="grid grid-cols-2 gap-3 p-4 sm:grid-cols-5">
          {RP_RES.map(r => (
            <div key={r.id}>
              <label className="mb-1.5 flex items-center gap-1 text-[11px] font-semibold uppercase tracking-wide" style={{ color: r.color }}><span>{r.emoji}</span>{r.label}</label>
              <input value={stock[r.id] ? stock[r.id].toLocaleString() : ''} onChange={e => setStockVal(r.id, e.target.value)} placeholder="0" className="h-10 w-full rounded-lg border border-zinc-200 bg-white px-3 text-[13px] font-bold tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />
            </div>
          ))}
        </div>
      </Card>

      {/* goal picker */}
      <Card className="overflow-hidden">
        <div className="flex flex-wrap items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <Icon name="target" size={16} className="text-brand" />
          <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Planned upgrades</span>
          <div className="ml-auto flex flex-wrap gap-1">
            {RP_TAGS.map(t => <button key={t} onClick={() => setTag(t)} className={`rounded-md border px-2 py-1 text-[11.5px] font-semibold transition-colors ${tag === t ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-500 dark:border-zinc-700 dark:text-zinc-400'}`}>{t}</button>)}
            <button onClick={() => setShowCustom(s => !s)} className={`rounded-md border px-2 py-1 text-[11.5px] font-semibold transition-colors ${showCustom ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-500 dark:border-zinc-700 dark:text-zinc-400'}`}>+ Custom</button>
          </div>
        </div>
        {showCustom && (
          <div className="flex flex-wrap items-end gap-3 border-b border-zinc-100 bg-zinc-50 p-4 dark:border-zinc-800 dark:bg-zinc-800/30">
            <div className="flex-1" style={{ minWidth: 140 }}>
              <label className="mb-1 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Label</label>
              <input value={custom.label} onChange={e => setCustom(c => ({ ...c, label: e.target.value }))} placeholder="e.g. Build Wall 40" className="h-9 w-full rounded-lg border border-zinc-200 bg-white px-3 text-[13px] outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />
            </div>
            {RP_RES.map(r => (
              <div key={r.id} style={{ minWidth: 80 }}>
                <label className="mb-1 flex items-center gap-1 text-[11px] font-semibold uppercase tracking-wide" style={{ color: r.color }}>{r.emoji}</label>
                <input type="number" value={custom[r.id] || ''} onChange={e => setCustom(c => ({ ...c, [r.id]: +e.target.value || 0 }))} placeholder="0" className="h-9 w-full rounded-lg border border-zinc-200 bg-white px-2 text-[12px] tabular-nums outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />
              </div>
            ))}
            <button onClick={addCustom} className="h-9 rounded-lg bg-brand px-3 text-[12.5px] font-semibold text-white hover:brightness-110">Add</button>
          </div>
        )}
        <div className="grid grid-cols-1 gap-px bg-zinc-100 dark:bg-zinc-800 sm:grid-cols-2 lg:grid-cols-3">
          {presets.map(p => {
            const on = goals.includes(p.id);
            return (
              <button key={p.id} onClick={() => toggleGoal(p.id)} className={`flex items-center gap-3 bg-white p-3.5 text-left transition-colors hover:bg-zinc-50 dark:bg-zinc-900 dark:hover:bg-zinc-800/70 ${on ? 'ring-1 ring-inset ring-brand/40' : ''}`}>
                <span className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${on ? 'border-brand bg-brand' : 'border-zinc-300 dark:border-zinc-600'}`}>{on && <Icon name="check" size={11} className="text-white" stroke={3} />}</span>
                <div className="min-w-0 flex-1">
                  <div className="text-[13px] font-semibold text-zinc-900 dark:text-white">{p.label}</div>
                  <div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-zinc-400">
                    <span className="rounded bg-zinc-100 px-1.5 py-0.5 font-medium dark:bg-zinc-800">{p.tag}</span>
                    {RP_RES.filter(r => (p[r.id] || 0) > 0).slice(0, 3).map(r => <span key={r.id} style={{ color: r.color }}>{r.emoji} {rpNum(p[r.id])}{r.id !== 'gold' ? 'M' : 'M'}</span>)}
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </Card>

      {/* totals */}
      {goals.length > 0 && (
        <Card className="overflow-hidden border-brand/20">
          <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
            <Icon name="bolt" size={16} className="text-brand" />
            <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Total required</span>
            <span className="text-[11.5px] text-zinc-400">{goals.length} upgrade{goals.length !== 1 ? 's' : ''} · {covered}/{RP_RES.filter(r => totals[r.id] > 0).length} resources covered</span>
            <button onClick={() => setGoals([])} className="ml-auto text-[11.5px] text-zinc-400 hover:text-brand">Clear all</button>
          </div>
          <div className="grid grid-cols-1 gap-px bg-zinc-100 dark:bg-zinc-800 sm:grid-cols-5">
            {RP_RES.map(r => {
              const need = totals[r.id], have = stock[r.id] || 0, gap = gaps[r.id];
              const pct = need > 0 ? Math.min(100, have / need * 100) : 100;
              return (
                <div key={r.id} className="bg-white p-4 dark:bg-zinc-900">
                  <div className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wide" style={{ color: r.color }}>{r.emoji} {r.label}</div>
                  <div className="mt-1 text-[18px] font-bold tabular-nums text-zinc-900 dark:text-white">{need > 0 ? rpNum(need) + 'M' : '—'}</div>
                  {need > 0 && (
                    <>
                      <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="h-full rounded-full" style={{ width: pct + '%', background: gap === 0 ? '#16a34a' : r.color }}></div></div>
                      {gap > 0 ? <div className="mt-1 text-[11px] font-semibold tabular-nums text-rose-500">−{rpNum(gap)}M short</div>
                        : <div className="mt-1 flex items-center gap-1 text-[11px] font-semibold text-emerald-500"><Icon name="check" size={12} stroke={3} />Covered</div>}
                    </>
                  )}
                </div>
              );
            })}
          </div>
        </Card>
      )}

      {goals.length === 0 && <Card className="py-10 text-center text-[13px] text-zinc-400">Select upgrades above to see the total RSS bill and what you still need.</Card>}
      <p className="px-1 text-[11.5px] text-zinc-400">Enter your current stockpile, then tick your planned upgrades — the planner sums up the total bill and shows you which resources you're short on. Costs are from the ViG data sheets. Use "Custom" to add any upgrade not listed.</p>
    </div>
  );
}
window.ResourcePlannerPage = ResourcePlannerPage;
