// screens3.jsx — Pro Review (paid evaluation service)

const { useState: useState3 } = React;
const { Card, Chip, CoverArt, Waveform, TopBar, IconBtn, DisplayHeading, Icon } = window.LAUNCH_SCREENS_1;

const TIERS = [
{
  id: 'quick',
  name: 'QUICK SCORE',
  price: 11,
  eta: '48 HOURS',
  blurb: 'Fast point-based score. 5 categories, 1\u201310 each. Hit 40+/50 to unlock rewards.',
  perks: [
    'Song Structure \u00b7 1\u201310',
    'Title / Hook \u00b7 1\u201310',
    'Idea \u00b7 1\u201310',
    'Lyrics \u00b7 1\u201310',
    'Melody \u00b7 1\u201310',
    'Score 40+ \u2192 rewards & bonus XP'
  ],
  accent: false
},
{
  id: 'full',
  name: 'IN-DEPTH EVAL',
  price: 40,
  eta: '5 DAYS',
  blurb: 'Deep written breakdown + voice note from a Launch mentor. Mix, songwriting, vocals, arrangement.',
  perks: [
    'Mentor-matched to your genre',
    'Written breakdown (~600 words)',
    '5-min voice walkthrough',
    'Stems-level feedback',
    'Full rubric (out of 50)'
  ],
  accent: true,
  badge: 'MOST PICKED'
}];


const REVIEWERS = [
{ lbl: 'JB', color: '#C72820', name: 'Jay Brunswick', displayName: 'Jay', role: 'RIAA Gold · 170+ cuts · 2 Billboard Top 40' },
{ lbl: 'PG', color: '#7A5AE0', name: 'PG Banker',     displayName: 'PG',  role: 'Logic Pro certified · 1,000+ placements' }];


const RECENT_REVIEWS = [
{
  avatar: 'KP', color: '#C72820', name: 'kai.park',
  track: 'NEON HOURS', tier: 'IN-DEPTH EVAL',
  quote: '"Top-line is sticky as hell. Pull the 2k from your vocal bus — it\'s fighting the synth lead."',
  reviewer: 'JAY BRUNSWICK', stars: 5
},
{
  avatar: 'IL', color: '#FBBF24', name: 'isla.loop',
  track: 'LOW TIDE', tier: 'A&R SUBMIT',
  quote: '"Scored 9.1 — pitched to two labels. Hold tight."',
  reviewer: 'A&R PANEL', stars: 5, ar: true
}];


function Stars({ n, color, dim }) {
  return (
    <div style={{ display: 'inline-flex', gap: 2 }}>
      {[0, 1, 2, 3, 4].map((i) =>
      <svg key={i} width="11" height="11" viewBox="0 0 12 12">
          <path d="M6 0.5l1.55 3.65 3.95.3-3 2.6 1 3.85L6 8.85 2.5 10.9l1-3.85-3-2.6 3.95-.3L6 .5z"
        fill={i < n ? color : dim} />
        </svg>
      )}
    </div>);

}

