/* global React, window */
const { useState: useStateS, useMemo: useMemoS } = React;
const { ENGINES, PRESETS, CONF, fmt, calc } = window;

function ScenarioBuilder({ engines, setEngines, shares, setShares, pe, setPe, onApplyPreset }) {
  const [focus, setFocus] = useStateS('hpu');
  const [preset, setPreset] = useStateS('beachhead');

  const results = useMemoS(() => {
    const per = {};
    let totalProfit = 0, totalRev = 0, totalTip = 0, activeCount = 0;
    Object.entries(engines).forEach(([k, e]) => {
      const r = calc(e);
      per[k] = r;
      totalProfit += r.profit;
      totalRev += r.rev;
      totalTip += r.tipRev;
      if (e.enabled) activeCount++;
    });
    const netIncome = totalProfit;
    const mcap = netIncome * pe;
    const price = mcap / (shares * 1e6);
    return { per, totalProfit, totalRev, totalTip, netIncome, mcap, price, activeCount };
  }, [engines, pe, shares]);

  const upd = (k, patch) => setEngines(prev => ({ ...prev, [k]: { ...prev[k], ...patch } }));

  const applyPreset = (key) => {
    setPreset(key);
    onApplyPreset(key);
  };

  const fe = engines[focus];
  const isSale = fe.salePrice !== undefined;

  // sorted by profit contribution desc
  const sorted = Object.entries(engines).filter(([, e]) => e.enabled)
    .map(([k, e]) => ({ k, e, profit: results.per[k].profit }))
    .sort((a, b) => b.profit - a.profit);

  const maxProfit = Math.max(...sorted.map(s => s.profit), 1);

  return (
    <div>
      {/* Preset selector + top-line readout */}
      <div className="scenario-top" style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginRight: 8 }}>Preset</span>
          {Object.entries(PRESETS).map(([k, p]) => (
            <button key={k} className={`btn ${preset === k ? 'primary' : ''}`} onClick={() => applyPreset(k)}>
              {p.label}
            </button>
          ))}
          <span style={{ width: 1, height: 20, background: 'var(--line)', margin: '0 8px' }} />
          <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--fg-2)' }}>
            P/E <input type="number" value={pe} onChange={e => setPe(Math.max(5, Math.min(60, +e.target.value)))}
              style={{ width: 48, background: 'var(--bg-2)', border: '1px solid var(--line)', color: 'var(--fg-0)', padding: '3px 6px', borderRadius: 3, fontFamily: 'var(--mono)' }} />
          </span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--fg-2)' }}>
            Shares (M) <input type="number" value={shares} onChange={e => setShares(Math.max(30, Math.min(100, +e.target.value)))}
              style={{ width: 52, background: 'var(--bg-2)', border: '1px solid var(--line)', color: 'var(--fg-0)', padding: '3px 6px', borderRadius: 3, fontFamily: 'var(--mono)' }} />
          </span>
        </div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'baseline' }}>
          <div>
            <div className="card-label">Implied Price</div>
            <div className="num" style={{ fontSize: 36, color: 'var(--accent)', letterSpacing: '-0.03em', lineHeight: 1 }}>${results.price.toFixed(0)}</div>
          </div>
          <div>
            <div className="card-label">Net Income</div>
            <div className="num" style={{ fontSize: 22, color: 'var(--fg-0)', lineHeight: 1 }}>{fmt(results.netIncome)}</div>
          </div>
          <div>
            <div className="card-label">Market Cap</div>
            <div className="num" style={{ fontSize: 22, color: 'var(--fg-0)', lineHeight: 1 }}>{fmt(results.mcap)}</div>
          </div>
        </div>
      </div>

      <div className="scenario-grid">
        {/* LEFT: engine selector */}
        <div>
          <div className="card-label" style={{ marginBottom: 10 }}>Revenue Engines (click to edit)</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {Object.entries(engines).map(([k, e]) => (
              <div key={k} style={{ position: 'relative' }}>
                <button
                  className={`engine-btn ${focus === k ? 'selected' : ''} ${!e.enabled ? 'off' : ''}`}
                  onClick={() => setFocus(k)}
                  style={{ width: '100%', paddingRight: 28 }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ width: 6, height: 6, borderRadius: '50%', background: e.color, flexShrink: 0 }} />
                    <span style={{ fontWeight: 600, fontSize: 10 }}>{e.short}</span>
                  </div>
                  <div style={{ fontSize: 9, color: 'var(--fg-3)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {e.enabled ? fmt(results.per[k].profit) : 'off'}
                  </div>
                </button>
                <label style={{ position: 'absolute', right: 6, top: 6, cursor: 'pointer' }}>
                  <input
                    type="checkbox"
                    checked={e.enabled}
                    onChange={(ev) => upd(k, { enabled: ev.target.checked })}
                    style={{ accentColor: 'var(--accent)', cursor: 'pointer' }}
                  />
                </label>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 16, padding: 12, background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 6 }}>
            <div className="card-label">Total Revenue</div>
            <div className="num" style={{ fontSize: 18, color: 'var(--fg-0)' }}>{fmt(results.totalRev + results.totalTip)}</div>
            {results.totalTip > 0 && (
              <div style={{ fontSize: 10, color: 'var(--fg-3)', fontFamily: 'var(--mono)', marginTop: 2 }}>
                incl. {fmt(results.totalTip)} tipping fees
              </div>
            )}
          </div>
        </div>

        {/* CENTER: profit waterfall + focused engine editor */}
        <div>
          <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 8, padding: 20, marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <div>
                <div className="card-label">Profit contribution</div>
                <div style={{ fontSize: 14, color: 'var(--fg-1)', marginTop: 2 }}>Engines ranked by net profit</div>
              </div>
              <div className="num" style={{ fontSize: 18, color: 'var(--fg-0)' }}>{fmt(results.totalProfit)}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {sorted.slice(0, 8).map(({ k, e, profit }) => (
                <div key={k} style={{ display: 'grid', gridTemplateColumns: '90px 1fr 80px', gap: 10, alignItems: 'center' }}>
                  <div style={{ fontSize: 11, color: focus === k ? 'var(--fg-0)' : 'var(--fg-2)', fontWeight: focus === k ? 600 : 400, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {e.short}
                  </div>
                  <div style={{ height: 20, position: 'relative', background: 'var(--bg-2)', borderRadius: 3 }}>
                    <div style={{
                      position: 'absolute', top: 0, bottom: 0, left: 0,
                      width: `${(profit / maxProfit) * 100}%`,
                      background: e.color,
                      borderRadius: 3,
                      opacity: focus === k ? 1 : 0.7,
                      transition: 'width 0.3s',
                    }} />
                  </div>
                  <div className="num" style={{ fontSize: 11, color: 'var(--fg-1)', textAlign: 'right' }}>{fmt(profit)}</div>
                </div>
              ))}
              {sorted.length === 0 && (
                <div style={{ color: 'var(--fg-3)', fontSize: 12, fontStyle: 'italic', padding: 12 }}>No engines active. Enable one from the left.</div>
              )}
            </div>
          </div>

          <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 8, padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <div style={{ width: 10, height: 10, borderRadius: '50%', background: fe.color }} />
              <div style={{ fontSize: 15, color: 'var(--fg-0)', fontWeight: 500, fontFamily: 'var(--serif)', letterSpacing: '-0.01em' }}>{fe.name}</div>
              <div className="chip" style={{ marginLeft: 'auto', borderColor: CONF[fe.confidence].color, color: CONF[fe.confidence].color, background: `${CONF[fe.confidence].color}14` }}>
                {CONF[fe.confidence].label}
              </div>
              {!fe.core && <span className="chip">Optional</span>}
            </div>

            <div className="slider-row">
              <div className="slider-head">
                <div>
                  <div className="slider-lbl">Market share</div>
                  <div className="slider-note">TAM: {fe.tam >= 1000 ? (fe.tam/1000).toFixed(1) + 'B' : fe.tam}{fe.tam < 1000 ? 'M' : ''} {fe.unit}/yr · {fe.tamNote}</div>
                </div>
                <div className="slider-val">{fe.share.toFixed(fe.share < 1 ? 2 : 1)}%</div>
              </div>
              <input type="range" min="0" max={fe.maxShare} step="0.05" value={fe.share}
                onChange={(e) => upd(focus, { share: +e.target.value })} />
            </div>

            {isSale ? (
              <>
                <div className="slider-row">
                  <div className="slider-head">
                    <div className="slider-lbl">Product sale price ($/ton)</div>
                    <div className="slider-val">${fe.salePrice}</div>
                  </div>
                  <input type="range" min="800" max="3000" step="50" value={fe.salePrice}
                    onChange={(e) => upd(focus, { salePrice: +e.target.value })} />
                </div>
                <div className="slider-row">
                  <div className="slider-head">
                    <div className="slider-lbl">Royalty %</div>
                    <div className="slider-val">{fe.royaltyPct}%</div>
                  </div>
                  <input type="range" min="4" max="20" step="0.5" value={fe.royaltyPct}
                    onChange={(e) => upd(focus, { royaltyPct: +e.target.value })} />
                </div>
                <div className="slider-row">
                  <div className="slider-head">
                    <div className="slider-lbl">Yield %</div>
                    <div className="slider-val">{fe.yieldPct}%</div>
                  </div>
                  <input type="range" min="40" max="95" step="1" value={fe.yieldPct}
                    onChange={(e) => upd(focus, { yieldPct: +e.target.value })} />
                </div>
              </>
            ) : (
              <div className="slider-row">
                <div className="slider-head">
                  <div className="slider-lbl">Royalty $/bbl</div>
                  <div className="slider-val">${fe.royaltyPerUnit.toFixed(2)}</div>
                </div>
                <input type="range" min="0.5" max="5" step="0.05" value={fe.royaltyPerUnit}
                  onChange={(e) => upd(focus, { royaltyPerUnit: +e.target.value })} />
              </div>
            )}

            <div className="slider-row">
              <div className="slider-head">
                <div className="slider-lbl">Net margin</div>
                <div className="slider-val">{fe.margin}%</div>
              </div>
              <input type="range" min="40" max="85" step="1" value={fe.margin}
                onChange={(e) => upd(focus, { margin: +e.target.value })} />
            </div>
          </div>
        </div>

        {/* RIGHT: engine readout */}
        <div>
          <div className="card-label" style={{ marginBottom: 10 }}>{fe.short} Output</div>
          <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 8, padding: 18 }}>
            <div style={{ marginBottom: 14 }}>
              <div className="card-label">Volume processed</div>
              <div className="num" style={{ fontSize: 18, color: 'var(--fg-0)', marginTop: 2 }}>
                {(results.per[focus].vol / 1e6).toFixed(results.per[focus].vol < 1e7 ? 2 : 1)}M
              </div>
              <div style={{ fontSize: 10, color: 'var(--fg-3)', fontFamily: 'var(--mono)' }}>{fe.unit}/yr</div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <div className="card-label">Revenue</div>
              <div className="num" style={{ fontSize: 18, color: 'var(--fg-0)', marginTop: 2 }}>{fmt(results.per[focus].rev)}</div>
            </div>
            {results.per[focus].tipRev > 0 && (
              <div style={{ marginBottom: 14 }}>
                <div className="card-label">Tipping fees</div>
                <div className="num" style={{ fontSize: 16, color: 'var(--pos)', marginTop: 2 }}>+{fmt(results.per[focus].tipRev)}</div>
              </div>
            )}
            <div style={{ marginBottom: 14 }}>
              <div className="card-label">Net profit</div>
              <div className="num" style={{ fontSize: 22, color: 'var(--accent)', marginTop: 2 }}>{fmt(results.per[focus].profit)}</div>
            </div>
            {fe.plantSize && (
              <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, marginTop: 14 }}>
                <div className="card-label">Plant equivalents</div>
                <div className="num" style={{ fontSize: 16, color: 'var(--fg-1)' }}>
                  ~{Math.round(results.per[focus].vol / fe.plantSize)} plants
                </div>
                <div style={{ fontSize: 10, color: 'var(--fg-3)', fontFamily: 'var(--mono)', marginTop: 2 }}>
                  @ {fe.plantSize.toLocaleString()} {fe.unit}/yr each
                </div>
              </div>
            )}
          </div>

          {fe.overlap && (
            <div style={{ marginTop: 12, padding: 12, background: 'rgba(217,169,91,0.06)', border: '1px solid rgba(217,169,91,0.25)', borderRadius: 6 }}>
              <div style={{ fontSize: 10, color: 'var(--warn)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 4 }}>⚠ Overlap</div>
              <div style={{ fontSize: 11, color: 'var(--fg-1)', lineHeight: 1.5 }}>
                May overlap with {engines[fe.overlap].short}. Do not stack full TAM on both.
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.ScenarioBuilder = ScenarioBuilder;
