// audio-intelligence.jsx — auto-detected musical analysis on the Recording page
// ─────────────────────────────────────────────────────────────────────
// What this is, and what it isn't:
//
// The Audio tab already has a static "Fingerprints" section listing AcoustID,
// YouTube CID, Shazam, SoundExchange. Today those rows are passive — just
// catalogued IDs. This component upgrades them into ACTIVE intelligence:
//
//   1. FINGERPRINT MATCH STATUS (live)
//      Per-source: indexed | matching | error, last-seen, confidence,
//      and a count of UGC / sync uses found in the wild via that fingerprint.
//
//   2. AUTO-DETECTED MUSICAL FEATURES
//      BPM, key, mode, time-signature, plus the Spotify-style five
//      (energy, danceability, valence, instrumentalness, acousticness)
//      and a simple loudness profile. Sourced from Spotify Audio Features
//      and our own analysis pipeline; user can confirm/override.
//
//   3. SECTION ANALYSIS
//      Beat-aligned section markers (intro/verse/chorus/bridge/outro) on
//      a horizontal timeline, click to seek the inline player.
//
//   4. USE-OF-MUSIC FOUND IN THE WILD
//      Concrete fingerprint matches detected by partners — UGC clips,
//      cover/remix variants, sync placements — each routable to either
//      Issues (if unclaimed) or to the matching catalog row.
//
// Wire-in:
//   The existing recording-page.jsx Audio tab (RecAudio) imports nothing;
//   we expose <RecAudioIntelligence/> on window and the tab will render it.
//
// Determinism:
//   Mock numbers are seeded by the recording id so the same recording always
//   shows the same readings — flipping between recordings shows variety.
const { useMemo: _AI_useM, useState: _AI_useS, useEffect: _AI_useE, useRef: _AI_useR } = React;

// ─────────── seed helpers (deterministic per-recording)
function aiSeed(id) {
  const s = String(id || 'x');
  let h = 0;
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  return () => { h = (h * 1664525 + 1013904223) >>> 0; return h / 0xffffffff; };
}

const KEYS = ['C','C♯','D','D♯','E','F','F♯','G','G♯','A','A♯','B'];
const MODES = ['Major','Minor'];
const SECTION_KIND = ['Intro','Verse','Chorus','Verse','Chorus','Bridge','Chorus','Outro'];

function buildAnalysis(r) {
  const rng = aiSeed(r?.id || r?.isrc || 'x');
  const dur = r?.duration || 210;

  // BPM: gravitate toward 90–140
  const bpm = Math.round(85 + rng() * 70);
  const bpmConfidence = 0.84 + rng() * 0.14;
  const halfTime = bpm < 100 && rng() > 0.7;

  // Key & mode
  const keyIdx = Math.floor(rng() * 12);
  const modeIdx = rng() < 0.55 ? 0 : 1;
  const camelot = ['8B','3B','10B','5B','12B','7B','2B','9B','4B','11B','6B','1B'][keyIdx];
  const camelotMinor = ['8A','3A','10A','5A','12A','7A','2A','9A','4A','11A','6A','1A'][keyIdx];

  // Time signature
  const timeSigOptions = [[4,4],[4,4],[4,4],[4,4],[3,4],[6,8],[5,4]];
  const ts = timeSigOptions[Math.floor(rng() * timeSigOptions.length)];

  // Spotify-style five (each 0..1)
  const features = {
    energy:          0.45 + rng() * 0.5,
    danceability:    0.4  + rng() * 0.55,
    valence:         0.2  + rng() * 0.7,
    instrumentalness: rng() * 0.35,
    acousticness:    rng() * 0.6,
    speechiness:     0.03 + rng() * 0.1,
    liveness:        0.08 + rng() * 0.2,
  };

  // Loudness profile (12 buckets along the song timeline)
  const loudness = [];
  for (let i = 0; i < 24; i++) {
    const base = -12 + Math.sin((i / 24) * Math.PI * 2) * 3;
    loudness.push(base + (rng() - 0.5) * 4);
  }
  const lufs = -10.4 + (rng() - 0.5) * 1.2;

  // Section breakdown — 6–8 sections, total = dur
  const numSections = 6 + Math.floor(rng() * 3);
  const sections = [];
  let cursor = 0;
  for (let i = 0; i < numSections; i++) {
    const remainingSlots = numSections - i;
    const remainingDur = dur - cursor;
    const len = i === numSections - 1
      ? remainingDur
      : Math.max(8, Math.round(remainingDur / remainingSlots * (0.7 + rng() * 0.6)));
    const kind = SECTION_KIND[Math.min(i, SECTION_KIND.length - 1)];
    sections.push({ kind, start: cursor, end: Math.min(dur, cursor + len) });
    cursor += len;
  }
  if (sections.length) sections[sections.length - 1].end = dur;

  return {
    bpm, bpmConfidence, halfTime,
    key: KEYS[keyIdx], mode: MODES[modeIdx],
    camelot: modeIdx === 0 ? camelot : camelotMinor,
    timeSig: ts.join('/'),
    features,
    loudness, lufs,
    sections,
  };
}