// ─────────────────────────────────────────────────────────────
// Pro Review screen — 2 modes: 'browse' and 'submit'
// ─────────────────────────────────────────────────────────────
function ReviewScreen({ theme, copy, onBack, onOpenEvaluations }) {
  const [mode, setMode] = useState3('browse'); // 'browse' | 'submit' | 'success'
  const [tier, setTier] = useState3('full');
  const [trackTitle, setTrackTitle] = useState3('');
  const [notes, setNotes] = useState3('');
  const [trackUploaded, setTrackUploaded] = useState3(false);
  const [audioFile, setAudioFile] = useState3(null);
  const [coachLbl, setCoachLbl] = useState3('JB');
  const [reviewers, setReviewers] = useState3(REVIEWERS); // demo fallback until the table loads
  const [submitting, setSubmitting] = useState3(false);
  const [submitErr, setSubmitErr] = useState3(null);
  const [agreementGate, setAgreementGate] = useState3(false);  // consent gate before upload
  const [consented, setConsented] = useState3(false);  // read+agreed THIS submission — re-prompts on every upload
  const [creditCents, setCreditCents] = useState3(0);   // review-only credit from redeemed points
  React.useEffect(() => {
    let alive = true;
    if (window.LAUNCH_USER.fetchMyReviewCredit) window.LAUNCH_USER.fetchMyReviewCredit().then(c => { if (alive) setCreditCents(c || 0); });
    return () => { alive = false; };
  }, []);
  const fileRef = React.useRef(null);

  // Load the admin-managed coach roster (Supabase `coaches` table). Falls back
  // to the built-in REVIEWERS list in demo mode / on error.
  React.useEffect(() => {
    let alive = true;
    window.LAUNCH_USER.fetchCoaches().then((list) => {
      if (!alive || !list || !list.length) return;
      setReviewers(list);
      setCoachLbl((prev) => list.some((r) => r.lbl === prev) ? prev : list[0].lbl);
    });
    return () => { alive = false; };
  }, []);

  const selectedTier = TIERS.find((t) => t.id === tier);

  // Plan benefits: basic → 1 free quick ($11); vip → 2 free in-depth ($40).
  const ent = window.LAUNCH_USER.usePlan ? window.LAUNCH_USER.usePlan() : { plan: 'free', quickEval: 0, fullEval: 0 };
  const freeEvalLeft = tier === 'quick' ? (ent.quickEval || 0) : tier === 'full' ? (ent.fullEval || 0) : 0;
  const planCoversThis = freeEvalLeft > 0;

  const ITEM_OF_TIER = { quick: 'quick-score', full: 'full-review' };
  const tierItem = ITEM_OF_TIER[tier] || 'quick-score';
  // On native this review is bought from the App Store / Play Store.
  const storeBuy = !!(window.LAUNCH_USER.buysFromStore && window.LAUNCH_USER.buysFromStore(tierItem));

  // Real store prices, so what we show is what the store will charge.
  const [storePrices, setStorePrices] = useState3({});
  React.useEffect(() => {
    if (!storeBuy) return;
    let alive = true;
    window.LAUNCH_USER.iapItemPrices()
      .then((p) => { if (alive && p) setStorePrices(p); })
      .catch(() => {});
    return () => { alive = false; };
  }, [storeBuy]);
  const storePriceOf = (id) => (storePrices[ITEM_OF_TIER[id]] || {}).price || null;

  // Review-only credit (from redeemed points) applies ONLY to the $40 tier, and
  // only when the plan doesn't already cover it (plan benefit takes priority).
  const priceCents = (selectedTier ? selectedTier.price : 0) * 100;
  const isReviewTier = tier === 'full';
  // A store product is a fixed-price SKU — the store cannot charge "price minus
  // credit". So on native, account credit is all-or-nothing: it either covers
  // the whole review (no store purchase at all) or it doesn't apply, and the
  // store charges full price. Otherwise the total on screen wouldn't match what
  // Apple actually bills.
  const rawCredit = (!planCoversThis && isReviewTier) ? Math.max(0, creditCents) : 0;
  const creditApplied = storeBuy
    ? (rawCredit >= priceCents ? priceCents : 0)
    : Math.min(rawCredit, priceCents);
  const dueCents = planCoversThis ? 0 : Math.max(0, priceCents - creditApplied);

  const onPickFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (f) { setAudioFile(f); setTrackUploaded(true); setSubmitErr(null); }
  };
  // Show the Song Submission Agreement BEFORE the file picker opens — the user
  // can't even choose an audio file until they've read it and ticked "I agree".
  // We prompt on EVERY upload (per-submission `consented` flag), not just the
  // first time, even though the acceptance is still recorded in Supabase.
  const openFilePicker = () => {
    if (!consented) { setAgreementGate(true); return; }
    if (fileRef.current) fileRef.current.click();
  };
  const fmtSize = (b) => b < 1024 * 1024
    ? (b / 1024).toFixed(0) + ' KB'
    : (b / (1024 * 1024)).toFixed(1) + ' MB';
  const doSubmit = async () => {
    // Consent gate: the user must accept the Song Submission Agreement first.
    if (!consented) { setAgreementGate(true); return; }
    setSubmitting(true); setSubmitErr(null);
    const res = await window.LAUNCH_USER.submitSongForReview({
      title: trackTitle, notes, tier, coach: coachLbl, audioFile,
    });
    if (res && res.error) { setSubmitting(false); setSubmitErr(res.error); return; }
    const subId = res.submission && res.submission.id;

    // 1) Plan benefit: a free Quick (basic) or In-Depth (vip) eval — no payment.
    //    Works in both live and demo (claimFreeEval handles both).
    if (planCoversThis && subId && window.LAUNCH_USER.claimFreeEval) {
      const fr = await window.LAUNCH_USER.claimFreeEval(subId, tier);
      if (fr && fr.ok) { setSubmitting(false); (setConsented(false), setMode('success')); return; }
      // claim failed → fall through to the normal paid flow
    }

    // Live mode → charge via Stripe Checkout (redirects out and back).
    if (window.LAUNCH_USER.isConfigured()) {
      // If account credit (from redeemed points) covers the full price, apply it
      // directly — no Stripe, no payment page.
      if (subId && priceCents > 0 && creditApplied >= priceCents && window.LAUNCH_USER.payReviewWithCredit) {
        const pc = await window.LAUNCH_USER.payReviewWithCredit(subId, priceCents);
        if (pc && pc.ok && pc.covered) { setSubmitting(false); (setConsented(false), setMode('success')); return; }
        // credit didn't cover (e.g. stale balance) → fall through to checkout
      }
      const itemMap = { quick: 'quick-score', full: 'full-review' };
      const item = itemMap[tier] || 'quick-score';

      // Inside the native app an evaluation is bought from the App Store /
      // Play Store, not Stripe: it's asynchronous digital content, so it isn't
      // covered by the person-to-person exemption that keeps 1:1 coach
      // sessions on Stripe. The server verifies the purchase before the review
      // is unlocked (iap-fulfill).
      if (window.LAUNCH_USER.buysFromStore(item)) {
        const pr = await window.LAUNCH_USER.purchaseItemInApp(item, subId);
        setSubmitting(false);
        if (pr && pr.cancelled) return;                  // backed out — stay put
        if (pr && pr.error) { setSubmitErr(pr.error); return; }
        (setConsented(false), setMode('success'));
        return;
      }
      // Store billing is required here but unavailable → sell nothing. We must
      // not quietly fall back to Stripe: on iOS that's the 3.1.1 rejection.
      // (On Android this is false until Play billing is configured, so the
      // shipped app keeps charging through Stripe as it does today.)
      if (window.LAUNCH_USER.storeRequiredFor(item)) {
        setSubmitting(false);
        setSubmitErr('Purchases are unavailable in the app right now. Please try again later.');
        return;
      }

      const co = await window.LAUNCH_USER.startCheckout({
        item,
        submissionId: subId,
      });
      if (co && co.error) { setSubmitting(false); setSubmitErr('Saved, but checkout failed: ' + co.error); return; }
      // Account credit fully covered it server-side → no Stripe redirect.
      if (co && co.done) { setSubmitting(false); (setConsented(false), setMode('success')); return; }
      return; // leaving the page for Stripe
    }
    // Demo mode → simulated success.
    setSubmitting(false);
    (setConsented(false), setMode('success'));
  };

  // ───────── SUCCESS ─────────
  if (mode === 'success') {
    return (
      <div style={{ paddingBottom: 110, minHeight: '100%' }}>
        <TopBar theme={theme}
        left={null}
        right={<IconBtn theme={theme}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M2 2l10 10M12 2L2 12" stroke={theme.text} strokeWidth="2" strokeLinecap="round" />
            </svg>
          </IconBtn>} />
        
        <div style={{ padding: `40px ${theme.pad}px 0`, textAlign: 'center' }}>
          <div style={{
            width: 88, height: 88, borderRadius: 99, background: theme.accent,
            margin: '0 auto 24px', display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none">
              <path d="M5 12l5 5L20 6" stroke={theme.onAccent} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <div style={{
            fontFamily: theme.fontMono, fontSize: 11, color: theme.accent,
            letterSpacing: 1, fontWeight: 700, marginBottom: 8
          }}>SUBMITTED · {dueCents <= 0 ? 'COVERED BY CREDIT' : '$' + (dueCents / 100).toFixed(0) + ' CHARGED'}</div>
          <DisplayHeading theme={theme} size={36}>
            YOUR TRACK<br />IS IN THE QUEUE
          </DisplayHeading>
          <div style={{
            fontFamily: theme.fontBody, fontSize: 15, color: theme.muted,
            marginTop: 14, lineHeight: 1.5, padding: '0 12px'
          }}>
            Expect your review within <span style={{ color: theme.text, fontWeight: 600 }}>{selectedTier.eta.toLowerCase()}</span>. We'll notify you the moment it drops.
          </div>
          <Card theme={theme} style={{ padding: 16, marginTop: 24, textAlign: 'left' }}>
            <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700, marginBottom: 10 }}>
              ORDER · LCH-2487
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.muted }}>Track</span>
              <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.text, fontWeight: 600 }}>
                {trackTitle || 'Untitled Demo v3'}
              </span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.muted }}>Tier</span>
              <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.text, fontWeight: 600 }}>
                {selectedTier.name}
              </span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.muted }}>ETA</span>
              <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.accent, fontWeight: 600 }}>
                {selectedTier.eta}
              </span>
            </div>
          </Card>
          <button onClick={onBack} style={{
            marginTop: 18, width: '100%', background: theme.text, color: theme.bg,
            fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
            padding: '14px 18px', borderRadius: 12, border: 'none', cursor: 'pointer',
            textTransform: 'uppercase'
          }}>BACK TO HOME</button>
        </div>
      </div>);

  }

  // ───────── SUBMIT FORM ─────────
  if (mode === 'submit') {
    const canSubmit = trackTitle.trim() && audioFile && !submitting;
    return (
      <div style={{ paddingBottom: 130 }}>
        {/* Top bar with back */}
        <div style={{
          paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between'
        }}>
          <button onClick={() => setMode('browse')} 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
          }}>STEP 2 / 2</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 }}>
            {selectedTier.name} · {storePriceOf(tier) || '$' + selectedTier.price}
          </div>
          <DisplayHeading theme={theme} size={32}>
            DROP YOUR<br />TRACK
          </DisplayHeading>
        </div>

        {/* Upload area */}
        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0` }}>
          <input
            ref={fileRef}
            type="file"
            accept="audio/*,.wav,.mp3,.aiff,.aif,.m4a"
            onChange={onPickFile}
            style={{ display: 'none' }} />
          <button onClick={openFilePicker} style={{
            width: '100%', padding: 18, borderRadius: 14,
            border: `2px dashed ${trackUploaded ? theme.accent : theme.border}`,
            background: trackUploaded ? `${theme.accent}15` : 'transparent',
            cursor: 'pointer', textAlign: 'left',
            display: 'flex', alignItems: 'center', gap: 14
          }}>
            {trackUploaded ?
            <>
                <CoverArt palette={[theme.accent, '#FBBF24']} label="??" size={56} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 1, fontWeight: 700 }}>
                    ✓ UPLOADED{audioFile ? ' · ' + fmtSize(audioFile.size) : ''}
                  </div>
                  <div style={{
                  fontFamily: theme.fontBody, fontSize: 15, color: theme.text,
                  fontWeight: 600, marginTop: 2,
                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'
                }}>{audioFile ? audioFile.name : 'your track'}</div>
                  <div style={{ marginTop: 6 }}>
                    <Waveform accent={theme.accent} muted={theme.faint} bars={32} played={0} />
                  </div>
                </div>
              </> :

            <>
                <div style={{
                width: 56, height: 56, borderRadius: 14,
                background: theme.surface2,
                display: 'flex', alignItems: 'center', justifyContent: 'center'
              }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                    <path d="M12 4v12m0-12l-5 5m5-5l5 5M5 20h14" stroke={theme.text} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{
                  fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text,
                  textTransform: 'uppercase', letterSpacing: 0.2, lineHeight: 1
                }}>UPLOAD A TRACK</div>
                  <div style={{
                  fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
                  letterSpacing: 0.5, marginTop: 4, fontWeight: 600
                }}>WAV · MP3 · AIFF · 50MB MAX</div>
                </div>
              </>
            }
          </button>
        </div>

        {/* Form fields */}
        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0`, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <label style={{
              fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
              letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 8
            }}>TRACK TITLE</label>
            <input
              value={trackTitle}
              onChange={(e) => setTrackTitle(e.target.value)}
              placeholder="e.g. NEON HOURS"
              style={{
                width: '100%', padding: '14px 16px', borderRadius: 12,
                background: theme.surface, border: `1px solid ${theme.border}`,
                color: theme.text, fontFamily: theme.fontBody, fontSize: 15,
                outline: 'none'
              }}
              onFocus={(e) => e.target.style.borderColor = theme.accent}
              onBlur={(e) => e.target.style.borderColor = theme.border} />
            
          </div>

          <div>
            <label style={{
              fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
              letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 8
            }}>WHAT DO YOU WANT FEEDBACK ON?</label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="Mix? Songwriting? The vibe? Be specific — better notes = better review."
              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'
              }}
              onFocus={(e) => e.target.style.borderColor = theme.accent}
              onBlur={(e) => e.target.style.borderColor = theme.border} />
            
          </div>

          {/* Reviewer preference */}
          <div>
            <label style={{
              fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
              letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 8
            }}>PICK YOUR COACH</label>
            <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: `0 -${theme.pad}px`, padding: `0 ${theme.pad}px` }}>
              {reviewers.map((r, i) => {
                const picked = coachLbl === r.lbl;
                return (
                <button key={i} onClick={() => setCoachLbl(r.lbl)} style={{
                  flexShrink: 0, padding: '8px 12px 10px', borderRadius: 12,
                  background: picked ? `${theme.accent}15` : theme.surface,
                  border: `${picked ? 2 : 1}px solid ${picked ? theme.accent : theme.border}`,
                  display: 'flex', alignItems: 'center', gap: 8, minWidth: 200,
                  cursor: 'pointer', textAlign: 'left'
                }}>
                  <div style={{
                  width: 32, height: 32, borderRadius: 99, background: r.color,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: theme.fontDisplay, color: '#0A0A0A', fontSize: 12,
                  flexShrink: 0
                }}>{r.lbl}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: theme.fontBody, fontSize: 12, color: theme.text, fontWeight: 600 }}>
                      {r.displayName || r.name}
                    </div>
                    <div style={{ fontFamily: theme.fontMono, fontSize: 9, color: theme.muted, letterSpacing: 0.5 }}>
                      {r.role.toUpperCase()}
                    </div>
                  </div>
                  {picked && <span style={{ fontFamily: theme.fontMono, fontSize: 12, color: theme.accent, fontWeight: 700 }}>✓</span>}
                </button>
                );
              })}
            </div>
          </div>
        </div>

        {/* Sticky pay bar */}
        <div style={{
          position: 'absolute', bottom: 86, 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 }}>
            {(planCoversThis || creditApplied > 0) && !submitErr &&
            <div style={{ fontFamily: theme.fontMono, fontSize: 9, color: '#22C55E', letterSpacing: 0.8, fontWeight: 700 }}>
              {planCoversThis
                ? `INCLUDED · ${String(ent.plan || '').toUpperCase()} PLAN · ${freeEvalLeft} LEFT`
                : `ACCOUNT CREDIT −$${(creditApplied / 100).toFixed(0)}`}
            </div>
            }
            <div style={{ fontFamily: theme.fontMono, fontSize: 9, color: submitErr ? theme.accent : theme.muted, letterSpacing: 1, fontWeight: 700, marginTop: (planCoversThis || creditApplied > 0) ? 2 : 0 }}>
              {submitErr ? '⚠ ' + submitErr.toUpperCase() : (dueCents <= 0 ? (planCoversThis ? 'FREE WITH YOUR PLAN' : 'COVERED BY CREDIT') : 'TOTAL · ' + selectedTier.eta)}
            </div>
            <div style={{ fontFamily: theme.fontDisplay, fontSize: 26, color: theme.text, lineHeight: 1, marginTop: 2 }}>
              {dueCents > 0 && storePriceOf(tier)
                // What the store will actually charge — never a number of ours
                // that could differ from Apple's price for this storefront.
                ? storePriceOf(tier)
                : <React.Fragment>${(dueCents / 100).toFixed(0)}<span style={{ fontSize: 13, color: theme.muted }}>.00</span></React.Fragment>}
            </div>
          </div>
          <button
            onClick={doSubmit}
            disabled={!canSubmit}
            style={{
              background: canSubmit ? theme.accent : theme.surface2,
              color: canSubmit ? theme.onAccent : theme.faint,
              fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
              padding: '14px 18px', borderRadius: 12, border: 'none',
              cursor: canSubmit ? 'pointer' : 'not-allowed',
              textTransform: 'uppercase'
            }}>{submitting ? 'SENDING…' : (dueCents <= 0 ? 'SUBMIT · FREE →' : 'SUBMIT & PAY →')}</button>
        </div>

        {/* Consent gate — must be accepted before picking a file or submitting */}
        {agreementGate && window.LAUNCH_AGREEMENT &&
          <window.LAUNCH_AGREEMENT.SongAgreementGate
            theme={theme}
            onClose={() => setAgreementGate(false)}
            onAccepted={() => { setAgreementGate(false); setConsented(true); if (fileRef.current) fileRef.current.click(); }}
          />
        }
      </div>);

  }

  // ───────── BROWSE / TIER PICKER ─────────
  return (
    <div style={{ paddingBottom: 130 }}>
      {/* Top bar with back */}
      <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={() => onOpenEvaluations && onOpenEvaluations()} style={{
          padding: '7px 12px', borderRadius: 99, background: theme.surface,
          border: `1px solid ${theme.border}`, color: theme.accent, cursor: 'pointer',
          fontFamily: theme.fontMono, fontSize: 10, letterSpacing: 1, fontWeight: 700
        }}>MY REVIEWS →</button>
      </div>

      {/* Hero */}
      <div style={{ padding: `4px ${theme.pad}px 0` }}>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 1, fontWeight: 700, marginBottom: 6 }}>
          PRO REVIEW
        </div>
        <DisplayHeading theme={theme} size={36}>
          GET YOUR<br />TRACK <span style={{ color: theme.accent }}>HEARD</span>
        </DisplayHeading>
        <div style={{
          fontFamily: theme.fontBody, fontSize: 14, color: theme.muted,
          marginTop: 10, lineHeight: 1.5
        }}>
          Real feedback from signed producers, mix engineers, and A&R. Pay once. No subscriptions. Top scores get pitched to labels.
        </div>
      </div>

      {/* Tier cards */}
      <div style={{ padding: `${theme.gap + 6}px ${theme.pad}px 0`, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {TIERS.map((t) => {
          const selected = tier === t.id;
          return (
            <button
              key={t.id}
              onClick={() => setTier(t.id)}
              style={{
                background: t.accent ? theme.accent : theme.surface,
                color: t.accent ? theme.onAccent : theme.text,
                border: selected ?
                `2px solid ${t.accent ? '#0A0A0A' : theme.accent}` :
                `1px solid ${theme.border}`,
                borderRadius: theme.radius, padding: 16,
                cursor: 'pointer', textAlign: 'left',
                position: 'relative'
              }}>
              
              {t.badge &&
              <div style={{
                position: 'absolute', top: -8, left: 16,
                background: t.accent ? '#0A0A0A' : theme.accent,
                color: t.accent ? '#fff' : theme.onAccent,
                fontFamily: theme.fontMono, fontSize: 9, fontWeight: 700,
                letterSpacing: 0.8, padding: '4px 10px', borderRadius: 99
              }}>{t.badge}</div>
              }
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
                <div style={{ flex: 1, color: "rgb(199, 33, 8)" }}>
                  <div style={{
                    fontFamily: theme.fontDisplay, fontSize: 22,
                    letterSpacing: 0.3, lineHeight: 1
                  }}>{t.name}</div>
                  <div style={{
                    fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
                    letterSpacing: 1, marginTop: 6,
                    opacity: t.accent ? 0.7 : 1,
                    color: t.accent ? theme.onAccent : theme.muted
                  }}>ETA · {t.eta}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{
                    fontFamily: theme.fontDisplay, fontSize: 30, lineHeight: 1,
                    letterSpacing: -0.5
                  }}>
                    {storePriceOf(t.id)
                      // Store price, formatted for the buyer's storefront.
                      ? storePriceOf(t.id)
                      : <React.Fragment><span style={{ fontSize: 16, verticalAlign: 'top', opacity: 0.7 }}>$</span>{t.price}</React.Fragment>}
                  </div>
                  <div style={{
                    fontFamily: theme.fontMono, fontSize: 9, fontWeight: 700,
                    letterSpacing: 0.8, marginTop: 2,
                    opacity: t.accent ? 0.7 : 1,
                    color: t.accent ? theme.onAccent : theme.muted
                  }}>ONE-TIME</div>
                </div>
              </div>
              <div style={{
                fontFamily: theme.fontBody, fontSize: 13,
                marginTop: 10, lineHeight: 1.5,
                opacity: t.accent ? 0.85 : 1,
                color: t.accent ? theme.onAccent : theme.muted
              }}>{t.blurb}</div>
              <div style={{
                marginTop: 12, paddingTop: 12,
                borderTop: t.accent ? '1px solid rgba(10,10,10,0.15)' : `1px solid ${theme.border}`,
                display: 'flex', flexDirection: 'column', gap: 6
              }}>
                {t.perks.map((p, i) =>
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
                      <path d="M2 7l3.5 3.5L12 4" stroke={t.accent ? '#0A0A0A' : theme.accent} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                    <span style={{
                    fontFamily: theme.fontBody, fontSize: 12, fontWeight: 500,
                    color: t.accent ? theme.onAccent : theme.text
                  }}>{p}</span>
                  </div>
                )}
              </div>
              {selected &&
              <div style={{
                marginTop: 12, padding: '8px 12px', borderRadius: 8,
                background: t.accent ? 'rgba(10,10,10,0.15)' : `${theme.accent}15`,
                color: t.accent ? '#0A0A0A' : theme.accent,
                fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
                letterSpacing: 1, textAlign: 'center'
              }}>SELECTED ✓</div>
              }
            </button>);

        })}
      </div>

      {/* Recent reviews */}
      <div style={{ padding: `${theme.gap + 10}px ${theme.pad}px 0` }}>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 11, color: theme.muted,
          letterSpacing: 1, fontWeight: 600, marginBottom: 10
        }}>RECENT REVIEWS · FROM THE SQUAD</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {RECENT_REVIEWS.map((r, i) =>
          <Card key={i} theme={theme} style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <div style={{
                width: 32, height: 32, borderRadius: 99, background: r.color,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: theme.fontDisplay, color: '#0A0A0A', fontSize: 12
              }}>{r.avatar}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: theme.text, fontWeight: 600 }}>
                    {r.name} · {r.track}
                  </div>
                  <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 0.5, fontWeight: 700, marginTop: 1 }}>
                    {r.tier} {r.ar && '· PITCHED'}
                  </div>
                </div>
                <Stars n={r.stars} color={theme.accent} dim={theme.surface2} />
              </div>
              <div style={{
              fontFamily: theme.fontBody, fontStyle: 'italic',
              fontSize: 13, color: theme.text, lineHeight: 1.5,
              paddingLeft: 12, borderLeft: `2px solid ${theme.accent}`
            }}>{r.quote}</div>
              <div style={{
              fontFamily: theme.fontMono, fontSize: 9, color: theme.muted,
              letterSpacing: 1, fontWeight: 700, marginTop: 8
            }}>— {r.reviewer}</div>
            </Card>
          )}
        </div>
      </div>

      {/* Trust strip */}
      <div style={{
        padding: `${theme.gap + 6}px ${theme.pad}px 0`,
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8
      }}>
        {[
        { n: '12K+', l: 'TRACKS\nREVIEWED' },
        { n: '47', l: 'LABEL\nPLACEMENTS' },
        { n: '4.9', l: 'AVG\nRATING' }].
        map((s, i) =>
        <div key={i} style={{ textAlign: 'center', padding: '12px 8px' }}>
            <div style={{ fontFamily: theme.fontDisplay, fontSize: 26, color: theme.text, lineHeight: 1, letterSpacing: -0.5 }}>
              {s.n}
            </div>
            <div style={{
            fontFamily: theme.fontMono, fontSize: 9, color: theme.muted,
            letterSpacing: 0.8, marginTop: 6, whiteSpace: 'pre-line', lineHeight: 1.3,
            fontWeight: 600
          }}>{s.l}</div>
          </div>
        )}
      </div>

      {/* Sticky CTA */}
      <div style={{
        position: 'absolute', bottom: 86, 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: theme.muted, letterSpacing: 1, fontWeight: 700 }}>
            SELECTED · {selectedTier.eta}
          </div>
          <div style={{ fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text, lineHeight: 1, marginTop: 2, letterSpacing: 0.2 }}>
            {selectedTier.name} · {storePriceOf(tier) || '$' + selectedTier.price}
          </div>
        </div>
        <button onClick={() => setMode('submit')} style={{
          background: theme.accent, color: theme.onAccent,
          fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
          padding: '14px 18px', borderRadius: 12, border: 'none', cursor: 'pointer',
          textTransform: 'uppercase'
        }}>CONTINUE →</button>
      </div>
    </div>);

}

