// rs-catalog.jsx — proof screen: real Rocket Science data rendering end-to-end
// Lists 553 works, opens a work detail panel with full share hierarchy + recordings + linked profiles.

const { useState, useMemo, useEffect } = React;

const fmtPct = (n) => (n == null || isNaN(n) ? '—' : n.toFixed(2) + '%');
const sumShares = (arr, key) => arr.reduce((a, x) => a + (parseFloat(x[key]) || 0), 0);

function RSWorkRow({ w, active, onClick }) {
  const writers = w.writerShares.map(ws => ws.profile?.artist_name || ws.Writer).filter(Boolean);
  const pubs = new Set();
  w.writerShares.forEach(ws => ws.publishingShares?.forEach(ps => ps.Publisher && pubs.add(ps.Publisher)));
  const recCount = w.recordings.length;

  return (
    <button
      onClick={onClick}
      style={{
        display: 'grid',
        gridTemplateColumns: '1fr 110px 70px 60px',
        gap: 16,
        padding: '14px 18px',
        textAlign: 'left',
        background: active ? '#000' : 'transparent',
        color: active ? '#fff' : 'inherit',
        border: 0,
        borderBottom: '1px solid rgba(0,0,0,0.06)',
        cursor: 'pointer',
        fontFamily: 'inherit',
        width: '100%',
      }}
    >
      <div style={{ minWidth: 0 }}>
        <div style={{ fontWeight: 500, fontSize: 14, marginBottom: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {w['Work Title']}
        </div>
        <div style={{ fontSize: 11, color: active ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.5)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {writers.slice(0, 2).join(' · ')}{writers.length > 2 ? ` +${writers.length - 2}` : ''}
        </div>
      </div>
      <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 11, color: active ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.5)', alignSelf: 'center' }}>
        {w.ISWC || '—'}
      </div>
      <div style={{ fontSize: 11, color: active ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.5)', alignSelf: 'center', textAlign: 'right' }}>
        {pubs.size} pub
      </div>
      <div style={{ fontSize: 11, color: active ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.5)', alignSelf: 'center', textAlign: 'right' }}>
        {recCount} rec
      </div>
    </button>
  );
}

function RSWriterShareCard({ ws, onProfile }) {
  const writerName = ws.profile?.artist_name || ws.Writer;
  const writerSoc = ws.profile?.affiliations?.[0]?.Society;
  const role = ws['Writer Role'];
  const perf = ws['Performance Share'] || '0%';
  const mech = ws['Mech Share'] || '0%';
  const sync = ws['Sync Share'] || '0%';
  const controlled = ws.Controlled === 'Yes';
  const pubs = ws.publishingShares || [];

  return (
    <div style={{ border: '1px solid rgba(0,0,0,0.1)', padding: 16, marginBottom: 12, background: '#fff' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10, gap: 16 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <button
            onClick={() => ws.profile && onProfile(ws.profile)}
            disabled={!ws.profile}
            style={{
              border: 0, background: 'transparent', padding: 0, cursor: ws.profile ? 'pointer' : 'default',
              fontWeight: 600, fontSize: 15, fontFamily: 'inherit',
              textDecoration: ws.profile ? 'underline' : 'none', textUnderlineOffset: 3,
              color: 'inherit', textAlign: 'left',
            }}
          >
            {writerName}
          </button>
          <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)', marginTop: 3 }}>
            {role || 'Writer'}{writerSoc ? ` · ${writerSoc}` : ''}{ws.profile?.cae_ipi ? ` · IPI ${ws.profile.cae_ipi}` : ''}{controlled ? ' · CONTROLLED' : ' · UNCONTROLLED'}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', flexShrink: 0 }}>
          <SharePill label="PERF" value={perf} />
          <SharePill label="MECH" value={mech} />
          <SharePill label="SYNC" value={sync} />
        </div>
      </div>

      {pubs.length > 0 ? (
        <div style={{ paddingTop: 10, borderTop: '1px dashed rgba(0,0,0,0.12)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 110px 60px 60px 60px', gap: 12, padding: '6px 0', fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.4)', fontFamily: 'ui-monospace, monospace' }}>
            <div>publisher</div><div>role</div><div style={{textAlign:'right'}}>perf</div><div style={{textAlign:'right'}}>mech</div><div style={{textAlign:'right'}}>sync</div>
          </div>
          {pubs.map((p, i) => {
            const pub = window.RS.publisherByName?.(p.Publisher);
            return (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 110px 60px 60px 60px', gap: 12, padding: '6px 0', fontSize: 12, alignItems: 'center', borderTop: i > 0 ? '1px solid rgba(0,0,0,0.04)' : 0 }}>
                <div style={{ minWidth: 0 }}>
                  <button
                    onClick={() => pub && onProfile(pub)}
                    disabled={!pub}
                    style={{
                      border: 0, background: 'transparent', padding: 0, cursor: pub ? 'pointer' : 'default',
                      fontFamily: 'inherit', fontSize: 12, fontWeight: 500, color: 'inherit',
                      textDecoration: pub ? 'underline' : 'none', textUnderlineOffset: 2, textAlign: 'left',
                    }}
                  >
                    {p.Publisher}
                  </button>
                  <div style={{ fontSize: 9, color: 'rgba(0,0,0,0.45)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                    chain {p['Chain of title'] || '?'}{p['USA License'] ? ` · ${p['USA License']}` : ''}{p.territories?.[0]?.Territory ? ` · ${p.territories[0].Territory}` : ''}
                  </div>
                </div>
                <div style={{ fontSize: 10, color: 'rgba(0,0,0,0.6)' }}>{p['Publisher Role'] || '—'}</div>
                <div style={{ textAlign: 'right', fontFamily: 'ui-monospace, monospace', fontSize: 11 }}>{p['Performance Share'] || '0%'}</div>
                <div style={{ textAlign: 'right', fontFamily: 'ui-monospace, monospace', fontSize: 11 }}>{p['Mech Share'] || '0%'}</div>
                <div style={{ textAlign: 'right', fontFamily: 'ui-monospace, monospace', fontSize: 11 }}>{p['Sync Share'] || '0%'}</div>
              </div>
            );
          })}
        </div>
      ) : (
        <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.4)', fontStyle: 'italic' }}>No publishing chain</div>
      )}
    </div>
  );
}

function SharePill({ label, value }) {
  const num = parseFloat(value) || 0;
  const dim = num === 0;
  return (
    <div style={{ textAlign: 'right', opacity: dim ? 0.4 : 1 }}>
      <div style={{ fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)' }}>{label}</div>
      <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 13, fontWeight: 600 }}>{value}</div>
    </div>
  );
}

function RSWorkDetail({ work, onProfile }) {
  if (!work) {
    return (
      <div style={{ padding: 60, textAlign: 'center', color: 'rgba(0,0,0,0.4)', fontSize: 13 }}>
        Select a work to see its share structure.
      </div>
    );
  }

  const sumPct = (arr, key) => arr.reduce((a, x) => a + (parseFloat(x[key]) || 0), 0);
  const totalPerf = sumPct(work.writerShares, 'Performance Share');
  const totalMech = sumPct(work.writerShares, 'Mech Share');
  const totalSync = sumPct(work.writerShares, 'Sync Share');
  const fmt = n => n.toFixed(2) + '%';

  return (
    <div style={{ padding: 24, overflow: 'auto', height: '100%', boxSizing: 'border-box' }}>
      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)', marginBottom: 6 }}>
          Work · {work['Work ID']}
        </div>
        <h2 style={{ fontSize: 28, margin: 0, lineHeight: 1.15, letterSpacing: '-0.01em' }}>{work['Work Title']}</h2>
        <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 11, color: 'rgba(0,0,0,0.6)', flexWrap: 'wrap' }}>
          {work.ISWC && <div><span style={{ letterSpacing: '0.08em', textTransform: 'uppercase' }}>ISWC</span>&nbsp;<span style={{ fontFamily: 'ui-monospace, monospace' }}>{work.ISWC}</span></div>}
          {work.Genre && <div><span style={{ letterSpacing: '0.08em', textTransform: 'uppercase' }}>Genre</span>&nbsp;{work.Genre}</div>}
          {work['Original Language'] && <div><span style={{ letterSpacing: '0.08em', textTransform: 'uppercase' }}>Lang</span>&nbsp;{work['Original Language']}</div>}
          {work.Status && <div><span style={{ letterSpacing: '0.08em', textTransform: 'uppercase' }}>Status</span>&nbsp;{work.Status}</div>}
        </div>
      </div>

      {/* Shares totals */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 20, padding: 14, background: '#000', color: '#fff' }}>
        <div>
          <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.6 }}>Performance</div>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, fontWeight: 600, marginTop: 4 }}>{fmt(totalPerf)}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.6 }}>Mechanical</div>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, fontWeight: 600, marginTop: 4 }}>{fmt(totalMech)}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.6 }}>Sync</div>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, fontWeight: 600, marginTop: 4 }}>{fmt(totalSync)}</div>
        </div>
      </div>

      <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)', margin: '24px 0 12px' }}>
        Writers & Publishing Shares ({work.writerShares.length})
      </div>
      {work.writerShares.map((ws, i) => (
        <RSWriterShareCard key={i} ws={ws} onProfile={onProfile} />
      ))}

      <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)', margin: '24px 0 12px' }}>
        Linked Recordings ({work.recordings.length})
      </div>
      {work.recordings.length === 0 ? (
        <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.4)', fontStyle: 'italic' }}>None linked.</div>
      ) : (
        <div style={{ border: '1px solid rgba(0,0,0,0.1)' }}>
          {work.recordings.map((r, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 90px 110px', gap: 12, padding: '12px 14px', borderBottom: i < work.recordings.length - 1 ? '1px solid rgba(0,0,0,0.06)' : 0, alignItems: 'center', background: '#fff' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{r.title}</div>
                <div style={{ fontSize: 10, color: 'rgba(0,0,0,0.5)' }}>{r['Recording Artists'] || '—'}</div>
              </div>
              <div style={{ fontSize: 10, fontFamily: 'ui-monospace, monospace', color: 'rgba(0,0,0,0.55)' }}>{r.ISRC || '—'}</div>
              <div style={{ fontSize: 10, color: 'rgba(0,0,0,0.55)', textAlign: 'right' }}>
                {r['Recording Duration'] || '—'}{r['Recording Date'] ? ` · ${r['Recording Date']}` : ''}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function RSProfileDrawer({ profile, onClose }) {
  if (!profile) return null;
  const isPub = !!profile['Publisher Name'];

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 1000,
        display: 'flex', justifyContent: 'flex-end',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: 480, maxWidth: '90vw', height: '100%',
          background: '#fafaf7', overflow: 'auto', boxShadow: '-4px 0 24px rgba(0,0,0,0.15)',
        }}
      >
        <div style={{ padding: 24, borderBottom: '1px solid rgba(0,0,0,0.08)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
            <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.55)' }}>
              {isPub ? 'Publisher' : (profile.profile_kind || 'Profile')}
            </div>
            <button onClick={onClose} style={{ border: 0, background: 'transparent', cursor: 'pointer', fontSize: 18, padding: 0, lineHeight: 1 }}>×</button>
          </div>
          <h3 style={{ margin: 0, fontSize: 22, letterSpacing: '-0.01em' }}>
            {isPub ? profile['Publisher Name'] : profile.artist_name}
          </h3>
          {!isPub && profile.profile_kind && (
            <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.55)', marginTop: 4 }}>
              {profile.profile_kind === 'songwriter' ? 'Songwriter' : profile.profile_kind === 'artist' ? 'Recording Artist' : profile.profile_kind}
            </div>
          )}
        </div>

        {!isPub && (
          <>
            <RSDrawerSection title="Identifiers">
              <RSField label="Profile ID" value={profile.profile_id} mono />
              {profile.legal_name && <RSField label="Legal Name" value={profile.legal_name} />}
              {profile.cae_ipi && <RSField label="CAE/IPI" value={profile.cae_ipi} mono />}
              {profile.isni && <RSField label="ISNI" value={profile.isni} mono />}
            </RSDrawerSection>

            {profile.affiliations?.length > 0 && (
              <RSDrawerSection title={`Affiliations (${profile.affiliations.length})`}>
                {profile.affiliations.map((a, i) => (
                  <div key={i} style={{ padding: '10px 0', borderBottom: i < profile.affiliations.length - 1 ? '1px solid rgba(0,0,0,0.06)' : 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{a.Society}</div>
                    <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.55)' }}>{a.Role}{a['Effective Date'] ? ` · since ${a['Effective Date']}` : ''}</div>
                  </div>
                ))}
              </RSDrawerSection>
            )}
          </>
        )}

        {isPub && (
          <>
            <RSDrawerSection title="Identifiers">
              <RSField label="Publisher ID" value={profile['Publisher ID']} mono />
              {profile['CAE/IPI'] && <RSField label="CAE/IPI" value={profile['CAE/IPI']} mono />}
              {profile['Society Affiliation'] && <RSField label="Society" value={profile['Society Affiliation']} />}
              {profile.Country && <RSField label="Country" value={profile.Country} />}
              {profile.Email && <RSField label="Email" value={profile.Email} />}
            </RSDrawerSection>
          </>
        )}
      </div>
    </div>
  );
}

function RSDrawerSection({ title, children }) {
  return (
    <div style={{ padding: '16px 24px', borderBottom: '1px solid rgba(0,0,0,0.06)' }}>
      <div style={{ fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)', marginBottom: 10 }}>{title}</div>
      {children}
    </div>
  );
}

function RSField({ label, value, mono }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 12, padding: '4px 0', fontSize: 12 }}>
      <div style={{ color: 'rgba(0,0,0,0.5)' }}>{label}</div>
      <div style={{ fontFamily: mono ? 'ui-monospace, monospace' : 'inherit', fontSize: mono ? 11 : 12 }}>{value || '—'}</div>
    </div>
  );
}

