// ml-screens-leak.jsx — Leak Detection tab + drawer + embed
// ────────────────────────────────────────────────────────────────────
(function () {
  if (typeof window === 'undefined') return;
  const { useState: _S, useMemo: _M, useEffect: _E } = React;

  // ─── Severity chip ─────────────────────────────────────────────
  function SevChip({ sev }) {
    const cfg = sev === 'high'
      ? { fg: '#a32a18', l: 'HIGH' }
      : sev === 'med'
      ? { fg: '#a35418', l: 'MED' }
      : { fg: 'var(--ink-3)', l: 'LOW' };
    return (
      <span className="ff-mono upper" style={{
        fontSize: 9, letterSpacing: '.12em', padding: '2px 7px',
        border: '1px solid ' + cfg.fg, color: cfg.fg, fontWeight: 600,
      }}>{cfg.l}</span>
    );
  }
  const KIND_LABELS = {
    'under-report':      'Under-report',
    'missing-territory': 'Missing territory',
    'dead-link':         'Dead link (ISRC)',
    'share-drift':       'Share drift',
    'rate-drift':        'Rate floor drift',
  };

  // ─── Detail drawer ─────────────────────────────────────────────
  function LeakDrawer({ finding, onClose, onResolve }) {
    if (!finding) return null;
    return (
      <div onClick={onClose} 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',
          display: 'flex', flexDirection: 'column',
        }}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--rule)' }}>
            <div className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.14em', color: 'var(--ink-3)' }}>
              ROYALTY LEAK · {KIND_LABELS[finding.kind] || finding.kind}
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', marginTop: 6 }}>
              {finding.title}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>{finding.artist}</div>
          </div>

          <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--rule)', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
            <div>
              <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>RECOVERY ESTIMATE</div>
              <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, color: '#0a8754', marginTop: 6 }}>${finding.recovery.toLocaleString()}</div>
            </div>
            <div>
              <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>SEVERITY</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 8 }}>
                <SevChip sev={finding.severity} />
                <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>conf. {Math.round((finding.conf || 0.6) * 100)}%</span>
              </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: 8 }}>EXPLAINER</div>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--ink-2)' }}>{finding.explain}</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 }}>EVIDENCE</div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
              <tbody>
                {finding.dsp && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>DSP</td><td className="ff-mono" style={{ textAlign: 'right' }}>{finding.dsp}</td></tr>}
                {finding.territory && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Territory</td><td className="ff-mono" style={{ textAlign: 'right' }}>{finding.territoryName || finding.territory}</td></tr>}
                {finding.truth != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>DSP truth</td><td className="ff-mono num" style={{ textAlign: 'right' }}>{finding.truth.toLocaleString()}</td></tr>}
                {finding.reported != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Reported</td><td className="ff-mono num" style={{ textAlign: 'right' }}>{finding.reported.toLocaleString()}</td></tr>}
                {finding.gap != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Gap</td><td className="ff-mono num" style={{ textAlign: 'right', color: '#a32a18' }}>−{finding.gap.toLocaleString()} ({(finding.gapPct*100).toFixed(1)}%)</td></tr>}
                {finding.monthlyStreams != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Monthly streams</td><td className="ff-mono num" style={{ textAlign: 'right' }}>{finding.monthlyStreams.toLocaleString()}</td></tr>}
                {finding.orphanStreams != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Orphan streams</td><td className="ff-mono num" style={{ textAlign: 'right' }}>{finding.orphanStreams.toLocaleString()}</td></tr>}
                {finding.isrcExpected && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Expected ISRC</td><td className="ff-mono" style={{ textAlign: 'right' }}>{finding.isrcExpected}</td></tr>}
                {finding.isrcFound && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Found under</td><td className="ff-mono" style={{ textAlign: 'right' }}>{finding.isrcFound}</td></tr>}
                {finding.expected != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Agreement %</td><td className="ff-mono num" style={{ textAlign: 'right' }}>{finding.expected}%</td></tr>}
                {finding.reported != null && finding.expected != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Statement %</td><td className="ff-mono num" style={{ textAlign: 'right' }}>{finding.reported}%</td></tr>}
                {finding.floor != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Floor rate</td><td className="ff-mono num" style={{ textAlign: 'right' }}>${finding.floor.toFixed(5)}/stream</td></tr>}
                {finding.paidRate != null && <tr><td style={{ padding: '6px 0', color: 'var(--ink-3)' }}>Paid rate</td><td className="ff-mono num" style={{ textAlign: 'right', color: '#a32a18' }}>${finding.paidRate.toFixed(5)}/stream</td></tr>}
              </tbody>
            </table>
          </div>

          <div style={{ padding: '20px 24px', display: 'flex', gap: 10, marginTop: 'auto' }}>
            <button onClick={() => onResolve?.(finding, 'dispute')} style={{
              padding: '10px 16px', border: '1px solid var(--ink)', background: 'var(--ink)', color: 'var(--bg)',
              fontSize: 12, fontWeight: 600, cursor: 'pointer', flex: 1,
            }}>OPEN DISPUTE</button>
            <button onClick={() => onResolve?.(finding, 'investigate')} style={{
              padding: '10px 16px', border: '1px solid var(--rule)', background: 'transparent', color: 'var(--ink)',
              fontSize: 12, fontWeight: 600, cursor: 'pointer', flex: 1,
            }}>INVESTIGATE</button>
            <button onClick={() => onResolve?.(finding, 'dismiss')} style={{
              padding: '10px 16px', border: '1px solid var(--rule)', background: 'transparent', color: 'var(--ink-3)',
              fontSize: 12, cursor: 'pointer',
            }}>DISMISS</button>
          </div>
        </div>
      </div>
    );
  }

  // ─── KPI strip ─────────────────────────────────────────────────
  function LeakKPIs({ summary }) {
    return (
      <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' }}>RECOVERABLE</div>
          <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 600, color: '#0a8754', marginTop: 8, letterSpacing: '-0.02em' }}>
            ${summary.totalRecovery >= 1000 ? (summary.totalRecovery / 1000).toFixed(1) + 'k' : summary.totalRecovery.toFixed(0)}
          </div>
          <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>across {summary.totalFindings} findings</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' }}>HIGH SEVERITY</div>
          <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 600, color: '#a32a18', marginTop: 8, letterSpacing: '-0.02em' }}>{summary.bySeverity.high}</div>
          <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>need ops review</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' }}>MED</div>
          <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 600, marginTop: 8, letterSpacing: '-0.02em' }}>{summary.bySeverity.med}</div>
        </div>
        <div style={{ padding: '20px 22px' }}>
          <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>LOW</div>
          <div className="ff-mono num" style={{ fontSize: 32, fontWeight: 600, color: 'var(--ink-3)', marginTop: 8, letterSpacing: '-0.02em' }}>{summary.bySeverity.low}</div>
        </div>
      </div>
    );
  }

  // ─── Filter bar ────────────────────────────────────────────────
  function FilterBar({ kind, sev, onKind, onSev, summary }) {
    const KINDS = [
      { k: null, l: 'ALL' },
      { k: 'under-report', l: 'UNDER-REPORT' },
      { k: 'missing-territory', l: 'MISSING TERR' },
      { k: 'dead-link', l: 'DEAD LINK' },
      { k: 'share-drift', l: 'SHARE DRIFT' },
      { k: 'rate-drift', l: 'RATE DRIFT' },
    ];
    return (
      <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--rule)', alignItems: 'center', overflowX: 'auto' }}>
        {KINDS.map(k => {
          const count = k.k ? (summary.byKind[k.k]?.count || 0) : summary.totalFindings;
          return (
            <button key={k.k || 'all'} onClick={() => onKind(k.k)} className="ff-mono upper" style={{
              padding: '12px 14px', background: 'transparent', border: 0,
              borderBottom: '2px solid ' + (kind === k.k ? 'var(--ink)' : 'transparent'),
              cursor: 'pointer', fontSize: 10, letterSpacing: '.12em',
              color: kind === k.k ? 'var(--ink)' : 'var(--ink-3)',
              fontWeight: kind === k.k ? 600 : 400,
            }}>
              {k.l} <span className="num" style={{ marginLeft: 6, opacity: .6 }}>{count}</span>
            </button>
          );
        })}
        <div style={{ flex: 1 }} />
        <div className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em', padding: '12px 12px' }}>SEV</div>
        {[null, 'high', 'med', 'low'].map(s => (
          <button key={s || 'all'} onClick={() => onSev(s)} className="ff-mono upper" style={{
            padding: '12px 10px', background: 'transparent', border: 0,
            borderBottom: '2px solid ' + (sev === s ? 'var(--ink)' : 'transparent'),
            cursor: 'pointer', fontSize: 10, letterSpacing: '.12em',
            color: sev === s ? 'var(--ink)' : 'var(--ink-3)',
            fontWeight: sev === s ? 600 : 400,
          }}>{s ? s.toUpperCase() : 'ALL'}</button>
        ))}
      </div>
    );
  }

  // ─── Findings list ─────────────────────────────────────────────
  function FindingsList({ findings, onOpen, selected, onToggleSelect }) {
    return (
      <div>
        <div className="ff-mono upper" style={{
          display: 'grid', gridTemplateColumns: '32px 64px 1fr 200px 130px 100px 110px 80px',
          gap: 10, padding: '10px 14px', fontSize: 9, color: 'var(--ink-3)',
          background: 'var(--bg-2)', borderBottom: '1px solid var(--rule)', letterSpacing: '.12em',
        }}>
          <span/>
          <span>SEV</span>
          <span>TRACK</span>
          <span>ARTIST</span>
          <span>KIND</span>
          <span>DSP</span>
          <span style={{ textAlign: 'right' }}>RECOVERY</span>
          <span style={{ textAlign: 'right' }}>CONF</span>
        </div>
        {findings.slice(0, 200).map((f, i) => (
          <div key={i} onClick={() => onOpen(f)} style={{
            display: 'grid', gridTemplateColumns: '32px 64px 1fr 200px 130px 100px 110px 80px',
            gap: 10, padding: '12px 14px', borderBottom: '1px solid var(--rule-soft)',
            alignItems: 'center', cursor: 'pointer', fontSize: 13,
          }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <input type="checkbox" checked={selected.has(i)} onChange={e => { e.stopPropagation(); onToggleSelect(i); }} onClick={e => e.stopPropagation()} />
            <SevChip sev={f.severity} />
            <span style={{ fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.title}</span>
            <span style={{ color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.artist}</span>
            <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{KIND_LABELS[f.kind]}</span>
            <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{f.dsp || '—'}</span>
            <span className="ff-mono num" style={{ textAlign: 'right', fontSize: 13, fontWeight: 600, color: '#0a8754' }}>${f.recovery.toFixed(2)}</span>
            <span className="ff-mono num" style={{ textAlign: 'right', fontSize: 11, color: 'var(--ink-3)' }}>{Math.round(f.conf * 100)}%</span>
          </div>
        ))}
      </div>
    );
  }

  // ─── Bulk-action bar (sticky bottom) ───────────────────────────
  function BulkBar({ selected, findings, onClear, onAction }) {
    if (!selected.size) return null;
    const sel = [...selected].map(i => findings[i]);
    const total = sel.reduce((s, f) => s + (f.recovery || 0), 0);
    return (
      <div style={{
        position: 'sticky', bottom: 16, margin: '20px 0 0', padding: '14px 18px',
        background: 'var(--ink)', color: 'var(--bg)', display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <span className="ff-mono upper" style={{ fontSize: 10, letterSpacing: '.12em', opacity: .8 }}>{selected.size} SELECTED</span>
        <span className="ff-mono num" style={{ fontSize: 16, fontWeight: 600 }}>${total.toFixed(2)}</span>
        <span style={{ flex: 1 }} />
        <button onClick={() => onAction('dispute')} style={{ padding: '7px 14px', background: 'transparent', color: 'var(--bg)', border: '1px solid rgba(255,255,255,.4)', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>OPEN DISPUTES</button>
        <button onClick={() => onAction('investigate')} style={{ padding: '7px 14px', background: 'transparent', color: 'var(--bg)', border: '1px solid rgba(255,255,255,.4)', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>INVESTIGATE</button>
        <button onClick={() => onAction('export')} style={{ padding: '7px 14px', background: 'var(--bg)', color: 'var(--ink)', border: 0, fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>EXPORT CSV</button>
        <button onClick={onClear} style={{ padding: '7px 14px', background: 'transparent', color: 'rgba(255,255,255,.7)', border: 0, fontSize: 11, cursor: 'pointer' }}>CLEAR</button>
      </div>
    );
  }

  // ─── Insights tab body ─────────────────────────────────────────
  function MLLeaksTab() {
    const [kind, setKind] = _S(null);
    const [sev, setSev] = _S(null);
    const [active, setActive] = _S(null);
    const [selected, setSelected] = _S(new Set());

    const findings = _M(() => {
      if (window.__LEAK_FINDINGS) return window.__LEAK_FINDINGS;
      const f = window.LeakEngine ? window.LeakEngine.scanCatalog({ limit: 250 }) : [];
      window.__LEAK_FINDINGS = f;
      return f;
    }, []);

    const summary = _M(() => window.LeakEngine ? window.LeakEngine.summarize(findings) : { totalRecovery: 0, totalFindings: 0, byKind: {}, bySeverity: {high:0,med:0,low:0} }, [findings]);

    const filtered = _M(() => findings.filter(f =>
      (!kind || f.kind === kind) && (!sev || f.severity === sev)
    ), [findings, kind, sev]);

    const toggleSel = (i) => {
      const next = new Set(selected);
      if (next.has(i)) next.delete(i); else next.add(i);
      setSelected(next);
    };

    return (
      <div>
        <div style={{ padding: '0 0 18px', display: 'flex', alignItems: 'baseline', gap: 14, flexWrap: 'wrap' }}>
          <div className="ff-mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '.14em' }}>ROYALTY LEAK DETECTION</div>
          <div className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>· 5 detectors active · scanned {findings.length > 0 ? '250' : '0'} recordings</div>
          <span style={{ flex: 1 }} />
          <button onClick={() => { delete window.__LEAK_FINDINGS; window.dispatchEvent(new Event('leak-rescan')); }} className="ff-mono upper" style={{
            fontSize: 10, padding: '7px 12px', background: 'transparent', border: '1px solid var(--rule)',
            color: 'var(--ink-2)', cursor: 'pointer', letterSpacing: '.1em',
          }}>RE-SCAN</button>
        </div>
        <LeakKPIs summary={summary} />
        <FilterBar kind={kind} sev={sev} onKind={setKind} onSev={setSev} summary={summary} />
        <FindingsList findings={filtered} onOpen={setActive} selected={selected} onToggleSelect={toggleSel} />
        <BulkBar selected={selected} findings={filtered} onClear={() => setSelected(new Set())} onAction={(act) => {
          alert(`${act.toUpperCase()} → ${selected.size} findings (in production this would create dispute tickets / export CSV)`);
          if (act === 'dispute' || act === 'investigate') setSelected(new Set());
        }} />
        {active && <LeakDrawer finding={active} onClose={() => setActive(null)} onResolve={(f, action) => {
          alert(`${action.toUpperCase()} → ${f.title}`);
          setActive(null);
        }} />}
      </div>
    );
  }

  // ─── Embed: scorecard for a single recording ─────────────────
  function LeakScorecard({ rec }) {
    const findings = _M(() => {
      if (!window.LeakEngine || !rec) return [];
      return [
        ...window.LeakEngine.detectUnderReport(rec, {}),
        ...window.LeakEngine.detectMissingTerritory(rec),
        ...window.LeakEngine.detectDeadLink(rec),
        ...window.LeakEngine.detectShareDrift(rec),
        ...window.LeakEngine.detectRateDrift(rec),
      ].sort((a,b) => b.recovery - a.recovery);
    }, [rec && rec.id]);

    if (!findings.length) {
      return (
        <div style={{ padding: 20, border: '1px solid var(--rule)', background: 'var(--bg)' }}>
          <div className="ff-mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '.12em' }}>ROYALTY LEAK SCAN</div>
          <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 10 }}>No leaks detected for this track.</div>
        </div>
      );
    }
    const total = findings.reduce((s,f) => s + f.recovery, 0);
    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' }}>ROYALTY LEAK SCAN</span>
          <span style={{ flex: 1 }} />
          <span className="ff-mono num" style={{ fontSize: 18, fontWeight: 600, color: '#0a8754' }}>${total.toFixed(2)}</span>
          <span className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.12em' }}>RECOVERABLE</span>
        </div>
        <div>
          {findings.map((f, i) => (
            <div key={i} style={{ padding: '12px 18px', borderBottom: i < findings.length - 1 ? '1px solid var(--rule-soft)' : 0, display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              <SevChip sev={f.severity} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 600 }}>{KIND_LABELS[f.kind]} · {f.dsp || f.territory || ''}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 3, lineHeight: 1.5 }}>{f.explain}</div>
              </div>
              <span className="ff-mono num" style={{ fontSize: 13, fontWeight: 600, color: '#0a8754' }}>${f.recovery.toFixed(2)}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  window.MLLeaksTab = MLLeaksTab;
  window.LeakScorecard = LeakScorecard;
  window.LeakDrawer = LeakDrawer;
})();