// ─────────────────────────────────────────────────────────────
// "Pro Review" CTA — drop into other screens as a promo card
// ─────────────────────────────────────────────────────────────
function ProReviewCTA({ theme, onOpen, variant = 'card' }) {
  if (variant === 'inline') {
    return (
      <button onClick={onOpen} style={{
        width: '100%', display: 'flex', alignItems: 'center', gap: 12,
        background: 'transparent', border: `1px dashed ${theme.accent}`,
        borderRadius: 12, padding: '12px 14px', cursor: 'pointer', textAlign: 'left'
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8, background: `${theme.accent}20`,
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <svg width="14" height="16" viewBox="0 0 14 16" fill={theme.accent}>
            <path d="M8 1L2 9h4l-1 6 7-9H8l1-5z" />
          </svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: theme.fontDisplay, fontSize: 14, color: theme.text, letterSpacing: 0.3, textTransform: 'uppercase' }}>
            WANT IT REVIEWED BY A PRO?
          </div>
          <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 0.5, marginTop: 2 }}>
            FROM $11 · 48H TURNAROUND
          </div>
        </div>
        <span style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 1, fontWeight: 700 }}>
          GO →
        </span>
      </button>);

  }

  return (
    <button onClick={onOpen} style={{
      width: '100%', background: '#0A0A0A', color: '#fff',
      borderRadius: 18, padding: 16, border: 'none', cursor: 'pointer',
      textAlign: 'left', position: 'relative', overflow: 'hidden'
    }}>
      {/* Decorative accent bar */}
      <div style={{
        position: 'absolute', top: 0, right: 0, bottom: 0, width: 80,
        background: `linear-gradient(135deg, ${theme.accent} 0%, transparent 100%)`,
        opacity: 0.4
      }} />
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
          letterSpacing: 1, color: theme.accent,
          padding: '4px 8px', border: `1px solid ${theme.accent}`,
          borderRadius: 99
        }}>PRO REVIEW</div>
        <span style={{ fontFamily: theme.fontMono, fontSize: 10, color: 'rgba(255,255,255,0.5)', letterSpacing: 0.5 }}>
          FROM $11
        </span>
      </div>
      <div style={{
        fontFamily: theme.fontDisplay, fontSize: 24, marginTop: 10,
        letterSpacing: 0.2, lineHeight: 1, textTransform: 'uppercase'
      }}>
        SUBMIT A TRACK<br />FOR <span style={{ color: theme.accent }}>REAL FEEDBACK</span>
      </div>
      <div style={{
        fontFamily: theme.fontBody, fontSize: 12, color: 'rgba(255,255,255,0.6)',
        marginTop: 8, lineHeight: 1.4
      }}>
        Signed producers, mix engineers, A&R. Top scores pitched to labels.
      </div>
      <div style={{
        marginTop: 12, display: 'inline-flex', alignItems: 'center', gap: 6,
        fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
        letterSpacing: 1, color: theme.accent
      }}>
        SEE PRICING <svg width="10" height="10" viewBox="0 0 14 14" fill="none"><path d="M3 7h8m0 0L7 3m4 4L7 11" stroke={theme.accent} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
      </div>
    </button>);

}

window.LAUNCH_SCREENS_3 = { ReviewScreen, ProReviewCTA };