function ScreenRSCatalog({ go }) {
  const RS = window.RS;
  const [selectedId, setSelectedId] = useState('RWOR10001'); // Somos Los Que Faltan
  const [search, setSearch] = useState('');
  const [profile, setProfile] = useState(null);

  if (!RS || !RS.loaded) {
    return <div style={{ padding: 60, textAlign: 'center', color: 'rgba(0,0,0,0.5)' }}>Rocket Science data not loaded.</div>;
  }

  const filtered = useMemo(() => {
    if (!search.trim()) return RS.works;
    const q = search.toLowerCase();
    return RS.works.filter(w =>
      (w['Work Title'] || '').toLowerCase().includes(q) ||
      (w.ISWC || '').toLowerCase().includes(q) ||
      w.writerShares.some(ws => (ws.Writer || '').toLowerCase().includes(q))
    );
  }, [search, RS.works]);

  const selected = useMemo(() => RS.works.find(w => w['Work ID'] === selectedId), [selectedId, RS.works]);

  return (
    <div style={{ height: 'calc(100vh - 120px)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ paddingBottom: 20, borderBottom: '1px solid rgba(0,0,0,0.08)' }}>
        <div style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.55)', marginBottom: 6 }}>
          Real catalog · Rocket Science records
        </div>
        <h1 style={{ margin: 0, fontSize: 36, letterSpacing: '-0.02em', fontWeight: 500 }}>Works</h1>
        <div style={{ marginTop: 10, fontSize: 13, color: 'rgba(0,0,0,0.6)', maxWidth: 720 }}>
          {RS.works.length} works · {RS.recordings.length} recordings · {RS.publishers.length} publishers · {RS.profiles.length} profiles. Click any row to inspect the full share hierarchy and linked recordings.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '420px 1fr', flex: 1, minHeight: 0 }}>
        {/* List */}
        <div style={{ borderRight: '1px solid rgba(0,0,0,0.08)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ padding: '12px 18px', borderBottom: '1px solid rgba(0,0,0,0.06)' }}>
            <input
              type="text"
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search title, ISWC, writer..."
              style={{
                width: '100%', boxSizing: 'border-box',
                padding: '8px 12px', border: '1px solid rgba(0,0,0,0.15)',
                fontFamily: 'inherit', fontSize: 12, background: '#fff',
              }}
            />
            <div style={{ fontSize: 10, color: 'rgba(0,0,0,0.5)', marginTop: 6, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              {filtered.length} of {RS.works.length}
            </div>
          </div>
          <div style={{ overflow: 'auto', flex: 1 }}>
            {filtered.slice(0, 200).map(w => (
              <RSWorkRow
                key={w['Work ID']}
                w={w}
                active={w['Work ID'] === selectedId}
                onClick={() => setSelectedId(w['Work ID'])}
              />
            ))}
            {filtered.length > 200 && (
              <div style={{ padding: 16, fontSize: 11, color: 'rgba(0,0,0,0.5)', textAlign: 'center' }}>
                Showing first 200 of {filtered.length}. Refine search to narrow.
              </div>
            )}
          </div>
        </div>

        {/* Detail */}
        <div style={{ overflow: 'hidden', minHeight: 0, background: '#fafaf7' }}>
          <RSWorkDetail work={selected} onProfile={setProfile} />
        </div>
      </div>

      <RSProfileDrawer profile={profile} onClose={() => setProfile(null)} />
    </div>
  );
}

window.ScreenRSCatalog = ScreenRSCatalog;
