// subscription.jsx — PsyFit Pro: paywall, Google Play billing stub, manage sheet.
//
// IMPORTANT: this is a STUB. Real Google Play Billing is not connected yet.
// Nothing here charges money — the "Google Play" step is a faithful-looking
// simulation so the finish-workout gate and the upgrade flow can be demoed
// end-to-end. When you wire up real billing, replace runGooglePlayPurchase()
// with a call into the Play Billing Library / your backend and keep the rest.

const PRO_PRICE = '$3.99';
const PRO_PERIOD = 'month';
const TRIAL_DAYS = 3;
const PRO_PRODUCT = 'psyfit_pro_monthly';

const SUB_DEFAULTS = { status: 'none', startedAt: null, renewsAt: null, canceledAt: null };

const DAY_MS = 86400000;

// ── entitlement helpers ──────────────────────────────────────
function subDaysLeft(ts) {
  if (!ts) return 0;
  return Math.max(0, Math.ceil((ts - Date.now()) / DAY_MS));
}
// True while the user may log/finish workouts. A canceled sub keeps access
// until the paid period (renewsAt) runs out, just like real Google Play.
function isPro(sub) {
  if (!sub) return false;
  if (sub.status === 'trial' || sub.status === 'active') return true;
  if (sub.status === 'canceled') return !!sub.renewsAt && Date.now() < sub.renewsAt;
  return false;
}
function makeTrial() {
  const now = Date.now();
  return { status: 'trial', startedAt: now, renewsAt: now + TRIAL_DAYS * DAY_MS, canceledAt: null };
}
function makeActive() {
  const now = Date.now();
  return { status: 'active', startedAt: now, renewsAt: now + 30 * DAY_MS, canceledAt: null };
}
function fmtDate(ts) {
  if (!ts) return '';
  return new Date(ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

// Short human status line used on the profile card.
function subStatusLine(sub) {
  if (!sub || sub.status === 'none') return 'Free plan · upgrade to unlock Pro features';
  if (sub.status === 'trial') { const d = subDaysLeft(sub.renewsAt); return `Free trial · ${d} day${d === 1 ? '' : 's'} left`; }
  if (sub.status === 'active') return `${PRO_PRICE}/${PRO_PERIOD} · renews ${fmtDate(sub.renewsAt)}`;
  if (sub.status === 'canceled') return isPro(sub) ? `Canceled · access until ${fmtDate(sub.renewsAt)}` : 'Canceled · upgrade to unlock Pro features';
  return '';
}

const PRO_BENEFITS = [
  { icon: 'plus', label: 'Build custom workouts', sub: 'Design your own plans from scratch, your way' },
  { icon: 'flame', label: 'Advanced training programs', sub: 'Multi-week progressive programs with auto-scheduling' },
  { icon: 'bolt', label: 'Pro workout templates', sub: 'Unlock the full catalog of expert-designed plans' },
];

// ── tiny Google Play wordmark (original mark — not Google’s logo) ──
function PlayMark({ size = 18 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: size + 8, height: size + 8, borderRadius: 7, background: '#fff',
      border: '1px solid rgba(0,0,0,0.12)', flexShrink: 0 }}>
      <svg width={size - 2} height={size - 2} viewBox="0 0 24 24" style={{ display: 'block' }}>
        <path d="M3 2.5v19l11-9.5L3 2.5z" fill="#5566ff" />
        <path d="M3 2.5l11 9.5 3.4-2.9L4.4 1.8A1.6 1.6 0 0 0 3 2.5z" fill="#43c6ac" />
        <path d="M3 21.5l11-9.5 3.4 2.9-13 7.3A1.6 1.6 0 0 1 3 21.5z" fill="#ff6a6a" />
        <path d="M17.4 9.1L14 12l3.4 2.9 3.6-2a1.2 1.2 0 0 0 0-1.8l-3.6-2z" fill="#ffc24a" />
      </svg>
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// PAYWALL  — PsyFit-branded offer, then hands off to the GP billing stub.
// onSubscribed() is called once the (simulated) purchase succeeds.
// ─────────────────────────────────────────────────────────────
function PaywallSheet({ onClose, onSubscribed, reason }) {
  const c = useTheme();
  const [step, setStep] = React.useState('offer');

  return (
    <SheetShell title="PsyFit Pro" subtitle={reason === 'custom'
      ? 'Custom workouts are a Pro feature.'
      : reason === 'plans'
      ? 'Unlock every PsyFit Pro workout plan.'
      : 'Unlock the full PsyFit Pro experience.'} onClose={onClose}>

      {/* hero */}
      <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--radius)',
        border: `1px solid ${c.accent}55`, padding: '18px 18px 16px', marginBottom: 16,
        background: `radial-gradient(130% 130% at 100% 0%, ${c.accent}26, transparent 60%), var(--surface-2)` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <span style={{ width: 34, height: 34, borderRadius: 9, background: c.accent, color: c.accentInk,
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="bolt" size={20} /></span>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 24, letterSpacing: 0.6, color: 'var(--text)', whiteSpace: 'nowrap' }}>
            PSY<span style={{ color: c.accent }}>FIT</span> PRO
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 40, lineHeight: 1, color: 'var(--text)', whiteSpace: 'nowrap' }}>{PRO_PRICE}<span style={{ fontSize: 22, opacity: 0.6 }}>/{PRO_PERIOD}</span></span>
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, color: 'var(--muted)', marginTop: 10 }}>
          {PRO_PRICE}/{PRO_PERIOD} · Cancel anytime.
        </div>
      </div>

      {/* benefits */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
        {PRO_BENEFITS.map((b, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
            <span style={{ width: 30, height: 30, borderRadius: 8, flexShrink: 0, background: 'var(--surface-2)',
              border: '1px solid var(--border)', color: c.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={b.icon} size={17} />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14.5, color: 'var(--text)' }}>{b.label}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--muted)', marginTop: 1 }}>{b.sub}</div>
            </div>
          </div>
        ))}
      </div>

      <AccentButton onClick={() => setStep('billing')} icon={<Icon name="bolt" size={18} />}>
        Subscribe · {PRO_PRICE}/{PRO_PERIOD}
      </AccentButton>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, marginTop: 12,
        fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--muted)' }}>
        <PlayMark size={15} />
        <span>Billed through Google Play · cancel anytime</span>
      </div>
      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, lineHeight: 1.5, color: 'var(--dim)', textAlign: 'center', marginTop: 10, padding: '0 4px' }}>
        {PRO_PRICE}/{PRO_PERIOD}, billed monthly. Cancel anytime in Google Play before your next renewal date.
      </div>

      {step === 'billing' && (
        <GooglePlayPurchase
          onCancel={() => setStep('offer')}
          onSuccess={onSubscribed} />
      )}
    </SheetShell>
  );
}

