// review-queue.jsx — Coach side of song submissions.
// CoachQueueScreen: list incoming submissions → open one → listen → score with
// the 5-category rubric + verdict → submit. Reads/writes via window.LAUNCH_USER
// (Supabase in live mode, a shared localStorage list in demo mode).

const { useState: useStateRQ, useEffect: useEffectRQ } = React;
const { Card, Chip, DisplayHeading } = window.LAUNCH_SCREENS_1;

// Same rubric the member is scored against (evaluations.jsx).
const RQ_RUBRIC = [
  { id: 'structure', label: 'SONG STRUCTURE' },
  { id: 'hook',      label: 'TITLE / HOOK' },
  { id: 'idea',      label: 'IDEA' },
  { id: 'lyrics',    label: 'LYRICS' },
  { id: 'melody',    label: 'MELODY' },
];
const RQ_ZERO_SCORES = { structure: 7, hook: 7, idea: 7, lyrics: 7, melody: 7 };
const RQ_ZERO_NOTES = { structure: '', hook: '', idea: '', lyrics: '', melody: '' };

function rqStatusColor(theme, status) {
  if (status === 'reviewed') return '#22C55E';
  if (status === 'in_review') return '#E8A736';
  return theme.accent; // pending
}
function rqWhen(ts) {
  if (!ts) return '';
  try {
    const d = new Date(ts);
    return d.toLocaleDateString([], { month: 'short', day: 'numeric' }).toUpperCase()
      + ' · ' + d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }).toUpperCase();
  } catch (e) { return ''; }
}