// ─────────── fingerprint sources
function buildFingerprints(r) {
  const rng = aiSeed(r?.id || 'fp');
  const ugcRefs = Math.max(20, Math.round((r?.plays || 1e6) / 250));
  return [
    {
      id: 'acoustid', name: 'AcoustID',
      vendor: 'MusicBrainz · Chromaprint',
      status: 'indexed',
      hash: 'AID-' + (r?.id || '').padEnd(12,'a').slice(0,8) + '-' + (r?.isrc || '').replace(/-/g,'').slice(0,8),
      confidence: 0.99,
      lastChecked: '14m',
      matches: 1,
      detail: '1 canonical match · MBID linked',
      uses: 'Catalog dedupe · ingest matching',
    },
    {
      id: 'youtube-cid', name: 'YouTube Content ID',
      vendor: 'YouTube CMS',
      status: ugcRefs > 200 ? 'matching' : 'indexed',
      hash: 'cid:' + (r?.isrc || '').replace(/-/g,'') + '-asset',
      confidence: 0.97,
      lastChecked: '2m',
      matches: ugcRefs,
      detail: ugcRefs.toLocaleString() + ' UGC references · ' + Math.round(ugcRefs * 0.93).toLocaleString() + ' monetized',
      uses: 'UGC monetization · take-downs',
    },
    {
      id: 'pex', name: 'Pex',
      vendor: 'Pex Inc.',
      status: 'matching',
      hash: 'pex_' + (r?.id || '').replace(/-/g,'').padEnd(20,'9').slice(0,16),
      confidence: 0.95,
      lastChecked: '6m',
      matches: Math.round(ugcRefs * 1.4),
      detail: 'Cross-platform UGC match · TikTok / IG / Shorts',
      uses: 'UGC across non-YouTube platforms',
    },
    {
      id: 'shazam', name: 'Shazam',
      vendor: 'Apple · Shazam',
      status: 'indexed',
      hash: 'shz-' + (r?.isrc || '').replace(/-/g,'').slice(0,12),
      confidence: 0.98,
      lastChecked: '1d',
      matches: Math.round(ugcRefs * 0.018),
      detail: 'Indexed for radio + sync detection',
      uses: 'Radio play discovery · sync forensics',
    },
    {
      id: 'soundexchange', name: 'SoundExchange',
      vendor: 'SoundExchange (US digital perf.)',
      status: 'indexed',
      hash: window.isrcDisplay ? window.isrcDisplay(r?.isrc) : (r?.isrc || ''),
      confidence: 1.0,
      lastChecked: '4h',
      matches: null,
      detail: 'Featured-artist + sound-recording owner registered',
      uses: 'US digital perf. royalties (SiriusXM, webcast)',
    },
    {
      id: 'audible-magic', name: 'Audible Magic',
      vendor: 'Audible Magic',
      status: rng() > 0.7 ? 'error' : 'indexed',
      hash: 'am-' + (r?.id || '').slice(0,8) + '-' + Math.floor(rng() * 9999),
      confidence: 0.96,
      lastChecked: rng() > 0.7 ? 'failed' : '12h',
      matches: Math.round(ugcRefs * 0.05),
      detail: 'Sync detection · broadcast monitoring',
      uses: 'TV / film / advertising sync forensics',
    },
  ];
}