// ─────────────────────────────────────────────────────────────
// GOOGLE PLAY BILLING STUB
// A neutral, system-styled confirmation layer that stands in for the native
// Google Play purchase sheet. Original styling — references Google Play by
// name only. Replace runGooglePlayPurchase() with the real Billing call later.
// ─────────────────────────────────────────────────────────────
function runGooglePlayPurchase() {
  // Simulated network/billing round-trip. Resolves "purchased".
  return new Promise(resolve => setTimeout(resolve, 1700));
}

const gpFont = '-apple-system, "Segoe UI", Roboto, system-ui, sans-serif';

function GooglePlayPurchase({ onCancel, onSuccess }) {
  const [phase, setPhase] = React.useState('confirm'); // 'confirm' | 'processing' | 'done'

  const subscribe = async () => {
    setPhase('processing');
    await runGooglePlayPurchase();
    setPhase('done');
    setTimeout(() => onSuccess && onSuccess(), 900);
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 60, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={phase === 'confirm' ? onCancel : undefined}
        style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)', animation: 'psyfade .18s ease' }} />
      <div style={{ position: 'relative', background: '#fff', color: '#1f1f1f', fontFamily: gpFont,
        borderTopLeftRadius: 18, borderTopRightRadius: 18, padding: '18px 20px calc(env(safe-area-inset-bottom) + 22px)',
        animation: 'psyslide .26s cubic-bezier(.2,.8,.2,1)', boxShadow: '0 -10px 40px rgba(0,0,0,0.3)' }}>

        {/* GP header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingBottom: 14, borderBottom: '1px solid #eee' }}>
          <PlayMark size={20} />
          <span style={{ fontSize: 16, fontWeight: 600, letterSpacing: 0.1 }}>Google Play</span>
          <span style={{ marginLeft: 'auto', fontSize: 11.5, fontWeight: 600, color: '#9aa0a6',
            border: '1px solid #e3e3e3', borderRadius: 999, padding: '3px 9px' }}>Demo</span>
        </div>

        {phase === 'done' ? (
          <div style={{ padding: '30px 0 18px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
            <span style={{ width: 56, height: 56, borderRadius: 999, background: '#1b8a4b', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="check" size={30} stroke={2.6} />
            </span>
            <div style={{ fontSize: 17, fontWeight: 600 }}>You’re subscribed</div>
            <div style={{ fontSize: 13.5, color: '#5f6368', textAlign: 'center', lineHeight: 1.5 }}>
              You’re now subscribed to PsyFit Pro. Enjoy.
            </div>
          </div>
        ) : (
          <>
            {/* item */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '16px 0 14px' }}>
              <span style={{ width: 44, height: 44, borderRadius: 11, background: '#0A0B0D', color: '#C8FF2E',
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="bolt" size={24} />
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>PsyFit Pro</div>
                <div style={{ fontSize: 13, color: '#5f6368' }}>{PRO_PRICE}/{PRO_PERIOD} · cancel anytime</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{PRO_PRICE}</div>
                <div style={{ fontSize: 12, color: '#5f6368' }}>/{PRO_PERIOD}</div>
              </div>
            </div>

            {/* payment method row */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 0', borderTop: '1px solid #eee', borderBottom: '1px solid #eee' }}>
              <span style={{ width: 34, height: 22, borderRadius: 4, background: 'linear-gradient(135deg,#1a3a8f,#2b6fd6)', flexShrink: 0 }} />
              <span style={{ flex: 1, fontSize: 14, color: '#1f1f1f' }}>Visa ···· 4242</span>
              <span style={{ fontSize: 13, color: '#5566ff', fontWeight: 600 }}>Change</span>
            </div>

            <div style={{ fontSize: 12, lineHeight: 1.55, color: '#5f6368', padding: '13px 0 16px' }}>
              Free for {TRIAL_DAYS} days, then {PRO_PRICE}/{PRO_PERIOD} starting {fmtDate(Date.now() + TRIAL_DAYS * DAY_MS)}.
              Cancel anytime in Google Play at least 24 hours before renewal. No real charge — billing isn’t connected yet.
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <button onClick={onCancel} disabled={phase === 'processing'} style={{ flex: '0 0 auto', padding: '11px 18px',
                borderRadius: 999, border: 'none', background: 'transparent', color: '#5566ff', fontFamily: gpFont,
                fontSize: 14.5, fontWeight: 600, cursor: phase === 'processing' ? 'default' : 'pointer', opacity: phase === 'processing' ? 0.4 : 1 }}>
                Cancel
              </button>
              <button onClick={subscribe} disabled={phase === 'processing'} style={{ flex: 1, padding: '13px 18px',
                borderRadius: 999, border: 'none', background: '#5566ff', color: '#fff', fontFamily: gpFont,
                fontSize: 14.5, fontWeight: 600, cursor: phase === 'processing' ? 'default' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9 }}>
                {phase === 'processing'
                  ? <><span style={{ width: 17, height: 17, borderRadius: 999, border: '2.5px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', animation: 'psyspin .7s linear infinite' }} />Processing…</>
                  : '1-tap subscribe'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// MANAGE SUBSCRIPTION  — status, billing date, cancel / resubscribe.
// ─────────────────────────────────────────────────────────────
function SubscriptionSheet({ onClose, ctx }) {
  const c = useTheme();
  const { sub, setSub, openPaywall } = ctx;
  const [confirmCancel, setConfirmCancel] = React.useState(false);
  const pro = isPro(sub);
  const status = sub ? sub.status : 'none';

  const cancel = () => setSub({ ...sub, status: 'canceled', canceledAt: Date.now() });
  const resume = () => setSub({ ...sub, status: sub.startedAt ? 'active' : 'trial', canceledAt: null });

  // Headline state block
  const head = (() => {
    if (status === 'trial') {
      const d = subDaysLeft(sub.renewsAt);
      return { tag: 'Free trial', big: `${d} day${d === 1 ? '' : 's'} left`, sub: `Then ${PRO_PRICE}/${PRO_PERIOD} on ${fmtDate(sub.renewsAt)}` };
    }
    if (status === 'active') return { tag: 'PsyFit Pro', big: 'Active', sub: `${PRO_PRICE}/${PRO_PERIOD} · renews ${fmtDate(sub.renewsAt)}` };
    if (status === 'canceled') return pro
      ? { tag: 'Canceled', big: 'Ends soon', sub: `Pro access until ${fmtDate(sub.renewsAt)}` }
      : { tag: 'Expired', big: 'Free plan', sub: 'Subscribe again for custom workouts & programs' };
    return { tag: 'Free plan', big: 'Not subscribed', sub: 'Upgrade for custom workouts & Pro programs' };
  })();

  return (
    <SheetShell title="Subscription" subtitle="Manage your PsyFit Pro plan." onClose={onClose}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

        {/* status card */}
        <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--radius)', padding: '18px',
          border: `1px solid ${pro ? c.accent + '55' : 'var(--border)'}`,
          background: pro ? `radial-gradient(130% 130% at 100% 0%, ${c.accent}22, transparent 60%), var(--surface-2)` : 'var(--surface-2)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span style={{ width: 26, height: 26, borderRadius: 7, background: pro ? c.accent : 'var(--surface-3)',
              color: pro ? c.accentInk : 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="bolt" size={15} />
            </span>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: pro ? c.accent : 'var(--muted)' }}>{head.tag}</span>
          </div>
          <Display size={32}>{head.big}</Display>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, color: 'var(--muted)', marginTop: 8 }}>{head.sub}</div>
        </div>

        {/* billing details */}
        {pro && (
          <Card pad={0}>
            <Row label="Plan" value="PsyFit Pro (monthly)" />
            <Row label="Price" value={`${PRO_PRICE}/${PRO_PERIOD}`} top />
            <Row label={status === 'canceled' ? 'Access ends' : (status === 'trial' ? 'First charge' : 'Next charge')} value={fmtDate(sub.renewsAt)} top />
            <Row label="Payment" value="Google Play · Visa ···· 4242" top />
          </Card>
        )}

        {/* actions */}
        {!pro && (
          <AccentButton onClick={() => openPaywall('upgrade')} icon={<Icon name="bolt" size={18} />}>
            Subscribe · {PRO_PRICE}/{PRO_PERIOD}
          </AccentButton>
        )}

        {pro && status !== 'canceled' && (
          confirmCancel ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: 15, borderRadius: 'var(--radius-sm)',
              background: 'var(--surface-2)', border: '1px solid var(--border)' }}>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--text)' }}>
                Cancel your subscription? You’ll keep Pro access until {fmtDate(sub.renewsAt)}, then drop to the free plan.
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => setConfirmCancel(false)} style={ghostBtn}>Keep Pro</button>
                <button onClick={() => { cancel(); setConfirmCancel(false); }} style={dangerBtn}>Cancel subscription</button>
              </div>
            </div>
          ) : (
            <button onClick={() => setConfirmCancel(true)} style={ghostBtn}>Cancel subscription</button>
          )
        )}

        {pro && status === 'canceled' && (
          <AccentButton onClick={resume} icon={<Icon name="check" size={18} />}>Resume subscription</AccentButton>
        )}

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
          fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--dim)', lineHeight: 1.5, textAlign: 'center', padding: '2px 4px' }}>
          <PlayMark size={14} />
          <span>Subscriptions are managed through Google Play. This is a demo — no real charges occur.</span>
        </div>
      </div>
    </SheetShell>
  );
}

