// ml-screens-bbrank.jsx — Black-Box claim ranking tab
(function () {
  if (typeof window === 'undefined') return;
  const { useState: _S, useMemo: _M } = React;

  function buildPool() {
    const works = (window.WORKS || []).slice(0, 60);
    const writers = (window.PROFILES || []).slice(0, 200);
    const SOCIETIES = ['ASCAP','BMI','PRS','GEMA','SACEM','JASRAC','SOCAN','APRA','SIAE','MLC','HFA'];
    const out = [];
    let h = 0;
    function rand() { h = (h * 9301 + 49297) % 233280; return h / 233280; }
    h = 1234567;

    for (let i = 0; i < 200; i++) {
      const tweak = rand();
      const work = works[Math.floor(rand() * works.length)];
      if (!work) continue;
      // Title fuzz: sometimes exact, sometimes close, sometimes wrong
      let title;
      if (tweak < 0.30) title = work.title;
      else if (tweak < 0.60) title = work.title + (rand() < 0.5 ? ' (Live)' : ' [Remix]');
      else if (tweak < 0.85) title = work.title.split(' ').slice(0, -1).join(' ') || work.title;
      else title = ['Anywhere','Take Me Higher','Open Sky','Old Friend','Gold Light','Last Train','Static','Soft Hands'][Math.floor(rand() * 8)];

      const writerCount = 1 + Math.floor(rand() * 3);
      const claimWriters = [];
      for (let j = 0; j < writerCount; j++) {
        const w = writers[Math.floor(rand() * writers.length)];
        if (!w) continue;
        // Sometimes IPI matches, sometimes not
        const matchedIpi = rand() < 0.45;
        claimWriters.push({ name: w.name || 'Unknown', ipi: matchedIpi ? w.ipi : null });
      }
      out.push({
        id: 'BB-' + i.toString().padStart(4, '0'),
        society: SOCIETIES[Math.floor(rand() * SOCIETIES.length)],
        title,
        iswc: rand() < 0.20 ? work.iswc : null,
        writers: claimWriters,
        amount: Math.round(15 + rand() * 1850),
        period: ['2024 Q1','2024 Q2','2024 Q3','2024 Q4','2025 Q1','2025 Q2'][Math.floor(rand() * 6)],
        periodAgeMonths: Math.floor(rand() * 60),
      });
    }
    return out;
  }

  function MLBBRankTab() {
    const [bucket, setBucket] = _S(null);
    const [active, setActive] = _S(null);

    const ranked = _M(() => {
      if (window.__BBRANK_CACHE) return window.__BBRANK_CACHE;
      if (!window.BBRankEngine) return [];
      const pool = buildPool();
      const r = window.BBRankEngine.rankPool(pool);
      window.__BBRANK_CACHE = r;
      return r;
    }, []);

    const summary = _M(() => window.BBRankEngine ? window.BBRankEngine.summarize(ranked) : { total:0, likelyYours:0, possible:0, longshot:0, noise:0, totalRecovery:0, expectedRecovery:0 }, [ranked]);

    const filtered = _M(() => bucket ? ranked.filter(r => r.bucket === bucket) : ranked, [ranked, bucket]);

    return (
      <div>
        <div style={{ padding: '0 0 18px' }} className="ff-mono upper">
          <span style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '.14em' }}>BLACK-BOX CLAIM RANKING · 5-FACTOR ENSEMBLE</span>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 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' }}>POOL TOTAL</div>
            <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, marginTop: 6 }}>${(summary.totalRecovery/1000).toFixed(1)}k</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>{summary.total} entries scanned</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' }}>EXPECTED RECOVERY</div>
            <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, color: '#0a8754', marginTop: 6 }}>${(summary.expectedRecovery/1000).toFixed(1)}k</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>P(yours) × $</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' }}>LIKELY YOURS</div>
            <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, color: '#0a8754', marginTop: 6 }}>{summary.likelyYours}</div>
          </div>
          <div style={{ padding: '20px 22px' }}>
            <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>POSSIBLE / LONGSHOT</div>
            <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, marginTop: 6 }}>{summary.possible} <span style={{ color: 'var(--ink-3)', fontSize: 18 }}>· {summary.longshot}</span></div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--rule)' }}>
          {[null, 'likely-yours', 'possible', 'longshot', 'noise'].map(b => (
            <button key={b || 'all'} onClick={() => setBucket(b)} className="ff-mono upper" style={{
              padding: '12px 16px', background: 'transparent', border: 0,
              borderBottom: '2px solid ' + (bucket === b ? 'var(--ink)' : 'transparent'),
              cursor: 'pointer', fontSize: 10, letterSpacing: '.12em',
              color: bucket === b ? 'var(--ink)' : 'var(--ink-3)', fontWeight: bucket === b ? 600 : 400,
            }}>{b ? b.replace('-', ' ').toUpperCase() : 'ALL'}</button>
          ))}
        </div>

        <div>
          <div className="ff-mono upper" style={{
            display: 'grid', gridTemplateColumns: '90px 80px 1fr 200px 90px 100px 110px',
            gap: 10, padding: '10px 14px', fontSize: 9, color: 'var(--ink-3)',
            background: 'var(--bg-2)', borderBottom: '1px solid var(--rule)', letterSpacing: '.12em',
          }}>
            <span>BB ID</span><span>SOCIETY</span><span>CLAIMED TITLE</span><span>WRITERS</span>
            <span style={{ textAlign: 'right' }}>SCORE</span>
            <span style={{ textAlign: 'right' }}>POOL $</span>
            <span style={{ textAlign: 'right' }}>EXPECTED $</span>
          </div>
          {filtered.slice(0, 80).map(r => (
            <div key={r.id} onClick={() => setActive(r)} style={{
              display: 'grid', gridTemplateColumns: '90px 80px 1fr 200px 90px 100px 110px',
              gap: 10, padding: '12px 14px', borderBottom: '1px solid var(--rule-soft)',
              alignItems: 'center', fontSize: 13, cursor: 'pointer',
            }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{r.id}</span>
              <span className="ff-mono" style={{ fontSize: 11, fontWeight: 600 }}>{r.society}</span>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.title}</span>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 12, color: 'var(--ink-2)' }}>{r.writers.map(w => w.name).slice(0, 2).join(', ')}{r.writers.length > 2 ? ` +${r.writers.length - 2}` : ''}</span>
              <span className="ff-mono num" style={{ textAlign: 'right', fontWeight: 600, fontSize: 14, color: r.score > 78 ? '#0a8754' : r.score > 55 ? 'var(--ink)' : r.score > 32 ? '#a35418' : 'var(--ink-3)' }}>{r.score}</span>
              <span className="ff-mono num" style={{ textAlign: 'right' }}>${r.amount}</span>
              <span className="ff-mono num" style={{ textAlign: 'right', fontWeight: 600, color: '#0a8754' }}>${r.expectedRecovery.toFixed(0)}</span>
            </div>
          ))}
        </div>

        {active && (
          <div onClick={() => setActive(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(15,12,8,.32)', zIndex: 70 }}>
            <div onClick={e => e.stopPropagation()} style={{
              position: 'absolute', top: 0, right: 0, width: 540, height: '100%',
              background: 'var(--bg)', borderLeft: '1px solid var(--rule)', overflowY: 'auto',
            }}>
              <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--rule)' }}>
                <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.14em' }}>{active.society} · {active.id} · {active.period}</div>
                <div style={{ fontSize: 22, fontWeight: 600, marginTop: 6 }}>{active.title}</div>
              </div>
              <div style={{ padding: '20px 24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, borderBottom: '1px solid var(--rule)' }}>
                <div>
                  <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>P(YOURS)</div>
                  <div className="ff-mono num" style={{ fontSize: 36, fontWeight: 600, marginTop: 4 }}>{active.score}<span style={{ fontSize: 18, color: 'var(--ink-3)' }}>%</span></div>
                  <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.1em', marginTop: 6 }}>{active.bucket.replace('-', ' ')}</div>
                </div>
                <div>
                  <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>EXPECTED RECOVERY</div>
                  <div className="ff-mono num" style={{ fontSize: 36, fontWeight: 600, color: '#0a8754', marginTop: 4 }}>${active.expectedRecovery.toFixed(0)}</div>
                  <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 6 }}>of ${active.amount} pool</div>
                </div>
              </div>
              <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--rule)' }}>
                <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em', marginBottom: 12 }}>5-FACTOR BREAKDOWN</div>
                {active.attribution.map(a => (
                  <div key={a.k} style={{ display: 'grid', gridTemplateColumns: '110px 1fr 50px', gap: 12, padding: '8px 0', alignItems: 'center', fontSize: 12 }}>
                    <span>{a.k}</span>
                    <div>
                      <span style={{ display: 'block', height: 6, background: 'var(--rule-soft)', position: 'relative' }}>
                        <span style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: a.v + '%', background: 'var(--ink)' }}></span>
                      </span>
                      <span style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 3, display: 'block' }}>{a.detail}</span>
                    </div>
                    <span className="ff-mono num" style={{ textAlign: 'right' }}>{a.v}</span>
                  </div>
                ))}
              </div>
              <div style={{ padding: '20px 24px', display: 'flex', gap: 10 }}>
                <button style={{ padding: '10px 16px', background: 'var(--ink)', color: 'var(--bg)', border: 0, fontSize: 12, fontWeight: 600, cursor: 'pointer', flex: 1 }}>FILE CLAIM</button>
                <button style={{ padding: '10px 16px', background: 'transparent', border: '1px solid var(--rule)', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>NEEDS REVIEW</button>
                <button style={{ padding: '10px 16px', background: 'transparent', border: '1px solid var(--rule)', color: 'var(--ink-3)', fontSize: 12, cursor: 'pointer' }}>DISMISS</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }

  window.MLBBRankTab = MLBBRankTab;
})();