// ─────────── use-of-music findings (UGC + sync)
function buildFindings(r) {
  const rng = aiSeed((r?.id || 'find') + 'finds');
  const types = [
    { kind: 'ugc-tiktok', l: 'TikTok video', source: 'Pex' },
    { kind: 'ugc-reels',  l: 'Instagram Reel', source: 'Pex' },
    { kind: 'ugc-shorts', l: 'YouTube Shorts', source: 'YouTube CID' },
    { kind: 'ugc-yt',     l: 'YouTube video', source: 'YouTube CID' },
    { kind: 'sync',       l: 'Sync placement', source: 'Audible Magic' },
    { kind: 'cover',      l: 'Cover / remix detected', source: 'AcoustID' },
  ];
  const out = [];
  const n = 6 + Math.floor(rng() * 4);
  for (let i = 0; i < n; i++) {
    const t = types[Math.floor(rng() * types.length)];
    const claimed = rng() > 0.25;
    out.push({
      id: 'find-' + i,
      kind: t.kind, label: t.l, source: t.source,
      handle: ['@willowxio','@brokenbeat.daily','@latenighttv','@sun_maria','@chase_d','@mks_archive','@kbe.b','@latticefm'][i % 8],
      title: ['"this part hits 🥲"','dance trend','official drop','bts edit','chorus loop','sleep mix','intro chop','sad-girl edit'][i % 8],
      views: Math.round(1000 + rng() * 4_000_000),
      detected: ['2h','11h','1d','3d','5d','1w','2w'][i % 7],
      confidence: 0.86 + rng() * 0.13,
      claimStatus: claimed ? 'claimed' : 'unclaimed',
      revenueShare: claimed ? '$' + (rng() * 240).toFixed(2) : null,
      offset: Math.round(rng() * (r?.duration || 200)),
      length: Math.round(8 + rng() * 22),
    });
  }
  return out;
}

// ─────────── small atoms
function Mono({ children, color = 'var(--ink-2)', size = 11, upper, ls = '.04em', style }) {
  return <span className={'ff-mono ' + (upper ? 'upper' : '')} style={{ fontSize: size, color, letterSpacing: upper ? '.12em' : ls, ...style }}>{children}</span>;
}
function Pill({ children, fg = 'var(--ink-2)', bg, border = true, dot }) {
  return (
    <span className="ff-mono upper" style={{
      fontSize: 9, letterSpacing: '.12em', padding: '3px 8px',
      color: fg, background: bg || 'transparent',
      border: border ? '1px solid ' + fg : '0',
      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>
  );
}

// ─────────── radial bar — for the "Spotify five" features
function FeatureBar({ label, value, color = 'var(--ink)' }) {
  const pct = Math.max(0, Math.min(1, value));
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '110px 1fr 36px', gap: 12, alignItems: 'center', padding: '7px 0' }}>
      <Mono upper size={9} color="var(--ink-3)">{label}</Mono>
      <div style={{ position: 'relative', height: 6, background: 'var(--bg-2)' }}>
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: (pct * 100) + '%', background: color }}/>
      </div>
      <Mono size={11} style={{ textAlign: 'right' }} color="var(--ink)">{Math.round(pct * 100)}</Mono>
    </div>
  );
}

// ─────────── loudness sparkline
function LoudnessProfile({ data }) {
  const W = 320, H = 36;
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const bw = W / data.length;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display:'block' }}>
      {data.map((v, i) => {
        const norm = (v - min) / range;
        const h = 4 + norm * (H - 4);
        return <rect key={i} x={i * bw + 0.5} y={H - h} width={bw - 1} height={h} fill="var(--ink)" opacity={0.7 + norm * 0.3}/>;
      })}
    </svg>
  );
}