function Row({ label, value, top }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', borderTop: top ? '1px solid var(--border)' : 'none' }}>
      <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--muted)' }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 700, color: 'var(--text)', textAlign: 'right' }}>{value}</span>
    </div>
  );
}

const ghostBtn = { width: '100%', padding: '14px 18px', borderRadius: 'var(--radius-sm)', cursor: 'pointer',
  background: 'var(--surface-2)', border: '1px solid var(--border)', color: 'var(--text)',
  fontFamily: 'var(--font-body)', fontSize: 14.5, fontWeight: 700 };
const dangerBtn = { flex: 1, padding: '12px 16px', borderRadius: 'var(--radius-sm)', cursor: 'pointer',
  background: 'transparent', border: '1px solid var(--danger)', color: 'var(--danger)',
  fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700 };

// ── Profile card surfaced on the Profile screen ──────────────
function ProCard({ sub, onOpen }) {
  const c = useTheme();
  const pro = isPro(sub);
  return (
    <Card onClick={onOpen} pad={16} style={{ display: 'flex', alignItems: 'center', gap: 14,
      borderColor: pro ? c.accent + '55' : 'var(--border)',
      background: pro ? `radial-gradient(130% 130% at 100% 0%, ${c.accent}1c, transparent 62%), var(--surface)` : 'var(--surface)' }}>
      <span style={{ width: 42, height: 42, borderRadius: 11, flexShrink: 0, background: pro ? c.accent : 'var(--surface-2)',
        color: pro ? c.accentInk : c.accent, border: pro ? 'none' : '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name="bolt" size={22} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, letterSpacing: 0.4, color: 'var(--text)' }}>
          PSYFIT PRO
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, color: 'var(--muted)', marginTop: 2 }}>
          {subStatusLine(sub)}
        </div>
      </div>
      {!pro
        ? <span style={{ flexShrink: 0, fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, letterSpacing: 0.3,
            background: c.accent, color: c.accentInk, borderRadius: 999, padding: '7px 14px' }}>Upgrade</span>
        : <span style={{ color: 'var(--dim)' }}><Icon name="chevR" size={18} /></span>}
    </Card>
  );
}

