// ml-screens-forecast.jsx — Per-work forecast tab + scorecard embed
(function () {
  if (typeof window === 'undefined') return;
  const { useState: _S, useMemo: _M } = React;

  function ForecastChart({ months, height = 180 }) {
    const W = 760, H = height, padL = 50, padR = 18, padT = 18, padB = 28;
    const max = Math.max(...months.map(m => m.high)) || 1;
    const cw = W - padL - padR, ch = H - padT - padB;
    const bw = cw / months.length;
    const ticks = [0, max * .25, max * .5, max * .75, max];

    const linePts = months.map((m, i) => {
      const x = padL + i * bw + bw / 2;
      const y = padT + ch - (m.total / max) * ch;
      return [x, y];
    });
    const bandTop = months.map((m, i) => {
      const x = padL + i * bw + bw / 2;
      const y = padT + ch - (m.high / max) * ch;
      return `${x},${y}`;
    }).join(' ');
    const bandBot = months.slice().reverse().map((m, i) => {
      const realI = months.length - 1 - i;
      const x = padL + realI * bw + bw / 2;
      const y = padT + ch - (m.low / max) * ch;
      return `${x},${y}`;
    }).join(' ');

    return (
      <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
        {ticks.map((t, i) => {
          const y = padT + ch - (t / max) * ch;
          return (
            <g key={i}>
              <line x1={padL} y1={y} x2={W - padR} y2={y} stroke="var(--rule-soft)" strokeWidth="1" strokeDasharray={i === 0 ? '' : '2,3'}/>
              <text x={padL - 8} y={y + 3} fontSize="9" fill="var(--ink-3)" textAnchor="end" fontFamily="monospace">${t >= 1000 ? (t/1000).toFixed(1) + 'k' : Math.round(t)}</text>
            </g>
          );
        })}
        <polygon points={`${bandTop} ${bandBot}`} fill="var(--ink)" opacity="0.10"/>
        <polyline points={linePts.map(p => p.join(',')).join(' ')} fill="none" stroke="var(--ink)" strokeWidth="2"/>
        {linePts.map(([x, y], i) => <circle key={i} cx={x} cy={y} r="3" fill="var(--ink)"/>)}
        {months.map((m, i) => (
          <text key={i} x={padL + i * bw + bw/2} y={H - 8} fontSize="9" fill="var(--ink-3)" textAnchor="middle" fontFamily="monospace">{m.label}</text>
        ))}
      </svg>
    );
  }

  function BreakdownTable({ rows, label }) {
    const total = rows.reduce((s, r) => s + r.total, 0);
    return (
      <div>
        <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em', padding: '0 0 10px' }}>{label}</div>
        {rows.map(r => {
          const pct = (r.total / total) * 100;
          return (
            <div key={r.key} style={{ display: 'grid', gridTemplateColumns: '1fr 80px 60px', gap: 10, padding: '7px 0', borderBottom: '1px solid var(--rule-soft)', alignItems: 'center', fontSize: 12 }}>
              <span style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 0, top: -3, height: 18, width: pct + '%', background: 'var(--ink)', opacity: .08 }}></span>
                <span style={{ position: 'relative' }}>{r.key}</span>
              </span>
              <span className="ff-mono num" style={{ textAlign: 'right' }}>${r.total >= 1000 ? (r.total/1000).toFixed(1)+'k' : r.total.toFixed(2)}</span>
              <span className="ff-mono num" style={{ textAlign: 'right', color: 'var(--ink-3)' }}>{pct.toFixed(1)}%</span>
            </div>
          );
        })}
      </div>
    );
  }

  function MLForecastTab() {
    const works = _M(() => (window.WORKS || []).slice(0, 80), []);
    const [workId, setWorkId] = _S(works[0]?.id);
    const work = _M(() => works.find(w => w.id === workId) || works[0], [workId, works]);

    const fc = _M(() => work && window.ForecastEngine ? window.ForecastEngine.forecastWork(work) : null, [work]);

    if (!fc) return <div style={{ padding: 40, color: 'var(--ink-3)' }}>Forecast engine not loaded.</div>;

    return (
      <div>
        <div style={{ padding: '0 0 18px', display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <div className="ff-mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '.14em' }}>12-MONTH FORECAST · LINE-ITEM</div>
          <span style={{ flex: 1 }} />
          <select value={workId} onChange={e => setWorkId(e.target.value)} style={{ padding: '8px 12px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 13, minWidth: 280 }}>
            {works.map(w => <option key={w.id} value={w.id}>{w.title}</option>)}
          </select>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)' }}>
          <div style={{ padding: '20px 22px', borderRight: '1px solid var(--rule)' }}>
            <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>12-MO TOTAL</div>
            <div className="ff-mono num" style={{ fontSize: 30, fontWeight: 600, marginTop: 6, letterSpacing: '-0.02em' }}>${fc.total >= 1000 ? (fc.total/1000).toFixed(1)+'k' : fc.total.toFixed(0)}</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>${fc.totalLow >= 1000 ? (fc.totalLow/1000).toFixed(1)+'k' : fc.totalLow.toFixed(0)} – ${fc.totalHigh >= 1000 ? (fc.totalHigh/1000).toFixed(1)+'k' : fc.totalHigh.toFixed(0)}</div>
          </div>
          <div style={{ padding: '20px 22px', borderRight: '1px solid var(--rule)' }}>
            <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>MONTHLY DECAY</div>
            <div className="ff-mono num" style={{ fontSize: 30, fontWeight: 600, marginTop: 6, letterSpacing: '-0.02em' }}>{((1 - fc.profile.monthlyDecay) * 100).toFixed(2)}%</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>per month · {fc.ageYears}y old</div>
          </div>
          <div style={{ padding: '20px 22px', borderRight: '1px solid var(--rule)' }}>
            <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>VOLATILITY</div>
            <div className="ff-mono num" style={{ fontSize: 30, fontWeight: 600, marginTop: 6, letterSpacing: '-0.02em' }}>±{(fc.profile.vol * 100).toFixed(0)}%</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>1-sigma</div>
          </div>
          <div style={{ padding: '20px 22px' }}>
            <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>LINE COUNT</div>
            <div className="ff-mono num" style={{ fontSize: 30, fontWeight: 600, marginTop: 6, letterSpacing: '-0.02em' }}>{fc.months.reduce((s,m) => s + m.lineCount, 0).toLocaleString()}</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>DSP × type × terr × month</div>
          </div>
        </div>

        <div style={{ padding: '24px 0', borderBottom: '1px solid var(--rule)' }}>
          <div className="ff-mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '.12em', marginBottom: 12 }}>MONTHLY PROJECTION (CONFIDENCE BAND)</div>
          <ForecastChart months={fc.months} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 30, padding: '24px 0' }}>
          <BreakdownTable rows={fc.byDsp.slice(0, 8)} label="BY DSP"/>
          <BreakdownTable rows={fc.byType} label="BY ROYALTY TYPE"/>
          <BreakdownTable rows={fc.byTerritory.slice(0, 12)} label="BY TERRITORY"/>
        </div>
      </div>
    );
  }

  function ForecastScorecard({ work }) {
    const fc = _M(() => work && window.ForecastEngine ? window.ForecastEngine.forecastWork(work) : null, [work && work.id]);
    if (!fc) return null;
    return (
      <div style={{ border: '1px solid var(--rule)', background: 'var(--bg)' }}>
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--rule)', display: 'flex', alignItems: 'baseline', gap: 12 }}>
          <span className="ff-mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '.12em' }}>12-MO FORECAST</span>
          <span style={{ flex: 1 }} />
          <span className="ff-mono num" style={{ fontSize: 18, fontWeight: 600 }}>${fc.total >= 1000 ? (fc.total/1000).toFixed(1)+'k' : fc.total.toFixed(0)}</span>
          <span className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>${fc.totalLow >= 1000 ? (fc.totalLow/1000).toFixed(1)+'k' : fc.totalLow.toFixed(0)} – ${fc.totalHigh >= 1000 ? (fc.totalHigh/1000).toFixed(1)+'k' : fc.totalHigh.toFixed(0)}</span>
        </div>
        <div style={{ padding: 12 }}>
          <ForecastChart months={fc.months} height={120} />
        </div>
      </div>
    );
  }

  window.MLForecastTab = MLForecastTab;
  window.ForecastScorecard = ForecastScorecard;
})();