// ─────────── section timeline
function SectionTimeline({ sections, duration, onSeek }) {
  const palette = {
    Intro:  '#7d8b9c',
    Verse:  '#5a6f8c',
    Chorus: 'var(--accent, #c0392b)',
    Bridge: '#a8754f',
    Outro:  '#3d4a5c',
  };
  const fmtTs = (s) => `${Math.floor(s/60)}:${String(Math.floor(s%60)).padStart(2,'0')}`;
  return (
    <div>
      {/* timeline bar */}
      <div style={{ position:'relative', height: 36, border: '1px solid var(--rule)', display:'flex', overflow:'hidden' }}>
        {sections.map((s, i) => {
          const w = ((s.end - s.start) / duration) * 100;
          return (
            <button key={i}
              onClick={() => onSeek?.(s.start)}
              title={`${s.kind} · ${fmtTs(s.start)}–${fmtTs(s.end)}`}
              style={{
                width: w + '%', height: '100%', padding: 0,
                border: 0, borderRight: i < sections.length - 1 ? '1px solid var(--bg)' : 'none',
                background: palette[s.kind] || 'var(--ink-3)',
                cursor: 'pointer', position: 'relative',
                color: '#fff', fontSize: 9, fontWeight: 600, letterSpacing: '.08em',
              }} className="ff-mono upper">
              {w > 8 ? s.kind : ''}
            </button>
          );
        })}
      </div>
      {/* axis */}
      <div style={{ display:'flex', justifyContent:'space-between', marginTop: 4 }}>
        <Mono size={9} color="var(--ink-3)">0:00</Mono>
        <Mono size={9} color="var(--ink-3)">{fmtTs(duration / 2)}</Mono>
        <Mono size={9} color="var(--ink-3)">{fmtTs(duration)}</Mono>
      </div>
    </div>
  );
}

// ─────────── BPM / Key giant readout block
function BigReadout({ label, value, sub, accent }) {
  return (
    <div style={{ padding: '20px 22px', borderRight: '1px solid var(--rule)', minHeight: 124, display:'flex', flexDirection:'column', justifyContent:'space-between' }}>
      <Mono upper size={9} color="var(--ink-3)">{label}</Mono>
      <div className="ff-mono num" style={{
        fontSize: 38, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1,
        color: accent ? 'var(--accent-ink)' : 'var(--ink)',
        background: accent ? 'var(--accent)' : 'transparent',
        padding: accent ? '2px 6px' : 0,
        alignSelf: 'flex-start',
      }}>{value}</div>
      {sub && <Mono size={11} color="var(--ink-3)">{sub}</Mono>}
    </div>
  );
}

// ─────────── fingerprint row
function FpRow({ fp, last }) {
  const TONE = {
    indexed:  { fg: 'var(--ok)',     l: 'INDEXED'  },
    matching: { fg: 'var(--info)',   l: 'MATCHING' },
    error:    { fg: 'var(--danger)', l: 'ERROR'    },
  };
  const t = TONE[fp.status] || TONE.indexed;
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 100px 90px 1fr 110px',
      gap: 14, padding: '14px 16px',
      borderBottom: last ? 'none' : '1px solid var(--rule-soft, var(--bg-2))',
      alignItems: 'center'
    }}>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 13, fontWeight: 600 }}>{fp.name}</span>
          <Pill fg={t.fg} dot>{t.l}</Pill>
        </div>
        <Mono size={10} color="var(--ink-3)" style={{ marginTop: 3, display: 'block', wordBreak: 'break-all' }}>{fp.hash}</Mono>
      </div>
      <div style={{ textAlign: 'right' }}>
        <Mono size={11} color="var(--ink)">{Math.round(fp.confidence * 100)}%</Mono>
        <Mono size={9} color="var(--ink-3)" style={{ display:'block' }}>confidence</Mono>
      </div>
      <div style={{ textAlign: 'right' }}>
        <Mono size={11} color="var(--ink)">{fp.matches == null ? '—' : fp.matches.toLocaleString()}</Mono>
        <Mono size={9} color="var(--ink-3)" style={{ display:'block' }}>matches</Mono>
      </div>
      <Mono size={11} color="var(--ink-2)">{fp.detail}</Mono>
      <div style={{ textAlign: 'right' }}>
        <Mono size={11} color="var(--ink-2)">{fp.lastChecked}</Mono>
        <Mono size={9} color="var(--ink-3)" style={{ display: 'block' }}>last checked</Mono>
      </div>
    </div>
  );
}

