// screen-upgrade.jsx — "Lasting Record" $99/year upgrade page
// Shows tier comparison, calls /api/stripe-checkout, redirects to Stripe Checkout.

function UpgradeScreen({ onNav }) {
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [email, setEmail] = React.useState('');
  const [handle, setHandle] = React.useState('');

  // Load handle from any locally-stored player record
  React.useEffect(() => {
    try {
      const players = JSON.parse(localStorage.getItem('pj_my_handle_v1') || 'null');
      if (typeof players === 'string') setHandle(players);
    } catch {}
  }, []);

  const upgrade = async () => {
    setErr(null);
    setLoading(true);
    try {
      const device_id = (window.pjDeviceId && window.pjDeviceId()) || localStorage.getItem('pj_device_id');
      if (!device_id) throw new Error('No device ID — refresh and try again');
      const resp = await fetch('/api/stripe-checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device_id,
          handle: handle || undefined,
          email: email || undefined,
        }),
      });
      const data = await resp.json();
      if (!resp.ok || !data.url) {
        throw new Error(data.detail || data.error || 'Checkout failed');
      }
      window.location.href = data.url; // redirect to Stripe Checkout
    } catch (e) {
      setErr(String(e.message || e));
      setLoading(false);
    }
  };

  // Tier comparison rows
  const rows = [
    ['Locked equity swaps', '✓', '✓'],
    ['QR double-confirm', '✓', '✓'],
    ['Browse marketplace', '✓', '✓'],
    ['Bankroll planner', '✓', '✓'],
    ['Record kept', '30 days', 'Forever'],
    ['Multi-channel confirmation (SMS / Email / WhatsApp)', '—', '✓'],
    ['PDF court-ready receipt', '—', '✓'],
    ['Reputation badge', 'Standard', 'Verified'],
    ['Auto-collections (escalating reminders to non-payers)', '1 reminder', 'Full escalation ladder'],
    ['Public unpaid-wall protection', '—', '✓'],
    ['Block list', '—', '✓'],
    ['Annual export of all swaps (CSV)', '—', '✓'],
  ];

  return (
    <div className="page" style={{padding: '40px 20px 120px', maxWidth: 720, margin: '0 auto'}}>
      <div style={{textAlign: 'center', marginBottom: 32}}>
        <div className="mono green" style={{marginBottom: 12, letterSpacing: '0.22em'}}>◆ LASTING RECORD</div>
        <h1 style={{
          fontFamily: 'var(--font-display)', fontWeight: 800,
          fontSize: 'clamp(40px, 8vw, 64px)', lineHeight: 1.02, letterSpacing: '-0.035em',
          margin: 0, color: 'var(--text)', textWrap: 'balance'
        }}>
          Never get <span style={{color: 'var(--green)', textShadow: '0 0 24px var(--green-glow)'}}>Jamied</span> twice.
        </h1>
        <p className="text-2" style={{marginTop: 18, fontSize: 17, lineHeight: 1.5, maxWidth: 480, marginLeft: 'auto', marginRight: 'auto'}}>
          Permanent record. Auto-collections. Court-ready PDF. $99 a year. No subscription games — one annual charge, full year of coverage.
        </p>
      </div>

      <div className="card-glow" style={{padding: 0, overflow: 'hidden', marginBottom: 24}}>
        <table style={{width: '100%', borderCollapse: 'collapse'}}>
          <thead>
            <tr style={{background: 'rgba(0,0,0,0.3)'}}>
              <th style={{textAlign: 'left', padding: '14px 16px', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em', color: 'var(--text-3)', textTransform: 'uppercase'}}>Feature</th>
              <th style={{textAlign: 'center', padding: '14px 16px', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em', color: 'var(--text-3)', textTransform: 'uppercase'}}>Free</th>
              <th style={{textAlign: 'center', padding: '14px 16px', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em', color: 'var(--green)', textTransform: 'uppercase', textShadow: '0 0 10px var(--green-glow)'}}>Lasting Record</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i} style={{borderTop: '1px solid rgba(255,255,255,0.05)'}}>
                <td style={{padding: '12px 16px', fontSize: 14, color: 'var(--text-2)'}}>{r[0]}</td>
                <td style={{padding: '12px 16px', fontSize: 13, color: 'var(--text-3)', textAlign: 'center'}}>{r[1]}</td>
                <td style={{padding: '12px 16px', fontSize: 13, color: 'var(--green)', textAlign: 'center', fontWeight: 600}}>{r[2]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="card" style={{padding: 24, marginBottom: 16}}>
        <label className="field-label">Your handle (optional, helps us match your existing swaps)</label>
        <input className="input" type="text" placeholder="@yourhandle" value={handle} onChange={(e) => setHandle(e.target.value)} />
        <div style={{height: 12}} />
        <label className="field-label">Email (for receipt — Stripe will ask if you skip)</label>
        <input className="input" type="email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} />
      </div>

      {err && (
        <div style={{
          padding: '12px 16px', borderRadius: 10, border: '1px solid rgba(255,77,94,0.4)',
          background: 'var(--red-soft)', color: '#ff8a9c', fontFamily: 'var(--font-mono)', fontSize: 12,
          marginBottom: 12, letterSpacing: '0.04em'
        }}>{err}</div>
      )}

      <button
        onClick={upgrade}
        disabled={loading}
        style={{
          all: 'unset', cursor: loading ? 'wait' : 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          width: '100%', padding: '22px 24px', borderRadius: 14,
          color: '#0B0E11', textAlign: 'center', userSelect: 'none', fontWeight: 700,
          fontFamily: 'var(--font-display)', fontSize: 18, letterSpacing: '-0.015em',
          background: 'linear-gradient(180deg, #E8ECEF 0%, #B8BFC8 55%, #8A929C 100%)',
          boxShadow: [
            'inset 0 1px 0 rgba(255,255,255,0.65)',
            'inset 0 -1px 0 rgba(0,0,0,0.28)',
            '0 0 0 1px #2A323C',
            '0 0 28px rgba(0,224,138,0.40)',
            '0 0 70px rgba(0,224,138,0.18)',
            '0 10px 28px rgba(0,0,0,0.55)'
          ].join(', '),
          opacity: loading ? 0.6 : 1,
          transition: 'opacity 200ms'
        }}>
        {loading ? 'Opening Stripe…' : 'Upgrade to Lasting Record — $99/year'}
      </button>

      <div style={{textAlign: 'center', marginTop: 18, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: 'var(--text-mute)', textTransform: 'uppercase'}}>
        Secure checkout · Stripe · Cancel anytime
      </div>

      <div style={{textAlign: 'center', marginTop: 32}}>
        <button onClick={() => onNav('/')} className="btn btn-secondary">Back home</button>
      </div>
    </div>
  );
}

window.UpgradeScreen = UpgradeScreen;