function CoachQueueScreen({ theme, onBack }) {
  const [queue, setQueue] = useStateRQ([]);
  const [loading, setLoading] = useStateRQ(true);
  const [active, setActive] = useStateRQ(null);   // submission being reviewed
  const [audioUrl, setAudioUrl] = useStateRQ(null);
  const [scores, setScores] = useStateRQ(RQ_ZERO_SCORES);
  const [notes, setNotes] = useStateRQ(RQ_ZERO_NOTES);
  const [verdict, setVerdict] = useStateRQ('');
  const [saving, setSaving] = useStateRQ(false);
  const [saveErr, setSaveErr] = useStateRQ(null);
  const [historyMember, setHistoryMember] = useStateRQ(null); // { id, name } | null
  // Coach voice note (In-Depth / $40 tier) — recorded in-browser, private to the member.
  const [voiceBlob, setVoiceBlob] = useStateRQ(null);
  const [voiceUrl, setVoiceUrl] = useStateRQ(null);
  const [recording, setRecording] = useStateRQ(false);
  const [recSec, setRecSec] = useStateRQ(0);
  const recorderRef = React.useRef(null);
  const chunksRef = React.useRef([]);

  const refresh = () => {
    setLoading(true);
    window.LAUNCH_USER.fetchCoachQueue().then(rows => {
      setQueue(Array.isArray(rows) ? rows : []);
      setLoading(false);
    });
  };
  useEffectRQ(() => { refresh(); }, []);

  // When a submission is opened, fetch a playable URL (live mode only).
  useEffectRQ(() => {
    let alive = true;
    setAudioUrl(null);
    if (active && active.audio_path) {
      window.LAUNCH_USER.audioUrlFor(active.audio_path).then(u => { if (alive) setAudioUrl(u); });
    }
    return () => { alive = false; };
  }, [active && active.id]);

  const total = RQ_RUBRIC.reduce((sum, c) => sum + (Number(scores[c.id]) || 0), 0);

  // Tick the recording timer while capturing.
  useEffectRQ(() => {
    if (!recording) return;
    const t = setInterval(() => setRecSec(s => s + 1), 1000);
    return () => clearInterval(t);
  }, [recording]);

  const clearVoice = () => {
    setVoiceBlob(null);
    setVoiceUrl(u => { if (u) URL.revokeObjectURL(u); return null; });
    setRecSec(0);
  };
  const startRec = async () => {
    setSaveErr(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mr = new MediaRecorder(stream);
      chunksRef.current = [];
      mr.ondataavailable = e => { if (e.data && e.data.size) chunksRef.current.push(e.data); };
      mr.onstop = () => {
        const blob = new Blob(chunksRef.current, { type: mr.mimeType || 'audio/webm' });
        setVoiceBlob(blob);
        setVoiceUrl(URL.createObjectURL(blob));
        stream.getTracks().forEach(t => t.stop());
      };
      recorderRef.current = mr;
      mr.start();
      setRecSec(0); setRecording(true);
    } catch (e) { setSaveErr('Mic access denied'); }
  };
  const stopRec = () => {
    const mr = recorderRef.current;
    if (mr && mr.state !== 'inactive') mr.stop();
    setRecording(false);
  };

  const openOne = (s) => {
    setActive(s);
    setScores(RQ_ZERO_SCORES);
    setNotes(RQ_ZERO_NOTES);
    setVerdict('');
    setSaveErr(null);
    clearVoice();
  };
  const submitEval = async () => {
    setSaving(true); setSaveErr(null);
    const res = await window.LAUNCH_USER.saveEvaluation(active.id, {
      scores, notes, verdict, total,
      voiceNote: voiceBlob, memberId: active.member_id,
    });
    setSaving(false);
    if (res && res.error) { setSaveErr(res.error); return; }
    clearVoice();
    setActive(null);
    refresh();
  };

  const pendingCount = queue.filter(s => s.status !== 'reviewed').length;

  // ───────── ARTIST HISTORY ─────────
  if (historyMember) {
    return <ArtistHistoryView theme={theme} member={historyMember} onBack={() => setHistoryMember(null)} />;
  }

  // ───────── DETAIL / SCORING ─────────
  if (active) {
    const memberName = active.member_name || active.member_handle || 'Member';
    return (
      <div style={{ paddingBottom: 130 }}>
        <div style={{
          paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between'
        }}>
          <button onClick={() => setActive(null)} style={{
            width: 38, height: 38, borderRadius: 12,
            background: theme.surface, border: `1px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer'
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
          <div style={{
            padding: '6px 10px', borderRadius: 99, background: theme.accent, color: theme.onAccent,
            fontFamily: theme.fontMono, fontSize: 10, letterSpacing: 1, fontWeight: 700
          }}>★ COACH REVIEW</div>
        </div>

        <div style={{ padding: `4px ${theme.pad}px 0` }}>
          <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 1, fontWeight: 700, marginBottom: 6 }}>
            FROM {String(memberName).toUpperCase()} · {(active.tier || 'quick').toUpperCase()}
          </div>
          <DisplayHeading theme={theme} size={30}>{active.title || 'UNTITLED'}</DisplayHeading>
          {active.member_id && (
            <button onClick={() => setHistoryMember({ id: active.member_id, name: memberName })} style={{
              marginTop: 10, padding: '8px 12px', borderRadius: 99,
              background: theme.surface, border: `1px solid ${theme.border}`,
              color: theme.text, cursor: 'pointer',
              fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700, letterSpacing: 0.8,
              textTransform: 'uppercase', display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>📈 View {String(memberName).split(' ')[0]}'s history</button>
          )}
        </div>

        {/* Audio */}
        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0` }}>
          {audioUrl ? (
            <audio controls src={audioUrl} style={{ width: '100%' }} />
          ) : active.audio_path ? (
            <Card theme={theme} style={{ padding: 14 }}>
              <div style={{ fontFamily: theme.fontMono, fontSize: 11, color: theme.muted, letterSpacing: 0.5 }}>
                🎧 Loading audio…
              </div>
            </Card>
          ) : (
            <Card theme={theme} style={{ padding: 14 }}>
              <div style={{ fontFamily: theme.fontMono, fontSize: 11, color: theme.muted, letterSpacing: 0.5 }}>
                🎧 {active.audio_name || 'No audio'} {active.audio_name ? '· plays in live mode' : ''}
              </div>
            </Card>
          )}
        </div>

        {/* Member's ask */}
        {active.notes ? (
          <div style={{ padding: `${theme.gap}px ${theme.pad}px 0` }}>
            <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700, marginBottom: 6 }}>
              WANTS FEEDBACK ON
            </div>
            <div style={{
              fontFamily: theme.fontBody, fontSize: 14, color: theme.text, lineHeight: 1.5,
              paddingLeft: 12, borderLeft: `2px solid ${theme.accent}`
            }}>{active.notes}</div>
          </div>
        ) : null}

        {/* Rubric scoring */}
        <div style={{ padding: `${theme.gap + 6}px ${theme.pad}px 0`, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {RQ_RUBRIC.map(cat => (
            <div key={cat.id}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <span style={{ fontFamily: theme.fontMono, fontSize: 11, color: theme.text, letterSpacing: 0.8, fontWeight: 700 }}>
                  {cat.label}
                </span>
                <span style={{ fontFamily: theme.fontDisplay, fontSize: 18, color: theme.accent }}>
                  {scores[cat.id]}<span style={{ fontSize: 11, color: theme.muted }}>/10</span>
                </span>
              </div>
              <div style={{ display: 'flex', gap: 4 }}>
                {[1,2,3,4,5,6,7,8,9,10].map(n => {
                  const on = scores[cat.id] >= n;
                  return (
                    <button key={n} onClick={() => setScores(s => ({ ...s, [cat.id]: n }))} style={{
                      flex: 1, height: 30, borderRadius: 6, cursor: 'pointer',
                      background: on ? theme.accent : theme.surface2,
                      border: `1px solid ${on ? theme.accent : theme.border}`,
                      color: on ? theme.onAccent : theme.faint,
                      fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700, padding: 0
                    }}>{n}</button>
                  );
                })}
              </div>
              <input
                value={notes[cat.id]}
                onChange={e => setNotes(nn => ({ ...nn, [cat.id]: e.target.value }))}
                placeholder={`Note on ${cat.label.toLowerCase()} (optional)`}
                style={{
                  width: '100%', marginTop: 8, padding: '10px 12px', borderRadius: 10,
                  background: theme.surface, border: `1px solid ${theme.border}`,
                  color: theme.text, fontFamily: theme.fontBody, fontSize: 13, outline: 'none'
                }} />
            </div>
          ))}

          {/* Verdict */}
          <div>
            <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700, marginBottom: 8 }}>
              VERDICT · THE BOTTOM LINE
            </div>
            <textarea
              value={verdict}
              onChange={e => setVerdict(e.target.value)}
              placeholder="The one thing to fix, and the one thing that's working. Be direct."
              rows={4}
              style={{
                width: '100%', padding: '14px 16px', borderRadius: 12,
                background: theme.surface, border: `1px solid ${theme.border}`,
                color: theme.text, fontFamily: theme.fontBody, fontSize: 14,
                outline: 'none', resize: 'none', lineHeight: 1.5
              }} />
          </div>

          {/* Voice note — In-Depth ($40) tier only. Private to the member. */}
          {active.tier === 'full' && (
            <div>
              <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700, marginBottom: 8 }}>
                🎙 VOICE NOTE · PRIVATE TO {String(memberName).split(' ')[0].toUpperCase()}
              </div>
              <Card theme={theme} style={{ padding: 14 }}>
                {!voiceUrl ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <button onClick={recording ? stopRec : startRec} style={{
                      width: 44, height: 44, borderRadius: 99, border: 'none', cursor: 'pointer', flexShrink: 0,
                      background: recording ? '#C72820' : theme.accent, color: theme.onAccent,
                      fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>{recording ? '■' : '●'}</button>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: theme.text, fontWeight: 600 }}>
                        {recording ? 'Recording…' : 'Record a voice note'}
                      </div>
                      <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 0.5 }}>
                        {recording
                          ? `${Math.floor(recSec / 60)}:${String(recSec % 60).padStart(2, '0')} · tap to stop`
                          : 'Only this artist can hear it'}
                      </div>
                    </div>
                  </div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    <audio controls src={voiceUrl} style={{ width: '100%' }} />
                    <button onClick={clearVoice} style={{
                      alignSelf: 'flex-start', padding: '6px 12px', borderRadius: 99,
                      background: theme.surface2, border: `1px solid ${theme.border}`, color: theme.text,
                      fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700, letterSpacing: 0.8, cursor: 'pointer',
                    }}>↺ RE-RECORD</button>
                  </div>
                )}
              </Card>
            </div>
          )}
        </div>

        {/* Sticky submit */}
        <div style={{
          position: 'absolute', bottom: 24, left: theme.pad, right: theme.pad,
          background: theme.surface, borderRadius: 16, padding: 12,
          border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', gap: 10,
          boxShadow: '0 12px 32px rgba(0,0,0,0.3)'
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: theme.fontMono, fontSize: 9, color: saveErr ? theme.accent : theme.muted, letterSpacing: 1, fontWeight: 700 }}>
              {saveErr ? '⚠ ' + saveErr.toUpperCase() : 'TOTAL SCORE'}
            </div>
            <div style={{ fontFamily: theme.fontDisplay, fontSize: 26, color: theme.text, lineHeight: 1, marginTop: 2 }}>
              {total}<span style={{ fontSize: 13, color: theme.muted }}>/50</span>
            </div>
          </div>
          <button onClick={submitEval} disabled={saving} style={{
            background: theme.accent, color: theme.onAccent,
            fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
            padding: '14px 18px', borderRadius: 12, border: 'none',
            cursor: saving ? 'wait' : 'pointer', textTransform: 'uppercase'
          }}>{saving ? 'SENDING…' : 'SEND REVIEW →'}</button>
        </div>
      </div>
    );
  }

  // ───────── LIST / QUEUE ─────────
  return (
    <div style={{ paddingBottom: 40 }}>
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between'
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer'
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
        <button onClick={refresh} style={{
          padding: '6px 12px', borderRadius: 99, background: theme.surface,
          border: `1px solid ${theme.border}`, color: theme.muted, cursor: 'pointer',
          fontFamily: theme.fontMono, fontSize: 10, letterSpacing: 1, fontWeight: 700
        }}>↻ REFRESH</button>
      </div>

      <div style={{ padding: `4px ${theme.pad}px 0` }}>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 1, fontWeight: 700, marginBottom: 6 }}>
          COACH · REVIEW QUEUE
        </div>
        <DisplayHeading theme={theme} size={34}>
          {pendingCount} TRACK{pendingCount === 1 ? '' : 'S'}<br />WAITING ON YOU
        </DisplayHeading>
      </div>

      <div style={{ padding: `${theme.gap + 6}px ${theme.pad}px 0`, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {loading ? (
          <div style={{ fontFamily: theme.fontMono, fontSize: 12, color: theme.muted, padding: '20px 0' }}>Loading queue…</div>
        ) : queue.length === 0 ? (
          <Card theme={theme} style={{ padding: 20, textAlign: 'center' }}>
            <div style={{ fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text }}>NOTHING IN THE QUEUE</div>
            <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: theme.muted, marginTop: 6 }}>
              When a member submits a song, it lands here.
            </div>
          </Card>
        ) : queue.map(s => {
          const reviewed = s.status === 'reviewed';
          const name = s.member_name || s.member_handle || 'Member';
          return (
            <button key={s.id} onClick={() => !reviewed && openOne(s)} disabled={reviewed} style={{
              width: '100%', textAlign: 'left', padding: 0, border: 'none', background: 'transparent',
              cursor: reviewed ? 'default' : 'pointer', opacity: reviewed ? 0.6 : 1
            }}>
              <Card theme={theme} style={{ padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 10, flexShrink: 0,
                    background: theme.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center'
                  }}>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                      <path d="M9 18V5l10-2v13" stroke={theme.accent} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                      <circle cx="6" cy="18" r="3" stroke={theme.accent} strokeWidth="2" />
                      <circle cx="16" cy="16" r="3" stroke={theme.accent} strokeWidth="2" />
                    </svg>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text, lineHeight: 1, textTransform: 'uppercase' }}>
                      {s.title || 'UNTITLED'}
                    </div>
                    <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 0.5, marginTop: 4 }}>
                      {String(name).toUpperCase()} · {(s.tier || 'quick').toUpperCase()}{s.coach ? ' · → ' + s.coach : ''}
                    </div>
                    <div style={{ fontFamily: theme.fontMono, fontSize: 9, color: theme.faint, letterSpacing: 0.5, marginTop: 2 }}>
                      {rqWhen(s.created_at)}
                    </div>
                  </div>
                  <div style={{
                    padding: '5px 9px', borderRadius: 99, flexShrink: 0,
                    background: `${rqStatusColor(theme, s.status)}20`,
                    color: rqStatusColor(theme, s.status),
                    fontFamily: theme.fontMono, fontSize: 9, letterSpacing: 1, fontWeight: 700
                  }}>{(s.status || 'pending').toUpperCase()}</div>
                </div>
              </Card>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ArtistHistoryView — coach-facing per-member progress / mentoring tracker