// ─────────── findings row (UGC / sync)
function FindingRow({ f, last, onOpenIssue }) {
  const fmtTs = (s) => `${Math.floor(s/60)}:${String(Math.floor(s%60)).padStart(2,'0')}`;
  const KIND_TONE = {
    'ugc-tiktok': '#ff0050',
    'ugc-reels':  '#e1306c',
    'ugc-shorts': '#ff0000',
    'ugc-yt':     '#ff0000',
    'sync':       '#5b3aa3',
    'cover':      '#0f62fe',
  };
  const c = KIND_TONE[f.kind] || 'var(--ink-3)';
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '4px 1.2fr 1fr 90px 100px 100px',
      gap: 12, padding: '12px 16px',
      borderBottom: last ? 'none' : '1px solid var(--rule-soft, var(--bg-2))',
      alignItems: 'center', position: 'relative'
    }}>
      <span style={{ width: 4, height: 28, background: c, alignSelf: 'center' }}/>
      <div>
        <Mono upper size={9} color={c}>{f.label}</Mono>
        <div style={{ fontSize: 13, marginTop: 2 }}>{f.title}</div>
        <Mono size={10} color="var(--ink-3)" style={{ marginTop: 2 }}>{f.handle} · via {f.source}</Mono>
      </div>
      <div>
        <Mono size={11} color="var(--ink)">{f.views.toLocaleString()}</Mono>
        <Mono size={9} color="var(--ink-3)" style={{ display: 'block' }}>views · {f.detected} ago</Mono>
      </div>
      <div style={{ textAlign: 'right' }}>
        <Mono size={11} color="var(--ink)">{fmtTs(f.offset)}</Mono>
        <Mono size={9} color="var(--ink-3)" style={{ display: 'block' }}>+{f.length}s clip</Mono>
      </div>
      <div style={{ textAlign: 'right' }}>
        <Mono size={11} color="var(--ink)">{Math.round(f.confidence * 100)}%</Mono>
        <Mono size={9} color="var(--ink-3)" style={{ display: 'block' }}>match</Mono>
      </div>
      <div style={{ textAlign: 'right' }}>
        {f.claimStatus === 'claimed'
          ? <Pill fg="var(--ok)" dot>{f.revenueShare}</Pill>
          : <button onClick={onOpenIssue} className="ff-mono upper"
              style={{ fontSize: 9, letterSpacing: '.12em', padding: '4px 8px',
                background:'transparent', border:'1px solid var(--danger)', color:'var(--danger)',
                cursor:'pointer' }}>CLAIM →</button>
        }
      </div>
    </div>
  );
}