// ─────────────────────────────────────────────────────────────
// CONGRATS SCREEN — shown after finishing a workout for free users.
// Celebrates the session, then softly presents Pro benefits.
// Props: summary { title, exerciseCount, sets, volume }, onSubscribe, onDismiss
// ─────────────────────────────────────────────────────────────
function CongratsScreen({ summary, onSubscribe, onDismiss }) {
  const c = useTheme();
  const s = summary || {};
  const hasVolume = s.volume && s.volume > 0;

  const stats = [
    s.exerciseCount > 0 && { value: s.exerciseCount, label: s.exerciseCount === 1 ? 'exercise' : 'exercises' },
    s.sets > 0          && { value: s.sets,           label: s.sets === 1 ? 'set' : 'sets' },
    hasVolume           && { value: s.volume.toLocaleString(), label: 'lbs total' },
  ].filter(Boolean);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>

      {/* ── Hero celebrate block ── */}
      <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--radius)',
        background: `radial-gradient(120% 120% at 80% 10%, ${c.accent}44, transparent 55%), var(--surface-2)`,
        border: `1px solid ${c.accent}55`, padding: '28px 22px 24px', marginBottom: 16 }}>

        {/* big checkmark */}
        <div style={{ width: 60, height: 60, borderRadius: 18, background: c.accent,
          display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
          <Icon name="check" size={32} stroke={3} style={{ color: c.accentInk }} />
        </div>

        <div style={{ fontFamily: 'var(--font-display)', fontSize: 38, lineHeight: 1,
          letterSpacing: 0.5, color: 'var(--text)', marginBottom: 8 }}>
          WORKOUT<br />DONE.
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600,
          color: 'var(--muted)', marginBottom: stats.length > 0 ? 22 : 0, lineHeight: 1.4 }}>
          {s.title || 'Great session'} · saved to your history.
        </div>

        {/* stat pills */}
        {stats.length > 0 && (
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {stats.map((st, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'baseline', gap: 5,
                background: 'var(--surface-3)', border: '1px solid var(--border)',
                borderRadius: 999, padding: '7px 14px' }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 22,
                  letterSpacing: 0.3, color: 'var(--text)', lineHeight: 1 }}>{st.value}</span>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 12,
                  fontWeight: 700, color: 'var(--muted)' }}>{st.label}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ── Pro upsell ── */}
      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700,
        letterSpacing: 1.2, textTransform: 'uppercase', color: 'var(--muted)',
        marginBottom: 10, paddingLeft: 2 }}>
        Take it further with Pro
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 20 }}>
        {PRO_BENEFITS.map((b, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12,
            padding: '13px 14px', borderRadius: 'var(--radius-sm)',
            background: 'var(--surface-2)', border: '1px solid var(--border)' }}>
            <span style={{ width: 30, height: 30, borderRadius: 8, flexShrink: 0,
              background: `${c.accent}22`, color: c.accent,
              display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={b.icon} size={16} />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700,
                fontSize: 14, color: 'var(--text)' }}>{b.label}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12,
                color: 'var(--muted)', marginTop: 2, lineHeight: 1.4 }}>{b.sub}</div>
            </div>
          </div>
        ))}
      </div>

      {/* ── CTAs ── */}
      <AccentButton onClick={onSubscribe} icon={<Icon name="bolt" size={18} />}>
        Go Pro · {PRO_PRICE}/{PRO_PERIOD}
      </AccentButton>

      <button onClick={onDismiss} style={{ marginTop: 12, width: '100%', padding: '14px 18px',
        borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)',
        background: 'transparent', color: 'var(--muted)', cursor: 'pointer',
        fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600 }}>
        Maybe later
      </button>

      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--dim)',
        textAlign: 'center', marginTop: 12, lineHeight: 1.5 }}>
        {PRO_PRICE}/{PRO_PERIOD} · cancel anytime
      </div>
    </div>
  );
}

Object.assign(window, {
  SUB_DEFAULTS, PRO_PRICE, PRO_PERIOD, TRIAL_DAYS, PRO_PRODUCT,
  isPro, makeTrial, makeActive, subDaysLeft, subStatusLine, fmtDate,
  PaywallSheet, SubscriptionSheet, ProCard, PlayMark, CongratsScreen,
});
