/* What-if budget Reallocator ======================================= */

function ReallocatorModal({ open, onClose, accountId }){
  /* The reallocator models revenue via ROAS — meaningless for accounts
     where ROAS is blocklisted (e.g. Al Munawarah). Guard applied AFTER
     hooks (below) to keep the hook order stable across renders. */
  const roasBlocked = typeof metricHiddenFor==='function' && metricHiddenFor(accountId, 'roas');
  /* Build base allocations from current platform spend */
  const base = useMemo(()=>{
    const arr = platformBreakdown(accountId).map(m => {
      const p = PLATFORMS.find(x=>x.id===m.platform) || {};
      return { id:m.platform, label:(p.short||m.platform), tone:(p.tone||'#8351ff'), spend:m.spend, roas:m.roas, base:m.spend };
    }).filter(p => p.spend > 0);
    const total = arr.reduce((s,p)=>s+p.spend, 0);
    return { arr, total };
  }, [accountId, open]);

  const [alloc, setAlloc] = useState(() => Object.fromEntries(base.arr.map(p=>[p.id, p.spend])));
  const [horizon, setHorizon] = useState(7); // days

  useEffect(() => {
    if (open) setAlloc(Object.fromEntries(base.arr.map(p=>[p.id, p.spend])));
  }, [open, base]);

  const totalNow = useMemo(()=>Object.values(alloc).reduce((s,v)=>s+v,0), [alloc]);

  /* Update a single platform — redistribute delta across others proportionally */
  const setPlatform = (id, value) => {
    setAlloc(prev => {
      const newVal = Math.max(0, Math.round(value));
      const oldVal = prev[id];
      const diff = newVal - oldVal;
      const others = base.arr.filter(p => p.id !== id);
      const othersSum = others.reduce((s,p)=>s+prev[p.id], 0);
      const next = { ...prev, [id]: newVal };
      // Distribute -diff proportionally to others
      if (othersSum > 0){
        others.forEach(p => {
          const share = prev[p.id]/othersSum;
          next[p.id] = Math.max(0, Math.round(prev[p.id] - diff*share));
        });
      }
      return next;
    });
  };

  /* Projected revenue with diminishing returns */
  const projection = useMemo(()=>{
    const rows = base.arr.map(p => {
      const baseRev = p.spend * p.roas;
      const newSpend = alloc[p.id] || 0;
      const newRev = projectedRevenueFrom(p.spend, p.roas, newSpend);
      const baseRoas = p.roas;
      const newRoas = newSpend > 0 ? newRev / newSpend : 0;
      return {
        ...p,
        newSpend, newRev,
        deltaRev: newRev - baseRev,
        deltaSpend: newSpend - p.spend,
        newRoas,
        roasDelta: newRoas - baseRoas,
      };
    });
    const baseTotal  = rows.reduce((s,r)=>s + r.spend * r.roas, 0);
    const newTotal   = rows.reduce((s,r)=>s + r.newRev, 0);
    return { rows, baseTotal, newTotal, gain: newTotal - baseTotal, ratio: newTotal / baseTotal };
  }, [base, alloc, accountId]);

  const reset = () => setAlloc(Object.fromEntries(base.arr.map(p=>[p.id, p.spend])));

  if (roasBlocked) return (
    <Modal open={open} onClose={onClose} width={480}>
      <div className="p-6 text-center">
        <div className="text-[14px] font-bold mb-1.5">Reallocation unavailable</div>
        <div className="text-[12.5px] text-ink-500 dark:text-ink-300">
          Budget reallocation is ROAS-driven, and ROAS is disabled for this account
          (no revenue tracking). Pick another account to use this tool.
        </div>
        <div className="mt-4"><Btn variant="ghost" onClick={onClose}>Close</Btn></div>
      </div>
    </Modal>
  );

  return (
    <Modal open={open} onClose={onClose} width={760}>
      <div className="px-6 pt-5 pb-3 flex items-center justify-between border-b border-ink-200 dark:border-white/10">
        <div className="flex items-center gap-2">
          <span className="inline-flex h-7 w-7 rounded-lg bg-accent-100 text-accent-700 dark:bg-accent-500/15 dark:text-accent-200 items-center justify-center">
            <Icon name="sparkles" size={14}/>
          </span>
          <div>
            <div className="text-[15px] font-semibold leading-none">Budget reallocator</div>
            <div className="text-[12px] text-ink-500 dark:text-ink-300 mt-1">Shift spend across platforms — projected revenue updates instantly.</div>
          </div>
        </div>
        <button onClick={onClose} className="h-8 w-8 grid place-items-center rounded-lg hover:bg-ink-100 dark:hover:bg-white/10">
          <Icon name="x"/>
        </button>
      </div>

      <div className="px-6 py-5 space-y-5 overflow-auto">
        {/* Top summary */}
        <div className="grid grid-cols-3 gap-3">
          <div className="rounded-xl border border-ink-200 dark:border-white/10 p-3 bg-ink-50/50 dark:bg-white/[0.02]">
            <div className="text-[10.5px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300">Total spend</div>
            <div className="mt-1 text-[20px] font-semibold tabular">{fmt(totalNow,'currency')}</div>
            <div className={`text-[11px] font-mono mt-0.5 ${totalNow===base.total?'text-ink-400':'text-amber-600 dark:text-amber-400'}`}>
              {totalNow===base.total?'unchanged':`${totalNow>base.total?'+':''}${(totalNow-base.total).toLocaleString()} vs base`}
            </div>
          </div>
          <div className="rounded-xl border border-ink-200 dark:border-white/10 p-3 bg-ink-50/50 dark:bg-white/[0.02]">
            <div className="text-[10.5px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300">Projected revenue</div>
            <div className="mt-1 text-[20px] font-semibold tabular text-emerald-700 dark:text-emerald-400">{fmt(Math.round(projection.newTotal),'currency')}</div>
            <div className={`text-[11px] font-mono mt-0.5 ${projection.gain>=0?'text-emerald-600 dark:text-emerald-400':'text-rose-600 dark:text-rose-400'}`}>
              {projection.gain>=0?'+':''}{fmt(Math.round(projection.gain),'currency')} ({((projection.ratio-1)*100).toFixed(1)}%)
            </div>
          </div>
          <div className="rounded-xl border border-ink-200 dark:border-white/10 p-3 bg-ink-50/50 dark:bg-white/[0.02]">
            <div className="text-[10.5px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300">Implied ROAS</div>
            <div className="mt-1 text-[20px] font-semibold tabular">{(projection.newTotal/Math.max(totalNow,1)).toFixed(2)}×</div>
            <div className="text-[11px] font-mono mt-0.5 text-ink-400">{horizon}d horizon</div>
          </div>
        </div>

        {/* Sliders */}
        <div className="space-y-3">
          {projection.rows.length===0 && (
            <div className="text-center text-[12.5px] text-ink-400 py-8">No platform spend in this range yet — connect or import data first.</div>
          )}
          {projection.rows.map(r => {
            const sliderMax = Math.round(r.spend * 2.5);
            const pctChange = ((r.newSpend - r.spend)/r.spend)*100;
            const efficiency = r.newRoas / r.roas;  // 1.0 = same as baseline
            return (
              <div key={r.id} className="rounded-xl border border-ink-200 dark:border-white/10 p-3 bg-white dark:bg-ink-900/40">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <PlatformChip p={r.id} size={22}/>
                    <div>
                      <div className="text-[13px] font-semibold">{r.label}</div>
                      <div className="text-[10.5px] font-mono text-ink-400">base {fmt(r.spend,'currency')} · base ROAS {r.roas.toFixed(2)}×</div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="text-[16px] font-semibold tabular">{fmt(r.newSpend,'currency')}</div>
                    <div className={`text-[11px] font-mono ${pctChange>0?'text-emerald-600 dark:text-emerald-400':pctChange<0?'text-rose-600 dark:text-rose-400':'text-ink-400'}`}>
                      {pctChange>=0?'+':''}{pctChange.toFixed(1)}%
                    </div>
                  </div>
                </div>
                {/* Slider */}
                <div className="relative">
                  <input type="range" min="0" max={sliderMax} step="50" value={r.newSpend}
                    onChange={e => setPlatform(r.id, +e.target.value)}
                    className="w-full accent-accent-500"
                    style={{ accentColor: r.tone }}/>
                  {/* Base marker */}
                  <div className="absolute -top-1 -bottom-1 w-px bg-ink-400" style={{ left:`${(r.spend/sliderMax)*100}%` }}/>
                </div>
                <div className="mt-1 grid grid-cols-3 gap-2 text-[11px]">
                  <div>
                    <span className="text-ink-400">Proj. revenue </span>
                    <span className="font-mono tabular font-semibold">{fmt(Math.round(r.newRev),'currency')}</span>
                  </div>
                  <div>
                    <span className="text-ink-400">Implied ROAS </span>
                    <span className={`font-mono tabular font-semibold ${r.roasDelta>=0?'text-emerald-600 dark:text-emerald-400':'text-rose-600 dark:text-rose-400'}`}>
                      {r.newRoas.toFixed(2)}×
                    </span>
                  </div>
                  <div className="text-right">
                    <span className="text-ink-400">Efficiency </span>
                    <span className="font-mono tabular">{(efficiency*100).toFixed(0)}%</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div className="rounded-xl bg-amber-50 dark:bg-amber-500/5 border border-amber-200/60 dark:border-amber-500/20 p-3 flex items-start gap-2 text-[11.5px] text-amber-800 dark:text-amber-300">
          <Icon name="info" size={13} className="mt-0.5 flex-shrink-0"/>
          <div>
            <div className="font-semibold mb-0.5">Diminishing-returns model</div>
            Projections derive from each platform's historical efficiency curve (revenue ∝ spend<sup>0.78</sup>). Treat as directional, not predictive.
          </div>
        </div>
      </div>

      <div className="px-6 h-14 border-t border-ink-200 dark:border-white/10 flex items-center justify-between bg-ink-50/40 dark:bg-white/[0.02]">
        <Btn variant="ghost" size="sm" onClick={reset}>Reset to current</Btn>
        <div className="flex items-center gap-2">
          <Btn variant="ghost" onClick={onClose}>Discard</Btn>
          <Btn variant="accent" icon="check" onClick={onClose}>Apply allocation</Btn>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { ReallocatorModal });
