// app/page-recording.jsx — Recording detail (banner + working tabs + siblings).

function PageRecording() {
  const app = useApp();
  const S = window.SCHOLIA;
  const r = S.recording(app.route.id) || S.recording('kleiber-vpo-74');
  const w = r.work;
  const [tab, setTab] = React.useState('pro');
  React.useEffect(() => { setTab('pro'); }, [r.id]);

  const siblings = w.recordings.filter((x) => x.id !== r.id);
  const tempi = ['Allegro con brio', 'Andante con moto', 'Scherzo. Allegro', 'Allegro', 'Adagio', 'Largo', 'Vivace', 'Moderato'];
  const tracklist = Array.from({ length: Math.min(w.movements, 8) }, (_, i) => ({ n: ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII'][i], name: tempi[i % tempi.length] }));

  const tabs = [['pro', 'Pro reviews · ' + r.proReviews.length], ['fan', 'Fan reviews · ' + (r.fanCount).toLocaleString()], ['info', 'Recording info'], ['tracks', 'Tracklist']];

  const ProCard = ({ p }) => (
    <div style={{ border: '1px solid var(--rule)', borderRadius: 4, background: '#fff', padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <div className="c-serif" style={{ fontSize: 19, fontWeight: 600, letterSpacing: '0.01em' }}>{p.pub}</div>
          {p.award && <div className="c-eyebrow" style={{ color: 'var(--critic)', marginTop: 5 }}>★ {p.award}</div>}
        </div>
        <Ring value={p.score} kind="critic" size={50} />
      </div>
      <p className="c-serif" style={{ fontSize: 18, fontStyle: 'italic', lineHeight: 1.45, color: 'var(--ink)' }}>“{p.quote}”</p>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 2 }}>
        <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>— {p.critic}</span>
        <span className="c-link c-mono clickable" style={{ fontSize: 11.5, letterSpacing: '0.06em' }} onClick={() => app.showToast('Full review link is stubbed in this prototype')}>READ FULL ↗</span>
      </div>
    </div>
  );

  const FanCard = ({ f }) => (
    <div style={{ border: '1px solid var(--rule)', borderRadius: 4, background: f.mine ? 'var(--fan-soft)' : '#fff', padding: '18px 22px', display: 'flex', gap: 18 }}>
      <Ring value={f.score} kind="fan" size={44} />
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 7 }}>
          <span className="c-mono" style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 500 }}>{f.user}</span>
          {f.mine && <span className="c-eyebrow" style={{ color: 'var(--fan-ink)' }}>YOU</span>}
          <span className="c-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>· {f.when}</span>
        </div>
        <p style={{ fontSize: 15.5, lineHeight: 1.5, color: 'var(--ink)' }}>{f.text}</p>
        <div style={{ display: 'flex', gap: 8, marginTop: 11, alignItems: 'center', flexWrap: 'wrap' }}>
          {(f.tags || []).map((t) => <span key={t} className="c-mono" style={{ fontSize: 10, letterSpacing: '0.06em', color: 'var(--ink-3)', border: '1px solid var(--rule)', borderRadius: 3, padding: '2px 7px' }}>{t.toUpperCase()}</span>)}
          <span className="c-mono clickable" style={{ fontSize: 11, color: 'var(--ink-3)', marginLeft: 'auto' }} onClick={() => app.showToast('♥ Liked')}>♥ {f.likes}</span>
        </div>
      </div>
    </div>
  );

  return (
    <div className="coda" style={{ width: '100%', minHeight: '100%' }}>
      <Nav active="Works" />

      <section style={{ background: 'var(--paper-2)', borderBottom: '1px solid var(--rule)' }}>
        <div className="app-wrap rec-banner-grid" style={{ padding: '34px 48px' }}>
          <Cover composer={r.composerName.toUpperCase().slice(0, 9)} work={(w.subtitle || w.title)[0]} tone={r.tone} size={128} label={r.label.split(' ')[0]} style={{ width: 128, height: 128 }} />
          <div>
            <div className="c-mono clickable" onClick={() => navigate('/work/' + w.id)} style={{ fontSize: 12, letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 8 }}>
              {w.composerName.toUpperCase()} · {w.title.toUpperCase()}{w.catalog ? ', ' + w.catalog.toUpperCase() : ''} ↗
            </div>
            <h1 className="c-serif" style={{ fontSize: 'clamp(30px,4.4vw,42px)', lineHeight: 1, fontWeight: 500, letterSpacing: '-0.02em' }}>
              {r.conductor ? r.conductor + ' · ' + r.ensemble : r.soloist}
            </h1>
            <div style={{ fontSize: 14.5, color: 'var(--ink-2)', marginTop: 10 }}>
              {r.year} · {r.label}{r.remaster ? ' · ' + r.remaster : ''}{r.type ? ' · ' + r.type : ''}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 18, maxWidth: 560 }}>
              <Listen svc="Spotify" /><Listen svc="Apple Music" /><Listen svc="Qobuz" />
              <button className="c-btn" onClick={() => navigate('/recording/' + r.id + '/review')}>Write a review</button>
            </div>
          </div>
          <div className="rec-scores">
            <ScoreStat value={r.critic} kind="critic" label="CRITICS" count={r.proReviews.length + ' reviews'} size={92} />
            <ScoreStat value={r.fan} kind="fan" label="FANS" count={r.fanCount.toLocaleString() + ' ratings'} size={92} />
          </div>
        </div>
      </section>

      <main className="app-wrap" style={{ paddingBottom: 8 }}>
        <div className="tabs">
          {tabs.map(([k, l]) => <button key={k} className={'tab' + (tab === k ? ' on' : '')} onClick={() => setTab(k)}>{l}</button>)}
        </div>

        {tab === 'pro' && (
          <section style={{ paddingTop: 32 }}>
            {r.consensus && (
              <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start', background: 'var(--critic-soft)', border: '1px solid oklch(0.85 0.06 40)', borderRadius: 4, padding: '20px 24px', marginBottom: 32 }}>
                <Ring value={r.critic} kind="critic" size={56} />
                <div>
                  <div className="c-eyebrow" style={{ color: 'var(--critic)', marginBottom: 6 }}>Critics’ consensus</div>
                  <p className="c-serif" style={{ fontSize: 20, lineHeight: 1.4, fontStyle: 'italic', maxWidth: 880 }}>{r.consensus}</p>
                </div>
              </div>
            )}
            {r.proReviews.length ? (
              <div className="pro-grid">{r.proReviews.map((p, i) => <ProCard key={i} p={p} />)}</div>
            ) : <div className="c-mono" style={{ color: 'var(--ink-3)', padding: '20px 0' }}>No professional reviews aggregated yet.</div>}
          </section>
        )}

        {tab === 'fan' && (
          <section style={{ paddingTop: 32, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4, flexWrap: 'wrap', gap: 12 }}>
              <div>
                <h2 className="c-serif" style={{ fontSize: 24, fontWeight: 500 }}>What listeners say</h2>
                <div className="c-eyebrow" style={{ marginTop: 4 }}>{r.fanCount.toLocaleString()} ratings · fan score {r.fan}</div>
              </div>
              <button className="c-btn" onClick={() => navigate('/recording/' + r.id + '/review')}>Add your review</button>
            </div>
            {r.fanReviews.map((f, i) => <FanCard key={i} f={f} />)}
          </section>
        )}

        {tab === 'info' && (
          <section style={{ paddingTop: 32, maxWidth: 680 }}>
            {[['Work', w.composer + ' — ' + w.title + ' ' + w.subtitle], ['Catalogue', w.catalog || '—'], r.conductor ? ['Conductor', r.conductor] : null, ['Ensemble', r.ensemble], r.soloist ? ['Soloist', r.soloist] : null, ['Recorded', String(r.year)], ['Label', r.label], r.remaster ? ['Remaster', r.remaster] : null, ['Type', r.type], ['Duration', w.duration]].filter(Boolean).map(([k, v]) => (
              <div key={k} style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 20, padding: '15px 0', borderBottom: '1px solid var(--rule)' }}>
                <span className="c-eyebrow">{k}</span>
                <span className="c-serif" style={{ fontSize: 17 }}>{v}</span>
              </div>
            ))}
          </section>
        )}

        {tab === 'tracks' && (
          <section style={{ paddingTop: 32, maxWidth: 680 }}>
            {tracklist.map((t) => (
              <div key={t.n} style={{ display: 'flex', alignItems: 'center', gap: 18, padding: '14px 0', borderBottom: '1px solid var(--rule)' }}>
                <span className="c-serif" style={{ fontSize: 18, color: 'var(--ink-3)', width: 36 }}>{t.n}</span>
                <span className="c-serif" style={{ fontSize: 18, fontStyle: 'italic', flex: 1 }}>{t.name}</span>
                <Listen svc="Spotify" />
              </div>
            ))}
          </section>
        )}

        {/* siblings */}
        <section style={{ paddingTop: 52 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 24, paddingBottom: 14, borderBottom: '1px solid var(--rule)' }}>
            <h2 className="c-serif" style={{ fontSize: 27, fontWeight: 500, letterSpacing: '-0.01em' }}>Other recordings of this work</h2>
            <span className="c-link c-mono clickable" style={{ fontSize: 12, letterSpacing: '0.08em' }} onClick={() => navigate('/work/' + w.id)}>ALL {w.recordingCount} →</span>
          </div>
          <div className="siblings-row">
            {siblings.map((sb) => (
              <div key={sb.id} className="clickable" onClick={() => navigate('/recording/' + sb.id)} style={{ display: 'flex', flexDirection: 'column', gap: 11, width: 168, flex: '0 0 168px' }}>
                <Cover composer={sb.composerName.toUpperCase().slice(0, 9)} work="" tone={sb.tone} size={168} label={sb.year} style={{ width: 168, height: 168 }} />
                <div>
                  <div className="c-serif" style={{ fontSize: 16, fontWeight: 500 }}>{(sb.conductor || sb.soloist).split(' ').slice(-1)[0]} · {sb.ensemble.split(' ').map((x) => x[0]).join('').slice(0, 3).toUpperCase()}</div>
                  <div className="c-mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{sb.year}</div>
                </div>
                <ScoreInline c={sb.critic} f={sb.fan} size={34} />
              </div>
            ))}
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
}

Object.assign(window, { PageRecording });