// ─────────────────────────────────────────────────────────────
function ArtistHistoryView({ theme, member, onBack }) {
  const [rows, setRows] = useStateRQ(null); // null = loading
  const [playId, setPlayId] = useStateRQ(null);   // submission id being played
  const [playUrl, setPlayUrl] = useStateRQ(null);  // its signed audio URL
  useEffectRQ(() => {
    let alive = true;
    window.LAUNCH_USER.fetchArtistHistory(member.id).then(list => {
      if (alive) setRows(Array.isArray(list) ? list : []);
    });
    return () => { alive = false; };
  }, [member && member.id]);

  const play = (r) => {
    if (playId === r.id) { setPlayId(null); setPlayUrl(null); return; } // toggle off
    setPlayId(r.id); setPlayUrl(null);
    window.LAUNCH_USER.audioUrlFor(r.audio_path).then(u => setPlayUrl(u));
  };

  const list = rows || [];
  const reviewed = list.filter(r => typeof r.total === 'number');
  const best = reviewed.length ? Math.max(...reviewed.map(r => r.total)) : null;
  // reviewed[] is newest-first → latest is [0], first ever is last.
  const latest = reviewed.length ? reviewed[0].total : null;
  const earliest = reviewed.length ? reviewed[reviewed.length - 1].total : null;
  const trend = (latest != null && earliest != null) ? latest - earliest : null;

  const Stat = ({ n, l }) => (
    <Card theme={theme} style={{ padding: 12, flex: 1 }}>
      <div style={{ fontFamily: theme.fontDisplay, fontSize: 24, color: theme.text, lineHeight: 1 }}>{n}</div>
      <div style={{ fontFamily: theme.fontMono, fontSize: 8, color: theme.muted, letterSpacing: 0.8, marginTop: 6, fontWeight: 700, whiteSpace: 'pre-line', lineHeight: 1.3 }}>{l}</div>
    </Card>
  );

  return (
    <div style={{ paddingBottom: 40 }}>
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between'
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer'
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700 }}>MENTORING TRACKER</div>
      </div>

      <div style={{ padding: `4px ${theme.pad}px 0` }}>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 1, fontWeight: 700, marginBottom: 6 }}>★ ARTIST PROGRESS</div>
        <DisplayHeading theme={theme} size={32}>{String(member.name || 'ARTIST').toUpperCase()}</DisplayHeading>
      </div>

      {/* Evolution summary */}
      <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0`, display: 'flex', gap: 8 }}>
        <Stat n={list.length} l={'TRACKS\nSUBMITTED'} />
        <Stat n={reviewed.length} l={'REVIEWED'} />
        <Stat n={best != null ? best + '/50' : '—'} l={'BEST\nSCORE'} />
        <Stat
          n={trend == null ? '—' : (trend > 0 ? '+' + trend : String(trend))}
          l={'TREND\n(SCORE)'} />
      </div>

      {/* Track list */}
      <div style={{ padding: `${theme.gap + 6}px ${theme.pad}px 0`, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {rows === null ? (
          <div style={{ fontFamily: theme.fontMono, fontSize: 12, color: theme.muted }}>Loading history…</div>
        ) : list.length === 0 ? (
          <Card theme={theme} style={{ padding: 20, textAlign: 'center' }}>
            <div style={{ fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text }}>NO TRACKS YET</div>
            <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: theme.muted, marginTop: 6 }}>
              This artist hasn't submitted anything yet.
            </div>
          </Card>
        ) : list.map(r => {
          const isReviewed = typeof r.total === 'number';
          return (
            <Card key={r.id} theme={theme} style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: theme.fontDisplay, fontSize: 17, color: theme.text, textTransform: 'uppercase', lineHeight: 1 }}>
                    {r.title || 'UNTITLED'}
                  </div>
                  <div style={{ fontFamily: theme.fontMono, fontSize: 9, color: theme.muted, letterSpacing: 0.5, marginTop: 4 }}>
                    {(r.tier || 'quick').toUpperCase()} · {rqWhen(r.created_at)}
                  </div>
                </div>
                {isReviewed ? (
                  <div style={{ textAlign: 'right', flexShrink: 0 }}>
                    <div style={{ fontFamily: theme.fontDisplay, fontSize: 22, color: r.total >= 40 ? '#22C55E' : theme.text, lineHeight: 1 }}>
                      {r.total}<span style={{ fontSize: 11, color: theme.muted }}>/50</span>
                    </div>
                  </div>
                ) : (
                  <div style={{
                    padding: '5px 9px', borderRadius: 99, flexShrink: 0,
                    background: `${rqStatusColor(theme, r.status)}20`, color: rqStatusColor(theme, r.status),
                    fontFamily: theme.fontMono, fontSize: 9, letterSpacing: 1, fontWeight: 700
                  }}>{(r.status || 'pending').toUpperCase()}</div>
                )}
              </div>
              {r.audio_path && (
                <div style={{ marginTop: 10 }}>
                  {playId === r.id ? (
                    playUrl ? (
                      <audio controls autoPlay src={playUrl} style={{ width: '100%' }} />
                    ) : (
                      <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 0.5 }}>🎧 Loading audio…</div>
                    )
                  ) : (
                    <button onClick={() => play(r)} style={{
                      padding: '8px 14px', borderRadius: 99,
                      background: theme.surface2, border: `1px solid ${theme.border}`,
                      color: theme.text, cursor: 'pointer',
                      fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700, letterSpacing: 0.8,
                      textTransform: 'uppercase', display: 'inline-flex', alignItems: 'center', gap: 6,
                    }}>▶ Play track</button>
                  )}
                </div>
              )}
              {r.verdict ? (
                <div style={{
                  fontFamily: theme.fontBody, fontSize: 12, color: theme.muted, lineHeight: 1.45,
                  marginTop: 10, paddingTop: 10, borderTop: `1px solid ${theme.border}`,
                  paddingLeft: 10, borderLeft: `2px solid ${theme.accent}`,
                }}>“{r.verdict}”</div>
              ) : null}
            </Card>
          );
        })}
      </div>
    </div>
  );
}

window.LAUNCH_REVIEW_QUEUE = { CoachQueueScreen };