// ─────────── MAIN PANEL
function RecAudioIntelligence({ r, ext, onSeek }) {
  const a = _AI_useM(() => buildAnalysis(r), [r?.id, r?.duration]);
  const fps = _AI_useM(() => buildFingerprints(r), [r?.id]);
  const finds = _AI_useM(() => buildFindings(r), [r?.id]);
  const [confirmed, setConfirmed] = _AI_useS(false);
  const [findingsOpen, setFindingsOpen] = _AI_useS(true);

  const claimed = finds.filter(f => f.claimStatus === 'claimed').length;
  const unclaimed = finds.length - claimed;
  const totalUgc = fps.find(f => f.id === 'youtube-cid')?.matches || 0;
  const monetizedShare = totalUgc ? Math.round(totalUgc * 0.93) : 0;

  return (
    <div style={{ marginBottom: 32 }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems:'baseline', gap: 14, marginBottom: 16, paddingBottom: 14, borderBottom: '1px solid var(--rule)' }}>
        <div style={{ flex: 1 }}>
          <h3 style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', margin: 0 }}>Audio intelligence</h3>
          <Mono size={11} color="var(--ink-3)" style={{ marginTop: 4, display: 'block' }}>
            Auto-detected musical features and fingerprint matches. Run on every uploaded master and refreshed nightly across {fps.length} sources.
          </Mono>
        </div>
        <Pill fg={confirmed ? 'var(--ok)' : 'var(--ink-3)'} dot>
          {confirmed ? 'CONFIRMED BY EDITOR' : 'AUTO-DETECTED'}
        </Pill>
        {!confirmed && (
          <button onClick={() => setConfirmed(true)} className="ff-mono upper"
            style={{ fontSize: 10, letterSpacing: '.1em', padding: '6px 12px',
              background:'var(--ink)', color:'var(--bg)', border: 0, cursor:'pointer' }}>
            CONFIRM ANALYSIS
          </button>
        )}
      </div>

      {/* ─── BPM / KEY / TIME-SIG / LUFS row ─── */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
        border: '1px solid var(--rule)', marginBottom: 24
      }}>
        <BigReadout
          label="BPM · TEMPO"
          value={a.bpm}
          sub={`${Math.round(a.bpmConfidence * 100)}% conf · ${a.halfTime ? 'half-time feel' : 'straight time'}`}
          accent
        />
        <BigReadout
          label="KEY"
          value={`${a.key} ${a.mode === 'Major' ? 'maj' : 'min'}`}
          sub={`Camelot ${a.camelot} · matched against 12-key chroma`}
        />
        <BigReadout
          label="TIME SIGNATURE"
          value={a.timeSig}
          sub="metric grid stable across all sections"
        />
        <div style={{ padding: '20px 22px', minHeight: 124, display:'flex', flexDirection:'column', gap: 8 }}>
          <Mono upper size={9} color="var(--ink-3)">LOUDNESS · INTEGRATED</Mono>
          <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1 }}>
            {a.lufs.toFixed(1)} <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>LUFS</span>
          </div>
          <div style={{ marginTop: 'auto' }}>
            <LoudnessProfile data={a.loudness}/>
            <Mono size={9} color="var(--ink-3)" style={{ display:'block', marginTop: 4 }}>
              integrated loudness across {Math.floor((r?.duration || 0)/60)}:{String((r?.duration || 0)%60).padStart(2,'0')}
            </Mono>
          </div>
        </div>
      </div>

      {/* ─── Section breakdown (timeline) ─── */}
      <div style={{ marginBottom: 28 }}>
        <Mono upper size={10} color="var(--ink-3)" style={{ display: 'block', marginBottom: 10 }}>
          STRUCTURE · {a.sections.length} sections detected · click to seek
        </Mono>
        <SectionTimeline sections={a.sections} duration={r?.duration || 200} onSeek={onSeek}/>
      </div>

      {/* ─── Mood / energy features ─── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, marginBottom: 32 }}>
        <div>
          <Mono upper size={10} color="var(--ink-3)" style={{ display: 'block', marginBottom: 12 }}>
            MOOD &amp; ENERGY · 0–100 SCALE
          </Mono>
          <div style={{ border: '1px solid var(--rule)', padding: '6px 14px' }}>
            <FeatureBar label="Energy"           value={a.features.energy}           color="#c0392b"/>
            <FeatureBar label="Danceability"     value={a.features.danceability}     color="#7d3da8"/>
            <FeatureBar label="Valence"          value={a.features.valence}          color="#d4881f"/>
            <FeatureBar label="Acousticness"     value={a.features.acousticness}     color="#5a4fcf"/>
            <FeatureBar label="Instrumentalness" value={a.features.instrumentalness} color="#0f62fe"/>
            <FeatureBar label="Speechiness"      value={a.features.speechiness}      color="var(--ink-3)"/>
            <FeatureBar label="Liveness"         value={a.features.liveness}         color="var(--ink-3)"/>
          </div>
          <Mono size={10} color="var(--ink-3)" style={{ marginTop: 8, display: 'block' }}>
            Sourced from Spotify Audio Features and verified against ASTRO's onboard analysis. Used by sync search, playlisting, and pitch tooling.
          </Mono>
        </div>

        <div>
          <Mono upper size={10} color="var(--ink-3)" style={{ display: 'block', marginBottom: 12 }}>
            DERIVED TAGS &amp; SEARCH
          </Mono>
          <div style={{ border: '1px solid var(--rule)', padding: 16 }}>
            <Mono size={10} upper color="var(--ink-3)">SUGGESTED MOOD</Mono>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8, marginBottom: 16 }}>
              {(() => {
                const tags = [];
                if (a.features.energy > 0.7) tags.push('high-energy');
                if (a.features.energy < 0.4) tags.push('mellow');
                if (a.features.valence > 0.65) tags.push('uplifting');
                if (a.features.valence < 0.3) tags.push('moody');
                if (a.features.danceability > 0.7) tags.push('dance');
                if (a.features.acousticness > 0.5) tags.push('acoustic');
                if (a.features.instrumentalness > 0.4) tags.push('instrumental');
                if (a.bpm > 130) tags.push('uptempo');
                if (a.bpm < 90) tags.push('downtempo');
                if (tags.length === 0) tags.push('mid-tempo');
                return tags.map(t => (
                  <span key={t} className="ff-mono" style={{ fontSize: 11, padding: '3px 8px', background: 'var(--bg-2)', color: 'var(--ink-2)', border: '1px solid var(--rule)' }}>{t}</span>
                ));
              })()}
            </div>
            <Mono size={10} upper color="var(--ink-3)">SUGGESTED GENRE FIT</Mono>
            <div style={{ marginTop: 8, marginBottom: 16, display: 'grid', gridTemplateColumns: '1fr auto', rowGap: 4, columnGap: 14, fontSize: 12 }}>
              {(() => {
                const rng = aiSeed((r?.id || '') + 'genre');
                const pool = ['Indie pop','Alt R&B','Bedroom pop','Synthwave','Indie rock','Singer-songwriter','Lo-fi','Electronic'];
                const picks = pool.slice().sort(()=>rng()-0.5).slice(0,3);
                return picks.map((g, i) => (
                  <React.Fragment key={g}>
                    <span>{g}</span>
                    <Mono size={11} color="var(--ink-3)">{Math.round(80 - i * 18 + rng() * 6)}% fit</Mono>
                  </React.Fragment>
                ));
              })()}
            </div>
            <Mono size={10} upper color="var(--ink-3)">REFERENCE TRACKS</Mono>
            <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.6 }}>
              Closest 50 in the catalog by combined feature distance. <button onClick={()=>window.dispatchEvent(new CustomEvent('astro-toast',{detail:{msg:'Sounds-like search opened',tone:'ok'}}))} className="ff-mono upper" style={{ background:'transparent',border:0,padding:0,fontSize:10,letterSpacing:'.12em',color:'var(--ink)',cursor:'pointer',textDecoration:'underline' }}>OPEN SOUNDS-LIKE →</button>
            </div>
          </div>
        </div>
      </div>

      {/* ─── Fingerprint sources ─── */}
      <div style={{ marginBottom: 32 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 14 }}>
          <Mono upper size={10} color="var(--ink-3)">
            FINGERPRINT SOURCES · {fps.length}
          </Mono>
          <span style={{ flex: 1 }}/>
          <Mono size={11} color="var(--ink-3)">
            {fps.filter(f => f.status !== 'error').length} indexing · {fps.filter(f => f.status === 'matching').length} actively matching
          </Mono>
        </div>
        <div style={{ border: '1px solid var(--rule)' }}>
          {fps.map((f, i) => <FpRow key={f.id} fp={f} last={i === fps.length - 1}/>)}
        </div>
      </div>

      {/* ─── Use-of-music findings ─── */}
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 14 }}>
          <Mono upper size={10} color="var(--ink-3)">
            USE OF MUSIC · DETECTED IN THE WILD
          </Mono>
          <span style={{ flex: 1 }}/>
          <span style={{ display: 'flex', gap: 14 }}>
            <Mono size={11} color="var(--ok)">{claimed} claimed</Mono>
            {unclaimed > 0 && <Mono size={11} color="var(--danger)">{unclaimed} unclaimed</Mono>}
          </span>
        </div>

        {/* totals strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', border: '1px solid var(--rule)', marginBottom: 16 }}>
          <div style={{ padding: '14px 18px', borderRight: '1px solid var(--rule)' }}>
            <Mono upper size={9} color="var(--ink-3)">TOTAL UGC USES</Mono>
            <div className="ff-mono num" style={{ fontSize: 22, marginTop: 4 }}>{totalUgc.toLocaleString()}</div>
          </div>
          <div style={{ padding: '14px 18px', borderRight: '1px solid var(--rule)' }}>
            <Mono upper size={9} color="var(--ink-3)">MONETIZED</Mono>
            <div className="ff-mono num" style={{ fontSize: 22, marginTop: 4, color:'var(--ok)' }}>{monetizedShare.toLocaleString()}</div>
            <Mono size={9} color="var(--ink-3)">{Math.round((monetizedShare/Math.max(totalUgc,1))*100)}% of detections</Mono>
          </div>
          <div style={{ padding: '14px 18px', borderRight: '1px solid var(--rule)' }}>
            <Mono upper size={9} color="var(--ink-3)">SYNC PLACEMENTS</Mono>
            <div className="ff-mono num" style={{ fontSize: 22, marginTop: 4 }}>
              {finds.filter(f=>f.kind==='sync').length}
            </div>
            <Mono size={9} color="var(--ink-3)">via Audible Magic</Mono>
          </div>
          <div style={{ padding: '14px 18px' }}>
            <Mono upper size={9} color="var(--ink-3)">COVERS / REMIXES</Mono>
            <div className="ff-mono num" style={{ fontSize: 22, marginTop: 4 }}>
              {finds.filter(f=>f.kind==='cover').length}
            </div>
            <Mono size={9} color="var(--ink-3)">unmapped derivative works</Mono>
          </div>
        </div>

        <div style={{ border: '1px solid var(--rule)' }}>
          <div style={{
            display: 'grid', gridTemplateColumns: '4px 1.2fr 1fr 90px 100px 100px',
            gap: 12, padding: '8px 16px',
            background: 'var(--bg-2)', borderBottom: '1px solid var(--rule)'
          }}>
            <span/>
            <Mono upper size={9} color="var(--ink-3)">USE</Mono>
            <Mono upper size={9} color="var(--ink-3)">REACH</Mono>
            <Mono upper size={9} color="var(--ink-3)" style={{ textAlign: 'right' }}>OFFSET</Mono>
            <Mono upper size={9} color="var(--ink-3)" style={{ textAlign: 'right' }}>MATCH</Mono>
            <Mono upper size={9} color="var(--ink-3)" style={{ textAlign: 'right' }}>STATUS</Mono>
          </div>
          {(findingsOpen ? finds : finds.slice(0,4)).map((f, i, arr) => (
            <FindingRow
              key={f.id}
              f={f}
              last={i === arr.length - 1}
              onOpenIssue={() => {
                window.dispatchEvent(new CustomEvent('astro-toast', { detail: { msg: 'Claim filed against ' + f.handle + ' (' + f.label + ')', tone: 'ok' }}));
              }}
            />
          ))}
        </div>
        {finds.length > 4 && (
          <button onClick={() => setFindingsOpen(o => !o)} className="ff-mono upper"
            style={{ fontSize: 10, letterSpacing: '.12em', padding: '8px 12px', background: 'transparent', border: '1px solid var(--rule)', color: 'var(--ink-2)', cursor: 'pointer', marginTop: 10 }}>
            {findingsOpen ? `COLLAPSE · SHOW 4` : `EXPAND · SHOW ALL ${finds.length}`}
          </button>
        )}
      </div>
    </div>
  );
}

window.RecAudioIntelligence = RecAudioIntelligence;
