// valuation-screen.jsx — rich Valuation screen built on window.ValuationEngine
// ─────────────────────────────────────────────────────────────────────
// Replaces the original Insights → Valuation tab with a 7-sub-tab
// surface that exposes everything the engine can do:
//
//   01 Summary     — headline number + KPIs + multiple build-up + comps
//   02 DCF         — per-stream forecast, year-by-year cashflow, NPV @ rate
//   03 Sensitivity — tornado + 2-D heatmap (discount × growth)
//   04 Monte Carlo — 10k draws, histogram, P5/P50/P95 bands
//   05 Scenarios   — bull/base/bear/breakup/synch with own inputs
//   06 Per-work    — Shapley attribution: top contributors to NPV
//   07 Buy-side    — IRR, payback, breakeven sale price
//
// Public surface:
//   window.ValuationScreen({ go })   — the React component
// ─────────────────────────────────────────────────────────────────────

(function () {
  const { useMemo, useState, useEffect } = React;
  const VE = window.ValuationEngine;

  // ───────── formatters
  const fmtUsd = (n) => {
    if (n == null || !isFinite(n)) return '—';
    const a = Math.abs(n);
    const sign = n < 0 ? '-' : '';
    if (a >= 1e9) return sign + '$' + (a/1e9).toFixed(2) + 'B';
    if (a >= 1e6) return sign + '$' + (a/1e6).toFixed(2) + 'M';
    if (a >= 1e3) return sign + '$' + (a/1e3).toFixed(1) + 'k';
    return sign + '$' + Math.round(a).toLocaleString();
  };
  const fmtPct = (n, withSign) => {
    if (n == null || !isFinite(n)) return '—';
    return (withSign && n > 0 ? '+' : '') + (n*100).toFixed(1) + '%';
  };
  const fmtX = (n) => 'x ' + (n || 0).toFixed(2);

  // ───────── primitives
  function Mono({ children, color = 'var(--ink-2)', size = 11, upper, style }) {
    return <span className={'ff-mono ' + (upper ? 'upper' : '')}
      style={{ fontSize: size, color, letterSpacing: upper ? '.12em' : '.04em', ...style }}>{children}</span>;
  }
  function Pill({ children, fg = 'var(--ink-2)', dot, bg }) {
    return <span className="ff-mono upper" style={{
      fontSize: 9, letterSpacing: '.12em', padding: '3px 8px',
      color: fg, border: '1px solid ' + fg, background: bg || 'transparent',
      display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap'
    }}>
      {dot && <span style={{ display:'inline-block', width: 5, height: 5, borderRadius: 3, background: fg }}/>}
      {children}
    </span>;
  }
  function Kpi({ l, v, sub, accent, danger, ok }) {
    return (
      <div style={{ padding: '20px 22px', minHeight: 110, display:'flex', flexDirection:'column', gap: 6 }}>
        <Mono upper size={9} color="var(--ink-3)">{l}</Mono>
        <div className="ff-mono num" style={{
          fontSize: 30, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1,
          color: danger ? 'var(--danger)' : ok ? 'var(--ok)' : accent ? 'var(--accent-ink)' : 'var(--ink)',
          background: accent ? 'var(--accent)' : 'transparent',
          padding: accent ? '2px 6px' : 0,
          alignSelf: 'flex-start',
          marginTop: 4,
        }}>{v}</div>
        {sub && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>{sub}</div>}
      </div>
    );
  }
  function SectionHead({ children, sub }) {
    return (
      <div style={{ marginBottom: 12 }}>
        <Mono upper size={10} color="var(--ink-3)" style={{ display: 'block' }}>{children}</Mono>
        {sub && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4, lineHeight: 1.5 }}>{sub}</div>}
      </div>
    );
  }
  function Card({ children, style }) {
    return <div style={{ border: '1px solid var(--rule)', ...style }}>{children}</div>;
  }
  function HRule() { return <div style={{ height: 1, background: 'var(--rule-soft, var(--bg-2))' }}/>; }

  // ═════════════════════════════════════════════════════════════════
  // 01 SUMMARY SUB-TAB
  // ═════════════════════════════════════════════════════════════════
  function SummaryView({ valuation }) {
    const v = valuation;
    return (
      <div>
        {/* headline */}
        <Card style={{ padding: '32px 36px', marginBottom: 24, display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: 24 }}>
          <div>
            <Mono upper size={10} color="var(--ink-3)">CATALOG VALUATION · 2026 Q1 · BLENDED FAIR VALUE</Mono>
            <div className="ff-mono num" style={{ fontSize: 56, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 8 }}>
              {fmtUsd(v.value)}
            </div>
            <div style={{ marginTop: 8, color: 'var(--ink-2)', fontSize: 13, lineHeight: 1.5, maxWidth: 640 }}>
              Three methods, weighted: market multiple ({fmtUsd(v.marketValue)} · 45%), DCF @ {(v.opts.discountRate*100).toFixed(1)}% ({fmtUsd(v.dcfValue)} · 40%), comps regression ({fmtUsd(v.regressionValue)} · 15%).
              Confidence band: <Mono color="var(--ink)">{fmtUsd(v.lowValue)}–{fmtUsd(v.highValue)}</Mono>.
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 12 }}>
            <Pill fg="var(--ok)" dot>BUY-SIDE READY</Pill>
            <button onClick={() => window.dispatchEvent(new CustomEvent('astro-toast',{detail:{msg:'Valuation report (28 pp) queued · ready in 3 min',tone:'ok'}}))} className="ff-mono upper" style={{ fontSize: 10, letterSpacing: '.12em', padding: '8px 14px', background:'var(--ink)', color:'var(--bg)', border: 0, cursor:'pointer' }}>
              EXPORT REPORT →
            </button>
            <Mono size={10} color="var(--ink-3)">3 methods · 10 comps · 10y horizon</Mono>
          </div>
        </Card>

        {/* KPI strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', border: '1px solid var(--rule)', marginBottom: 32 }}>
          <Kpi l="TTM EARNINGS" v={fmtUsd(v.ttmEarnings)} sub="trailing 12 months · net to publisher"/>
          <div style={{ borderLeft: '1px solid var(--rule)' }}>
            <Kpi l="EFFECTIVE MULTIPLE" v={fmtX(v.multiple)} sub={`baseline ${fmtX(v.opts.baselineMultiple)} · regression band ${fmtX(v.regression.lowerBand)}–${fmtX(v.regression.upperBand)}`}/>
          </div>
          <div style={{ borderLeft: '1px solid var(--rule)' }}>
            <Kpi l="LIFETIME GROSS · 10Y" v={fmtUsd(v.lifetimeGross)} sub="undiscounted nominal · all 6 streams"/>
          </div>
          <div style={{ borderLeft: '1px solid var(--rule)' }}>
            <Kpi l={`NPV @ ${(v.opts.discountRate*100).toFixed(1)}%`} v={fmtUsd(v.dcfValue)} sub="risk-adjusted present value" accent/>
          </div>
        </div>

        {/* Multiple build-up + revenue composition */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, marginBottom: 32 }}>
          <div>
            <SectionHead sub="Each factor multiplies onto the prior. Negative factors shown as discounts.">MULTIPLE BUILD-UP</SectionHead>
            <Card>
              {v.factors.map((f, i) => (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '1fr 70px 90px',
                  gap: 14, padding: '12px 16px', alignItems: 'center',
                  borderBottom: i < v.factors.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none'
                }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{f.label}</div>
                    {f.hint && <Mono size={10} color="var(--ink-3)" style={{ marginTop: 2 }}>{f.hint}</Mono>}
                  </div>
                  <Mono size={11} color="var(--ink)" style={{ textAlign: 'right' }}>{fmtX(f.mult)}</Mono>
                  <div style={{ textAlign: 'right' }}>
                    {f.delta != null && (
                      <Mono size={11} color={f.delta > 0 ? 'var(--ok)' : f.delta < 0 ? 'var(--danger)' : 'var(--ink-3)'}>
                        {f.delta === 0 ? '—' : fmtPct(f.delta, true)}
                      </Mono>
                    )}
                  </div>
                </div>
              ))}
              <div style={{
                display: 'grid', gridTemplateColumns: '1fr 70px 90px',
                gap: 14, padding: '14px 16px', alignItems: 'center',
                background: 'var(--bg-2)',
              }}>
                <div style={{ fontSize: 12, fontWeight: 600 }}>EFFECTIVE MULTIPLE</div>
                <Mono size={12} color="var(--ink)" style={{ textAlign: 'right', fontWeight: 600 }}>{fmtX(v.multiple)}</Mono>
                <Mono size={11} color="var(--ink-2)" style={{ textAlign: 'right' }}>vs {fmtX(v.opts.baselineMultiple)}</Mono>
              </div>
            </Card>
          </div>
          <div>
            <SectionHead sub="Six streams, each with its own decay curve calibrated to MIDIA / IFPI data.">REVENUE COMPOSITION · TTM</SectionHead>
            <Card>
              {VE.REVENUE_STREAMS.map((s, i) => {
                const earned = v.ttmEarnings * s.share;
                return (
                  <div key={s.id} style={{
                    display: 'grid', gridTemplateColumns: '14px 1fr 80px 70px',
                    gap: 12, padding: '11px 14px', alignItems: 'center',
                    borderBottom: i < VE.REVENUE_STREAMS.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none'
                  }}>
                    <div style={{ width: 10, height: 10, background: s.color, borderRadius: 1 }}/>
                    <div>
                      <div style={{ fontSize: 12 }}>{s.label}</div>
                      <div style={{ position: 'relative', height: 4, background: 'var(--bg-2)', marginTop: 4 }}>
                        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: (s.share*100) + '%', background: s.color }}/>
                      </div>
                    </div>
                    <Mono size={11} color="var(--ink)" style={{ textAlign: 'right' }}>{fmtUsd(earned)}</Mono>
                    <Mono size={11} color={s.growth > 0 ? 'var(--ok)' : 'var(--danger)'} style={{ textAlign: 'right' }}>
                      {fmtPct(s.growth, true)}
                    </Mono>
                  </div>
                );
              })}
            </Card>
          </div>
        </div>

        {/* Comps */}
        <div>
          <SectionHead sub={`Linear regression on age vs. multiple. Predicted ${fmtX(v.regression.predictedMultiple)} for ${v.opts.catalogAgeYears}-yr catalog · 95% band ${fmtX(v.regression.lowerBand)}–${fmtX(v.regression.upperBand)}.`}>
            COMPARABLE DEALS · MARKET BENCHMARK
          </SectionHead>
          <Card>
            <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 60px 90px 80px 70px', gap: 12, padding: '8px 14px', background: 'var(--bg-2)', borderBottom: '1px solid var(--rule)' }}>
              <Mono upper size={9} color="var(--ink-3)">DEAL</Mono>
              <Mono upper size={9} color="var(--ink-3)">YEAR</Mono>
              <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>HEADLINE</Mono>
              <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>TTM</Mono>
              <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>MULTIPLE</Mono>
            </div>
            {VE.COMPARABLES.map((c, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '1.6fr 60px 90px 80px 70px',
                gap: 12, padding: '11px 14px', alignItems: 'center',
                borderBottom: i < VE.COMPARABLES.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none'
              }}>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500 }}>{c.name}</div>
                  <Mono size={10} color="var(--ink-3)" style={{ marginTop: 2 }}>{c.note} · {c.genre}</Mono>
                </div>
                <Mono size={11} color="var(--ink-2)">{c.year}</Mono>
                <Mono size={11} color="var(--ink)" style={{ textAlign: 'right' }}>{fmtUsd(c.value)}</Mono>
                <Mono size={11} color="var(--ink-2)" style={{ textAlign: 'right' }}>{fmtUsd(c.ttm)}</Mono>
                <div style={{ textAlign: 'right' }}>
                  <Mono size={11} color={c.mult >= v.multiple ? 'var(--ok)' : 'var(--ink-3)'}>
                    {fmtX(c.mult)}
                  </Mono>
                </div>
              </div>
            ))}
          </Card>
        </div>
      </div>
    );
  }

  // ═════════════════════════════════════════════════════════════════
  // 02 DCF SUB-TAB — per-stream stacked area + cashflow table
  // ═════════════════════════════════════════════════════════════════
  function DCFView({ valuation, opts, setOpts }) {
    const v = valuation;
    const fc = v.forecast;
    const W = 920, H = 240, padL = 60, padR = 18, padT = 18, padB = 32;
    const cw = W - padL - padR, ch = H - padT - padB;
    const years = fc.totals.length;
    const xStep = cw / (years + 1);
    // Stacked area: walk streams in order, compute cumulative offsets
    const maxTotal = Math.max(v.ttmEarnings, ...fc.totals) * 1.05;
    function yScale(val) { return padT + ch - (val / maxTotal) * ch; }

    // Build per-year stacks (year 0 = TTM)
    const yearsAll = [0].concat(fc.totals.map((_, i) => i + 1));
    function totalAt(yi) {
      if (yi === 0) return v.ttmEarnings;
      return fc.totals[yi - 1];
    }
    function streamAt(streamIdx, yi) {
      const s = fc.streams[streamIdx];
      if (yi === 0) return s.ttm;
      return s.yearly[yi - 1];
    }
    // for each stream build a polygon
    const polygons = fc.streams.map((s, sIdx) => {
      const top = [];
      const bot = [];
      for (let yi = 0; yi < yearsAll.length; yi++) {
        let cumBelow = 0;
        for (let k = 0; k < sIdx; k++) cumBelow += streamAt(k, yi);
        const cumThis = cumBelow + streamAt(sIdx, yi);
        const x = padL + xStep * (yi + 0.5);
        top.push([x, yScale(cumThis)]);
        bot.push([x, yScale(cumBelow)]);
      }
      const pts = top.concat(bot.reverse()).map(p => p.join(',')).join(' ');
      return { pts, color: s.color, label: s.label };
    });

    // discount-rate slider state
    const dr = opts.discountRate;
    const discountedCash = useMemo(() => {
      const flows = [v.ttmEarnings].concat(fc.totals);
      let cum = 0;
      const rows = flows.map((f, t) => {
        const discounted = f / Math.pow(1 + dr, t);
        cum += discounted;
        return { y: t, nominal: f, discounted, cumPv: cum };
      });
      return rows;
    }, [dr, v.ttmEarnings, fc.totals]);

    return (
      <div>
        <Card style={{ padding: '20px 24px', marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 24, alignItems: 'center' }}>
            <div>
              <Mono upper size={10} color="var(--ink-3)">DISCOUNTED CASH FLOW</Mono>
              <div className="ff-mono num" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 4 }}>{fmtUsd(v.dcfValue)}</div>
              <Mono size={11} color="var(--ink-3)" style={{ marginTop: 2, display: 'block' }}>NPV @ {(dr*100).toFixed(1)}% over {fc.totals.length}yr horizon</Mono>
            </div>
            <div>
              <Mono upper size={10} color="var(--ink-3)" style={{ display: 'block', marginBottom: 6 }}>DISCOUNT RATE · {(dr*100).toFixed(1)}%</Mono>
              <input type="range" min="4" max="18" step="0.25" value={(dr*100).toFixed(2)}
                onChange={e => setOpts(Object.assign({}, opts, { discountRate: parseFloat(e.target.value) / 100 }))}
                style={{ width: '100%' }}/>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
                <Mono size={10} color="var(--ink-3)">4%</Mono>
                <Mono size={10} color="var(--ink-3)">9% (typical)</Mono>
                <Mono size={10} color="var(--ink-3)">18%</Mono>
              </div>
            </div>
            <div>
              <Mono upper size={10} color="var(--ink-3)" style={{ display: 'block' }}>VS NOMINAL</Mono>
              <div className="ff-mono num" style={{ fontSize: 18, fontWeight: 500, marginTop: 4 }}>
                {fmtPct(v.dcfValue / v.lifetimeGross - 1)}
              </div>
              <Mono size={10} color="var(--ink-3)">discount of {fmtUsd(v.lifetimeGross - v.dcfValue)}</Mono>
            </div>
          </div>
        </Card>

        <div style={{ marginBottom: 24 }}>
          <SectionHead sub="Stacked area · 6 revenue streams · year 0 = TTM, years 1–10 = forecast">PER-STREAM 11-YEAR FORECAST</SectionHead>
          <Card style={{ padding: '14px 16px 6px' }}>
            <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: 'block' }}>
              {/* y grid */}
              {[0, 0.25, 0.5, 0.75, 1].map(t => {
                const y = padT + ch - t * ch;
                return <g key={t}>
                  <line x1={padL} y1={y} x2={W-padR} y2={y} stroke="var(--rule-soft, var(--bg-2))" strokeWidth="1"/>
                  <text x={padL - 6} y={y+3} textAnchor="end" fontSize="9" fill="var(--ink-3)" fontFamily="var(--ff-mono)">
                    {fmtUsd(maxTotal * t)}
                  </text>
                </g>;
              })}
              {/* stacked polygons */}
              {polygons.map((p, i) => (
                <polygon key={i} points={p.pts} fill={p.color} opacity="0.78" stroke="var(--bg)" strokeWidth="0.5"/>
              ))}
              {/* x labels */}
              {yearsAll.map((yi, i) => {
                const x = padL + xStep * (i + 0.5);
                return (
                  <text key={i} x={x} y={padT + ch + 16} textAnchor="middle" fontSize="9" fill="var(--ink-3)" fontFamily="var(--ff-mono)">
                    {yi === 0 ? 'TTM' : `Y+${yi}`}
                  </text>
                );
              })}
              {/* total line on top */}
              <polyline points={yearsAll.map((yi, i) => {
                const x = padL + xStep * (i + 0.5);
                return `${x},${yScale(totalAt(i))}`;
              }).join(' ')} fill="none" stroke="var(--ink)" strokeWidth="1.5" strokeDasharray="3 3" opacity="0.6"/>
            </svg>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, padding: '10px 0 4px' }}>
              {fc.streams.map(s => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 10, height: 10, background: s.color }}/>
                  <Mono size={10} color="var(--ink-2)">{s.label}</Mono>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <div>
          <SectionHead sub={`At ${(dr*100).toFixed(1)}% discount rate. Year-0 flow is TTM (undiscounted).`}>YEAR-BY-YEAR CASHFLOW TABLE</SectionHead>
          <Card>
            <div style={{
              display: 'grid', gridTemplateColumns: '60px 1fr 1fr 110px 1fr',
              padding: '8px 14px', background: 'var(--bg-2)', borderBottom: '1px solid var(--rule)',
              gap: 12,
            }}>
              <Mono upper size={9} color="var(--ink-3)">YEAR</Mono>
              <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>NOMINAL</Mono>
              <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>DISCOUNTED</Mono>
              <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>DF</Mono>
              <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>CUMULATIVE PV</Mono>
            </div>
            {discountedCash.map((row, i) => {
              const df = 1 / Math.pow(1 + dr, row.y);
              return (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '60px 1fr 1fr 110px 1fr',
                  padding: '9px 14px', alignItems: 'center', gap: 12,
                  borderBottom: i < discountedCash.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none',
                  background: row.y === 0 ? 'var(--bg-2)' : 'transparent',
                }}>
                  <Mono size={11} color={row.y === 0 ? 'var(--accent-ink, var(--ink))' : 'var(--ink-2)'}>
                    {row.y === 0 ? 'TTM' : `Y+${row.y}`}
                  </Mono>
                  <Mono size={11} color="var(--ink)" style={{textAlign:'right'}}>{fmtUsd(row.nominal)}</Mono>
                  <Mono size={11} color="var(--ink)" style={{textAlign:'right'}}>{fmtUsd(row.discounted)}</Mono>
                  <Mono size={11} color="var(--ink-3)" style={{textAlign:'right'}}>{df.toFixed(4)}</Mono>
                  <Mono size={11} color={row.y === discountedCash.length - 1 ? 'var(--ok)' : 'var(--ink-2)'} style={{textAlign:'right', fontWeight: row.y === discountedCash.length - 1 ? 600 : 400}}>
                    {fmtUsd(row.cumPv)}
                  </Mono>
                </div>
              );
            })}
          </Card>
        </div>
      </div>
    );
  }

  // ═════════════════════════════════════════════════════════════════
  // 03 SENSITIVITY SUB-TAB — tornado + 2-D heatmap
  // ═════════════════════════════════════════════════════════════════
  function SensitivityView({ opts }) {
    const tornado = useMemo(() => VE.tornado(opts), [opts]);
    const grid = useMemo(() => VE.sensitivityGrid(opts,
      { id: 'discountRate', from: 0.06, to: 0.14, steps: 7 },
      { id: 'ttmGrowth',    from: -0.02, to: 0.12, steps: 7 }
    ), [opts]);
    const baseValue = VE.compute(opts).value;
    const maxImpact = Math.max(...tornado.map(t => t.impact));

    // heatmap min/max
    let gMin = Infinity, gMax = -Infinity;
    grid.grid.forEach(row => row.forEach(v => { if (v < gMin) gMin = v; if (v > gMax) gMax = v; }));
    function heatColor(v) {
      const t = (v - gMin) / Math.max(1, gMax - gMin);
      // dark→accent ramp
      const r = Math.round(48 + (220 - 48) * t);
      const g = Math.round(48 + ( 90 - 48) * t);
      const b = Math.round(56 + ( 70 - 56) * t);
      return `rgb(${r},${g},${b})`;
    }

    return (
      <div>
        <Card style={{ padding: '24px 28px', marginBottom: 24 }}>
          <Mono upper size={10} color="var(--ink-3)">BASE CASE</Mono>
          <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 4 }}>{fmtUsd(baseValue)}</div>
          <Mono size={11} color="var(--ink-3)" style={{ marginTop: 4, display: 'block' }}>
            Each input perturbed independently around base. Bars show the swing in catalog value.
          </Mono>
        </Card>

        <div style={{ marginBottom: 32 }}>
          <SectionHead sub="One-variable sensitivity, sorted by impact magnitude. Width = swing.">TORNADO · ONE-VARIABLE SENSITIVITY</SectionHead>
          <Card style={{ padding: '14px 16px' }}>
            {tornado.map((t, i) => {
              const W = 100; // % space
              const lowPct = ((baseValue - t.lowValue) / maxImpact) * 50;
              const highPct = ((t.highValue - baseValue) / maxImpact) * 50;
              const fmtDelta = (d, mode) => mode === 'mult' ? `${d > 0 ? '+' : ''}${(d*100).toFixed(1)}%` : `${d > 0 ? '+' : ''}${typeof d === 'number' && Math.abs(d) >= 1 ? d.toFixed(1) : (d*100).toFixed(1) + (mode === 'add' && Math.abs(d) < 1 ? 'pp' : '')}`;
              return (
                <div key={t.id} style={{
                  display: 'grid', gridTemplateColumns: '180px 90px 1fr 90px',
                  gap: 14, padding: '8px 0', alignItems: 'center'
                }}>
                  <div style={{ fontSize: 12 }}>{t.label}</div>
                  <Mono size={11} color="var(--danger)" style={{textAlign:'right'}}>{fmtUsd(t.lowValue)}</Mono>
                  <div style={{ position: 'relative', height: 18, background: 'var(--bg-2)' }}>
                    <div style={{ position: 'absolute', left: '50%', top: 0, bottom: 0, width: 1, background: 'var(--ink-3)' }}/>
                    <div style={{ position: 'absolute', right: `${50}%`, width: `${lowPct}%`, top: 2, bottom: 2, background: 'var(--danger)', opacity: 0.7 }}/>
                    <div style={{ position: 'absolute', left: `${50}%`, width: `${highPct}%`, top: 2, bottom: 2, background: 'var(--ok)', opacity: 0.7 }}/>
                  </div>
                  <Mono size={11} color="var(--ok)" style={{textAlign:'right'}}>{fmtUsd(t.highValue)}</Mono>
                </div>
              );
            })}
          </Card>
        </div>

        <div>
          <SectionHead sub="Discount rate (x-axis) × TTM growth rate (y-axis). Heatmap of catalog value.">2-DIMENSIONAL SENSITIVITY GRID</SectionHead>
          <Card style={{ padding: '20px 24px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 16 }}>
              <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', paddingTop: 22, paddingBottom: 6 }}>
                <Mono size={10} color="var(--ink-3)">growth ↑</Mono>
                {grid.ys.slice().reverse().map((y, i) => (
                  <Mono size={10} color="var(--ink-3)" key={i} style={{textAlign:'right'}}>{(y*100).toFixed(1)}%</Mono>
                ))}
              </div>
              <div>
                <div style={{ display: 'grid', gridTemplateColumns: `repeat(${grid.xs.length}, 1fr)`, gap: 1, marginBottom: 6 }}>
                  {grid.xs.map((x, i) => (
                    <Mono size={10} color="var(--ink-3)" key={i} style={{textAlign:'center'}}>{(x*100).toFixed(1)}%</Mono>
                  ))}
                </div>
                <div style={{ display: 'grid', gridTemplateRows: `repeat(${grid.ys.length}, 1fr)`, gap: 1 }}>
                  {grid.grid.slice().reverse().map((row, i) => (
                    <div key={i} style={{ display: 'grid', gridTemplateColumns: `repeat(${grid.xs.length}, 1fr)`, gap: 1 }}>
                      {row.map((v, j) => (
                        <div key={j} style={{
                          background: heatColor(v),
                          padding: '14px 4px',
                          textAlign: 'center',
                          fontFamily: 'var(--ff-mono)', fontSize: 10,
                          color: '#fff', letterSpacing: '.04em',
                        }}>{fmtUsd(v)}</div>
                      ))}
                    </div>
                  ))}
                </div>
                <Mono size={10} color="var(--ink-3)" style={{ display: 'block', marginTop: 8, textAlign: 'center' }}>discount rate →</Mono>
              </div>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  // ═════════════════════════════════════════════════════════════════
  // 04 MONTE CARLO SUB-TAB
  // ═════════════════════════════════════════════════════════════════
  function MonteCarloView({ opts }) {
    const [iter, setIter] = useState(10000);
    const [running, setRunning] = useState(false);
    const [mc, setMc] = useState(() => VE.monteCarlo(Object.assign({}, opts, { iterations: 10000 })));

    function rerun(n) {
      setRunning(true);
      // synthetic delay so the UI feels real
      setTimeout(() => {
        setMc(VE.monteCarlo(Object.assign({}, opts, { iterations: n, seed: Date.now() & 0xffff })));
        setRunning(false);
      }, 350);
    }
    useEffect(() => { setMc(VE.monteCarlo(Object.assign({}, opts, { iterations: iter }))); /* eslint-disable-next-line */ }, [opts]);

    const W = 920, H = 240, padL = 60, padR = 18, padT = 18, padB = 36;
    const cw = W - padL - padR, ch = H - padT - padB;
    const maxC = Math.max(...mc.histogram.map(b => b.count));
    const bw = cw / mc.histogram.length;

    function xPos(value) {
      const range = mc.histogram[mc.histogram.length-1].to - mc.histogram[0].from;
      return padL + ((value - mc.histogram[0].from) / range) * cw;
    }

    return (
      <div>
        <Card style={{ padding: '24px 28px', marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr', gap: 0 }}>
            {[
              { l: 'P05', v: mc.p05, color: 'var(--danger)' },
              { l: 'P25', v: mc.p25, color: 'var(--ink-2)' },
              { l: 'MEDIAN', v: mc.median, color: 'var(--ink)' },
              { l: 'MEAN', v: mc.mean, color: 'var(--ink)' },
              { l: 'P75', v: mc.p75, color: 'var(--ink-2)' },
              { l: 'P95', v: mc.p95, color: 'var(--ok)' },
            ].map((s, i) => (
              <div key={i} style={{ borderLeft: i > 0 ? '1px solid var(--rule)' : 0, padding: '0 14px' }}>
                <Mono upper size={9} color="var(--ink-3)">{s.l}</Mono>
                <div className="ff-mono num" style={{ fontSize: 22, fontWeight: 500, color: s.color, marginTop: 4 }}>{fmtUsd(s.v)}</div>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 24, marginTop: 16, alignItems: 'center', borderTop: '1px solid var(--rule)', paddingTop: 14 }}>
            <Mono size={11} color="var(--ink-3)">{mc.n.toLocaleString()} iterations · σ = {fmtUsd(mc.stdev)} · CV = {(mc.stdev / mc.mean * 100).toFixed(1)}%</Mono>
            <div style={{ flex: 1 }}/>
            {[1000, 10000, 50000].map(n => (
              <button key={n} onClick={() => { setIter(n); rerun(n); }} disabled={running}
                className="ff-mono upper"
                style={{ fontSize: 10, letterSpacing: '.12em', padding: '6px 12px',
                  background: iter === n ? 'var(--ink)' : 'transparent',
                  color: iter === n ? 'var(--bg)' : 'var(--ink-2)',
                  border: '1px solid ' + (iter === n ? 'var(--ink)' : 'var(--rule)'),
                  cursor: running ? 'wait' : 'pointer',
                  opacity: running ? 0.5 : 1
                }}>
                {n.toLocaleString()} {running && iter === n ? '·' : ''}
              </button>
            ))}
          </div>
        </Card>

        <div style={{ marginBottom: 24 }}>
          <SectionHead sub={`${mc.n.toLocaleString()} Monte Carlo draws · 6 noisy inputs (TTM, growth, discount rate, concentration, rights, age) varied jointly. Vertical lines = key percentiles.`}>VALUATION DISTRIBUTION</SectionHead>
          <Card style={{ padding: '14px 16px 6px' }}>
            <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: 'block' }}>
              {/* y grid */}
              {[0, 0.5, 1].map(t => {
                const y = padT + ch - t * ch;
                return <g key={t}>
                  <line x1={padL} y1={y} x2={W-padR} y2={y} stroke="var(--rule-soft, var(--bg-2))" strokeWidth="1"/>
                  <text x={padL - 6} y={y+3} textAnchor="end" fontSize="9" fill="var(--ink-3)" fontFamily="var(--ff-mono)">
                    {Math.round(maxC * t).toLocaleString()}
                  </text>
                </g>;
              })}
              {/* histogram bars */}
              {mc.histogram.map((b, i) => {
                const h = (b.count / maxC) * ch;
                const x = padL + i * bw;
                const y = padT + ch - h;
                const mid = (b.from + b.to) / 2;
                const inP10P90 = mid >= mc.p10 && mid <= mc.p90;
                return (
                  <rect key={i} x={x+1} y={y} width={bw - 2} height={h}
                    fill={inP10P90 ? 'var(--ink)' : 'var(--ink-3)'}
                    opacity={inP10P90 ? 0.85 : 0.45}/>
                );
              })}
              {/* percentile markers */}
              {[
                { v: mc.p05, l: 'P5',  color: 'var(--danger)' },
                { v: mc.median, l: 'P50', color: 'var(--ink)' },
                { v: mc.p95, l: 'P95', color: 'var(--ok)' },
              ].map((m, i) => {
                const x = xPos(m.v);
                return (
                  <g key={i}>
                    <line x1={x} y1={padT} x2={x} y2={padT + ch} stroke={m.color} strokeWidth="1.5" strokeDasharray="4 3"/>
                    <text x={x} y={padT - 4} textAnchor="middle" fontSize="10" fill={m.color} fontFamily="var(--ff-mono)" fontWeight="600">{m.l}</text>
                    <text x={x} y={padT + ch + 14} textAnchor="middle" fontSize="9" fill={m.color} fontFamily="var(--ff-mono)">{fmtUsd(m.v)}</text>
                  </g>
                );
              })}
              {/* x axis label */}
              <text x={padL + cw/2} y={H - 8} textAnchor="middle" fontSize="10" fill="var(--ink-3)" fontFamily="var(--ff-mono)">catalog valuation →</text>
            </svg>
          </Card>
        </div>

        <div>
          <SectionHead sub="What the distribution tells us about deal certainty.">PROBABILITY STATEMENTS</SectionHead>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            {[
              { l: '90% confidence band', v: `${fmtUsd(mc.p05)} – ${fmtUsd(mc.p95)}`, sub: 'P5 to P95' },
              { l: 'Probability ≥ base mean', v: fmtPct(mc.draws.filter(d => d >= mc.mean).length / mc.n), sub: 'P(value ≥ μ)' },
              { l: 'Probability ≥ $50M', v: fmtPct(mc.draws.filter(d => d >= 50_000_000).length / mc.n), sub: 'asking-price test' },
            ].map((s, i) => (
              <Card key={i} style={{ padding: '16px 18px' }}>
                <Mono upper size={10} color="var(--ink-3)" style={{display:'block'}}>{s.l}</Mono>
                <div className="ff-mono num" style={{ fontSize: 18, fontWeight: 500, marginTop: 6 }}>{s.v}</div>
                <Mono size={10} color="var(--ink-3)" style={{ marginTop: 4, display: 'block' }}>{s.sub}</Mono>
              </Card>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // ═════════════════════════════════════════════════════════════════
  // 05 SCENARIOS SUB-TAB
  // ═════════════════════════════════════════════════════════════════
  function ScenariosView({ opts }) {
    const scenarios = useMemo(() => VE.scenarios(opts), [opts]);
    const [active, setActive] = useState(scenarios[1].id);
    const baseValue = scenarios.find(s => s.id === 'base').result.value;
    const probWeighted = scenarios.reduce((sum, s) => sum + s.probability * (s.result.combinedValue || s.result.value), 0);
    const totalProb = scenarios.reduce((s, x) => s + x.probability, 0);

    return (
      <div>
        <Card style={{ padding: '24px 28px', marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 0 }}>
            <div style={{ paddingRight: 14 }}>
              <Mono upper size={10} color="var(--ink-3)">PROBABILITY-WEIGHTED VALUE</Mono>
              <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 500, marginTop: 4 }}>{fmtUsd(probWeighted / totalProb)}</div>
              <Mono size={11} color="var(--ink-3)" style={{ marginTop: 4, display: 'block' }}>Σ p(s) · V(s)</Mono>
            </div>
            <div style={{ paddingLeft: 14, borderLeft: '1px solid var(--rule)' }}>
              <Mono upper size={10} color="var(--ink-3)">UPSIDE/DOWNSIDE SPREAD</Mono>
              <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 500, marginTop: 4 }}>
                {fmtPct(scenarios.find(s=>s.id==='bull').result.value / scenarios.find(s=>s.id==='bear').result.value - 1)}
              </div>
              <Mono size={11} color="var(--ink-3)" style={{ marginTop: 4, display: 'block' }}>bull / bear ratio</Mono>
            </div>
            <div style={{ paddingLeft: 14, borderLeft: '1px solid var(--rule)' }}>
              <Mono upper size={10} color="var(--ink-3)">BREAK-UP PREMIUM</Mono>
              <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 500, marginTop: 4 }}>
                {fmtPct((scenarios.find(s=>s.id==='breakup').result.combinedValue || baseValue) / baseValue - 1, true)}
              </div>
              <Mono size={11} color="var(--ink-3)" style={{ marginTop: 4, display: 'block' }}>top-5 carve-out vs base</Mono>
            </div>
          </div>
        </Card>

        <div style={{ marginBottom: 24, display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
          {scenarios.map(s => (
            <button key={s.id}
              onClick={() => setActive(s.id)}
              style={{
                textAlign: 'left',
                background: active === s.id ? 'var(--ink)' : 'transparent',
                color: active === s.id ? 'var(--bg)' : 'inherit',
                border: '1px solid ' + (active === s.id ? 'var(--ink)' : 'var(--rule)'),
                padding: '14px 16px', cursor: 'pointer',
              }}>
              <Mono upper size={9} color={active === s.id ? 'var(--bg)' : 'var(--ink-3)'}>{s.id} · p={Math.round(s.probability*100)}%</Mono>
              <div style={{ fontSize: 12, fontWeight: 500, marginTop: 4 }}>{s.label.split(' · ').slice(1).join(' · ')}</div>
              <div className="ff-mono num" style={{ fontSize: 17, fontWeight: 500, marginTop: 8 }}>
                {fmtUsd(s.result.combinedValue || s.result.value)}
              </div>
              <Mono size={10} color={active === s.id ? 'var(--bg)' : 'var(--ink-3)'} style={{ marginTop: 2, display: 'block' }}>
                {fmtPct((s.result.combinedValue || s.result.value) / baseValue - 1, true)} vs base
              </Mono>
            </button>
          ))}
        </div>

        {(() => {
          const s = scenarios.find(x => x.id === active);
          return (
            <Card style={{ padding: '20px 24px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
                <div>
                  <Mono upper size={10} color="var(--ink-3)">{s.label}</Mono>
                  <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 10 }}>{s.narrative}</div>
                  <div style={{ marginTop: 16 }}>
                    <Mono upper size={10} color="var(--ink-3)" style={{display:'block', marginBottom: 8}}>OVERRIDES VS BASE</Mono>
                    <Card>
                      {Object.entries(s.opts).map(([k, v]) => {
                        const baseV = opts[k];
                        if (baseV === v || baseV == null) return null;
                        return (
                          <div key={k} style={{
                            display: 'grid', gridTemplateColumns: '1fr 100px 100px',
                            gap: 12, padding: '8px 14px', alignItems: 'center',
                            borderBottom: '1px solid var(--rule-soft, var(--bg-2))'
                          }}>
                            <Mono size={11} color="var(--ink-2)">{k}</Mono>
                            <Mono size={11} color="var(--ink-3)" style={{textAlign:'right'}}>{typeof baseV === 'number' && baseV < 1 ? (baseV*100).toFixed(1) + '%' : baseV.toLocaleString?.() || baseV}</Mono>
                            <Mono size={11} color="var(--ink)" style={{textAlign:'right'}}>{typeof v === 'number' && v < 1 ? (v*100).toFixed(1) + '%' : v.toLocaleString?.() || v}</Mono>
                          </div>
                        );
                      })}
                    </Card>
                  </div>
                </div>
                <div>
                  <Mono upper size={10} color="var(--ink-3)" style={{display:'block', marginBottom: 12}}>RESULT BREAKDOWN</Mono>
                  <Card>
                    {[
                      { l: 'TTM earnings', v: fmtUsd(s.result.ttmEarnings) },
                      { l: 'Effective multiple', v: fmtX(s.result.multiple) },
                      { l: 'Market value', v: fmtUsd(s.result.marketValue) },
                      { l: 'DCF value', v: fmtUsd(s.result.dcfValue) },
                      { l: 'Regression value', v: fmtUsd(s.result.regressionValue) },
                      { l: 'BLENDED FAIR VALUE', v: fmtUsd(s.result.combinedValue || s.result.value), bold: true },
                      ...(s.result.tailValue ? [
                        { l: '→ Top-5 carve-out', v: fmtUsd(s.result.value), sub: true },
                        { l: '→ Tail catalog held', v: fmtUsd(s.result.tailValue), sub: true },
                      ] : []),
                      { l: 'Δ vs base', v: fmtPct((s.result.combinedValue || s.result.value) / baseValue - 1, true), trend: true },
                    ].map((r, i, arr) => (
                      <div key={i} style={{
                        display: 'grid', gridTemplateColumns: '1fr 1fr',
                        gap: 12, padding: '11px 14px', alignItems: 'center',
                        borderBottom: i < arr.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none',
                        background: r.bold ? 'var(--bg-2)' : 'transparent',
                        paddingLeft: r.sub ? 28 : 14,
                      }}>
                        <Mono size={11} color={r.sub ? 'var(--ink-3)' : 'var(--ink-2)'} style={{ fontWeight: r.bold ? 600 : 400 }}>{r.l}</Mono>
                        <Mono size={r.bold ? 13 : 11}
                          color={r.trend ? (r.v.startsWith('+') ? 'var(--ok)' : r.v.startsWith('-') ? 'var(--danger)' : 'var(--ink)') : 'var(--ink)'}
                          style={{ textAlign: 'right', fontWeight: r.bold ? 600 : 400 }}>{r.v}</Mono>
                      </div>
                    ))}
                  </Card>
                </div>
              </div>
            </Card>
          );
        })()}
      </div>
    );
  }

  // ═════════════════════════════════════════════════════════════════
  // 06 PER-WORK ATTRIBUTION (Shapley)
  // ═════════════════════════════════════════════════════════════════
  function PerWorkView({ opts }) {
    const [running, setRunning] = useState(false);
    const [shap, setShap] = useState(() => VE.shapleyAttribute(opts));
    function rerun() {
      setRunning(true);
      setTimeout(() => { setShap(VE.shapleyAttribute(Object.assign({}, opts, { seed: Date.now() & 0xffff }))); setRunning(false); }, 300);
    }
    useEffect(() => { setShap(VE.shapleyAttribute(opts)); /* eslint-disable-next-line */ }, [opts]);

    const totalValue = shap.reduce((s, w) => s + w.shapleyValue, 0);
    const top5Share = shap.slice(0, 5).reduce((s, w) => s + w.valueShare, 0);
    const top1Share = shap[0]?.valueShare || 0;

    return (
      <div>
        <Card style={{ padding: '24px 28px', marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 0 }}>
            {[
              { l: 'TOP-1 VALUE SHARE', v: fmtPct(top1Share), sub: shap[0]?.title || '—' },
              { l: 'TOP-5 VALUE SHARE', v: fmtPct(top5Share), sub: 'concentration risk metric' },
              { l: 'WORKS ANALYSED', v: shap.length, sub: 'Shapley estimator · 60 perms' },
              { l: 'TOTAL ATTRIBUTED', v: fmtUsd(totalValue), sub: 'matches blended value ±1%' },
            ].map((s, i) => (
              <div key={i} style={{ borderLeft: i > 0 ? '1px solid var(--rule)' : 0, padding: '0 14px' }}>
                <Mono upper size={9} color="var(--ink-3)">{s.l}</Mono>
                <div className="ff-mono num" style={{ fontSize: 22, fontWeight: 500, marginTop: 4 }}>{s.v}</div>
                <Mono size={10} color="var(--ink-3)" style={{ marginTop: 2, display: 'block' }}>{s.sub}</Mono>
              </div>
            ))}
          </div>
        </Card>

        <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <SectionHead sub="Each work's Shapley value approximates its true contribution to NPV — accounting for how removing it changes concentration risk and lifts the multiple on the rest.">PER-WORK ATTRIBUTION (SHAPLEY VALUES)</SectionHead>
          <button onClick={rerun} disabled={running}
            className="ff-mono upper"
            style={{ fontSize: 10, letterSpacing: '.12em', padding: '6px 12px',
              background: 'transparent', color: 'var(--ink-2)',
              border: '1px solid var(--rule)', cursor: running ? 'wait' : 'pointer'
            }}>
            {running ? 'COMPUTING…' : 'RE-SAMPLE 60 PERMUTATIONS'}
          </button>
        </div>

        <Card>
          <div style={{
            display: 'grid', gridTemplateColumns: '40px 1.6fr 1fr 100px 110px 110px 110px',
            padding: '8px 14px', background: 'var(--bg-2)', borderBottom: '1px solid var(--rule)', gap: 12,
          }}>
            <Mono upper size={9} color="var(--ink-3)">#</Mono>
            <Mono upper size={9} color="var(--ink-3)">WORK</Mono>
            <Mono upper size={9} color="var(--ink-3)">ARTIST</Mono>
            <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>TTM</Mono>
            <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>REV SHARE</Mono>
            <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>SHAPLEY VAL</Mono>
            <Mono upper size={9} color="var(--ink-3)" style={{textAlign:'right'}}>LEVERAGE</Mono>
          </div>
          {shap.map((w, i) => (
            <div key={w.id} style={{
              display: 'grid', gridTemplateColumns: '40px 1.6fr 1fr 100px 110px 110px 110px',
              padding: '11px 14px', alignItems: 'center', gap: 12,
              borderBottom: i < shap.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none',
            }}>
              <Mono size={11} color="var(--ink-3)">{i+1}</Mono>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{w.title}</div>
              <Mono size={11} color="var(--ink-2)">{w.artist}</Mono>
              <Mono size={11} color="var(--ink)" style={{textAlign:'right'}}>{fmtUsd(w.ttm)}</Mono>
              <Mono size={11} color="var(--ink-2)" style={{textAlign:'right'}}>{fmtPct(w.revenueShare)}</Mono>
              <Mono size={11} color="var(--ink)" style={{textAlign:'right', fontWeight: 600}}>{fmtUsd(w.shapleyValue)}</Mono>
              <div style={{ textAlign: 'right' }}>
                <Mono size={11}
                  color={w.leveragedMultiple >= 1.10 ? 'var(--ok)' : w.leveragedMultiple <= 0.90 ? 'var(--danger)' : 'var(--ink-3)'}>
                  {fmtX(w.leveragedMultiple)}
                </Mono>
              </div>
            </div>
          ))}
        </Card>

        <div style={{ marginTop: 14, padding: '12px 14px', background: 'var(--bg-2)', fontSize: 11, color: 'var(--ink-2)', lineHeight: 1.5 }}>
          <strong>Reading the leverage column:</strong> &gt; 1.0 means the work is worth MORE than its revenue share suggests (it anchors the catalog, lifting the multiple). &lt; 1.0 means it&apos;s replaceable. Top-1 works typically show 1.15–1.30x leverage.
        </div>
      </div>
    );
  }

  // ═════════════════════════════════════════════════════════════════
  // 07 BUY-SIDE ANALYSIS
  // ═════════════════════════════════════════════════════════════════
  function BuySideView({ opts }) {
    const [askPct, setAskPct] = useState(1.0); // 100% of fair value
    const baseAnalysis = useMemo(() => VE.buySideAnalysis(opts), [opts]);
    const askingPrice = baseAnalysis.askingPrice * askPct;
    const buyerFlows = [-askingPrice].concat(baseAnalysis.flows.slice(1));
    const buyerIrr = VE.irr(buyerFlows);
    const buyerPayback = VE.paybackPeriod(askingPrice, baseAnalysis.flows.slice(1));
    const buyerNpv8 = VE.npv(0.08, buyerFlows);
    const buyerNpv12 = VE.npv(0.12, buyerFlows);
    const sellerVerdict = askingPrice >= baseAnalysis.seller.breakevenSale ? 'sell' : 'hold';

    return (
      <div>
        <Card style={{ padding: '20px 24px', marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 24, alignItems: 'center' }}>
            <div>
              <Mono upper size={10} color="var(--ink-3)">ASKING PRICE</Mono>
              <div className="ff-mono num" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 4 }}>{fmtUsd(askingPrice)}</div>
              <Mono size={11} color="var(--ink-3)" style={{ marginTop: 4, display: 'block' }}>{(askPct*100).toFixed(0)}% of blended fair value</Mono>
            </div>
            <div>
              <Mono upper size={10} color="var(--ink-3)" style={{ display: 'block', marginBottom: 6 }}>OFFER · {(askPct*100).toFixed(0)}% OF FAIR VALUE</Mono>
              <input type="range" min="0.6" max="1.4" step="0.01" value={askPct}
                onChange={e => setAskPct(parseFloat(e.target.value))}
                style={{ width: '100%' }}/>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
                <Mono size={10} color="var(--ink-3)">60% (lowball)</Mono>
                <Mono size={10} color="var(--ink-3)">100% (fair)</Mono>
                <Mono size={10} color="var(--ink-3)">140% (premium)</Mono>
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <Pill fg={sellerVerdict === 'sell' ? 'var(--ok)' : 'var(--danger)'} dot>
                SELLER · {sellerVerdict.toUpperCase()}
              </Pill>
              <Mono size={11} color="var(--ink-3)" style={{ marginTop: 8, display: 'block' }}>
                breakeven {fmtUsd(baseAnalysis.seller.breakevenSale)}
              </Mono>
            </div>
          </div>
        </Card>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 24 }}>
          <Card style={{ padding: '20px 24px' }}>
            <Mono upper size={10} color="var(--ink-3)">BUYER METRICS</Mono>
            <div style={{ marginTop: 16 }}>
              {[
                { l: 'IRR (10y)', v: buyerIrr != null ? fmtPct(buyerIrr) : '—',
                  sub: buyerIrr > 0.12 ? 'above hurdle (12%)' : buyerIrr > 0.08 ? 'modest' : 'below hurdle',
                  color: buyerIrr > 0.12 ? 'var(--ok)' : buyerIrr > 0.08 ? 'var(--ink)' : 'var(--danger)' },
                { l: 'Payback', v: buyerPayback != null ? `${buyerPayback.toFixed(1)} yrs` : 'never', sub: 'cumulative cashflow ≥ 0' },
                { l: 'NPV @ 8%', v: fmtUsd(buyerNpv8), color: buyerNpv8 > 0 ? 'var(--ok)' : 'var(--danger)', sub: 'risk-free + premium' },
                { l: 'NPV @ 12%', v: fmtUsd(buyerNpv12), color: buyerNpv12 > 0 ? 'var(--ok)' : 'var(--danger)', sub: 'PE hurdle rate' },
              ].map((m, i, arr) => (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '1fr 1fr',
                  gap: 12, padding: '11px 0', alignItems: 'center',
                  borderBottom: i < arr.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none'
                }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{m.l}</div>
                    <Mono size={10} color="var(--ink-3)" style={{ marginTop: 2 }}>{m.sub}</Mono>
                  </div>
                  <div className="ff-mono num" style={{ fontSize: 18, fontWeight: 500, color: m.color || 'var(--ink)', textAlign: 'right' }}>{m.v}</div>
                </div>
              ))}
            </div>
          </Card>

          <Card style={{ padding: '20px 24px' }}>
            <Mono upper size={10} color="var(--ink-3)">SELLER ANALYSIS · SELL vs HOLD</Mono>
            <div style={{ marginTop: 16 }}>
              {[
                { l: 'Hold value (NPV @ 12%)', v: fmtUsd(baseAnalysis.seller.breakevenSale), sub: 'expected from holding 10y' },
                { l: 'Sell-now proceeds', v: fmtUsd(askingPrice), color: 'var(--accent-ink, var(--ink))', sub: 'after-tax basis assumed' },
                { l: 'Spread (sell − hold)', v: fmtUsd(askingPrice - baseAnalysis.seller.breakevenSale),
                  color: askingPrice >= baseAnalysis.seller.breakevenSale ? 'var(--ok)' : 'var(--danger)',
                  sub: 'positive = take the deal' },
                { l: 'Break-even price', v: fmtUsd(baseAnalysis.seller.breakevenSale), sub: 'below this = hold' },
              ].map((m, i, arr) => (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '1fr 1fr',
                  gap: 12, padding: '11px 0', alignItems: 'center',
                  borderBottom: i < arr.length - 1 ? '1px solid var(--rule-soft, var(--bg-2))' : 'none'
                }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{m.l}</div>
                    <Mono size={10} color="var(--ink-3)" style={{ marginTop: 2 }}>{m.sub}</Mono>
                  </div>
                  <div className="ff-mono num" style={{ fontSize: 18, fontWeight: 500, color: m.color || 'var(--ink)', textAlign: 'right' }}>{m.v}</div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <div>
          <SectionHead sub="Buyer cashflow over 10 years. Year 0 = -ask price, then 10y of catalog earnings.">BUYER CASHFLOW STREAM</SectionHead>
          <Card style={{ padding: '14px 16px' }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 140, padding: '0 4px' }}>
              {buyerFlows.map((f, i) => {
                const max = Math.max(...buyerFlows.map(Math.abs));
                const h = (Math.abs(f) / max) * 100;
                const isNeg = f < 0;
                return (
                  <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative', height: '100%' }}>
                    <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', width: '100%' }}>
                      {!isNeg && <div style={{ width: '100%', height: `${h}%`, background: 'var(--ok)', opacity: 0.7 }}/>}
                    </div>
                    <div style={{ height: 1, background: 'var(--ink-3)', width: '100%' }}/>
                    <div style={{ flex: '0 0 30%', display: 'flex', alignItems: 'flex-start', width: '100%' }}>
                      {isNeg && <div style={{ width: '100%', height: `${h * 0.3}%`, background: 'var(--danger)', opacity: 0.7 }}/>}
                    </div>
                  </div>
                );
              })}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${buyerFlows.length}, 1fr)`, marginTop: 6, gap: 4 }}>
              {buyerFlows.map((f, i) => (
                <div key={i} style={{ textAlign: 'center' }}>
                  <Mono size={9} color="var(--ink-3)">{i === 0 ? 'Y0' : `Y+${i}`}</Mono>
                  <div className="ff-mono num" style={{ fontSize: 9, color: f < 0 ? 'var(--danger)' : 'var(--ink-2)', marginTop: 2 }}>
                    {f < 0 ? '-' : ''}{fmtUsd(Math.abs(f))}
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    );
  }

  // ═════════════════════════════════════════════════════════════════
  // MAIN VALUATION SCREEN — sub-tab router
  // ═════════════════════════════════════════════════════════════════
  function ValuationScreen({ go }) {
    const [opts, setOpts] = useState(() => VE.defaultOpts());
    const [sub, setSub] = useState('summary');
    const valuation = useMemo(() => VE.compute(opts), [opts]);

    const SUB_TABS = [
      { id: 'summary',     label: 'Summary' },
      { id: 'dcf',         label: 'DCF' },
      { id: 'sensitivity', label: 'Sensitivity' },
      { id: 'montecarlo',  label: 'Monte Carlo' },
      { id: 'scenarios',   label: 'Scenarios' },
      { id: 'perwork',     label: 'Per-work' },
      { id: 'buyside',     label: 'Buy-side' },
    ];

    return (
      <div>
        <div style={{ display: 'flex', borderBottom: '1px solid var(--rule)', marginBottom: 24, gap: 0 }}>
          {SUB_TABS.map(t => (
            <button key={t.id}
              onClick={() => setSub(t.id)}
              className="ff-mono upper"
              style={{
                fontSize: 11, letterSpacing: '.12em',
                padding: '12px 20px',
                background: 'transparent',
                color: sub === t.id ? 'var(--ink)' : 'var(--ink-3)',
                borderBottom: sub === t.id ? '2px solid var(--ink)' : '2px solid transparent',
                border: 'none', cursor: 'pointer',
                marginBottom: -1,
              }}>
              {t.label}
            </button>
          ))}
        </div>

        {sub === 'summary'     && <SummaryView valuation={valuation}/>}
        {sub === 'dcf'         && <DCFView valuation={valuation} opts={opts} setOpts={setOpts}/>}
        {sub === 'sensitivity' && <SensitivityView opts={opts}/>}
        {sub === 'montecarlo'  && <MonteCarloView opts={opts}/>}
        {sub === 'scenarios'   && <ScenariosView opts={opts}/>}
        {sub === 'perwork'     && <PerWorkView opts={opts}/>}
        {sub === 'buyside'     && <BuySideView opts={opts}/>}
      </div>
    );
  }

  // export
  window.ValuationScreen = ValuationScreen;
})();
