// paywall.jsx — Login + Subscribe modal for full access
function Paywall() {
  // Open by default for first-time visitors. localStorage gates re-display.
  const initiallyOpen = window.localStorage.getItem('wcl_dismissed_paywall') !== '1' &&
                        window.localStorage.getItem('wcl_subscribed') !== '1';
  const [open, setOpen] = React.useState(initiallyOpen);
  const [tab, setTab] = React.useState('subscribe'); // 'subscribe' | 'signin'
  const [plan, setPlan] = React.useState('pro');
  const [submitting, setSubmitting] = React.useState(false);
  const [signedIn, setSignedIn] = React.useState(window.localStorage.getItem('wcl_signed_in') === '1');

  // Re-open helper: floating "Get full access" button when closed and not subscribed.
  function dismiss() {
    setOpen(false);
    window.localStorage.setItem('wcl_dismissed_paywall', '1');
  }
  function subscribe() {
    setSubmitting(true);
    setTimeout(() => {
      window.localStorage.setItem('wcl_subscribed', '1');
      window.localStorage.setItem('wcl_signed_in', '1');
      setSignedIn(true);
      setSubmitting(false);
      setOpen(false);
    }, 700);
  }
  function signin() {
    setSubmitting(true);
    setTimeout(() => {
      window.localStorage.setItem('wcl_signed_in', '1');
      setSignedIn(true);
      setSubmitting(false);
      setOpen(false);
    }, 500);
  }

  const subscribed = window.localStorage.getItem('wcl_subscribed') === '1';

  // Allow other parts of the app to open the paywall
  React.useEffect(() => {
    function onOpen() { setOpen(true); }
    window.addEventListener('wcl-open-paywall', onOpen);
    return () => window.removeEventListener('wcl-open-paywall', onOpen);
  }, []);

  return (
    <>
      {/* Trigger button — visible when closed and not subscribed */}
      {!open && !subscribed && (
        <button onClick={() => setOpen(true)} style={{
          position: 'fixed', bottom: 20, right: 20, zIndex: 90,
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '10px 16px',
          background: 'var(--trophy)',
          color: '#1a1505',
          fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
          border: 'none',
          borderRadius: 999,
          cursor: 'pointer',
          boxShadow: 'var(--shadow-md)',
        }}>
          <I.Crown size={14} /> Get full access · free 7 days
        </button>
      )}

      {!open ? null : (
        <div onClick={dismiss} style={{
          position: 'fixed', inset: 0, zIndex: 100,
          background: 'rgba(0,0,0,0.6)',
          backdropFilter: 'blur(8px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 24,
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            width: 'min(880px, 100%)',
            maxHeight: '92vh',
            overflowY: 'auto',
            background: 'var(--card)',
            border: '1px solid var(--border)',
            borderRadius: 'var(--radius-xl)',
            boxShadow: 'var(--shadow-lg)',
            display: 'grid',
            gridTemplateColumns: '1.1fr 1fr',
            position: 'relative',
          }}>
            <button onClick={dismiss} aria-label="close" style={{
              position: 'absolute', top: 14, right: 14, zIndex: 1,
              width: 32, height: 32, borderRadius: 8,
              background: 'rgba(0,0,0,0.3)', backdropFilter: 'blur(8px)',
              border: '1px solid var(--border)',
              color: 'var(--foreground)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer',
            }}><I.X size={14} /></button>

            {/* Left: marketing */}
            <div style={{
              padding: '36px 32px',
              background: `
                radial-gradient(ellipse 80% 60% at 30% 0%, color-mix(in oklch, var(--brand) 22%, transparent), transparent 60%),
                linear-gradient(180deg, var(--surface), var(--card))`,
              borderRight: '1px solid var(--border)',
              borderRadius: 'var(--radius-xl) 0 0 var(--radius-xl)',
            }}>
              <SoccerBall size={42} />
              <h2 style={{ margin: '18px 0 6px', fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
                Every World Cup,<br/>everywhere, live.
              </h2>
              <p className="subtle" style={{ fontSize: 13, lineHeight: 1.6, margin: '0 0 22px', textWrap: 'pretty' }}>
                Sign in to play pick\u2019em and follow your favourites. Go Pro to unlock the forecast model, all-time stats and live match data without rate limits.
              </p>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13 }}>
                {[
                  ['Live xG, win probability and timelines for every match', true],
                  ['22 World Cups · all-time stats, scorers and finals', true],
                  ['Forecast model · trophy + stage odds, edge vs market', 'pro'],
                  ['Daily ranking challenge · streaks + global leaderboard', true],
                  ['Pick\u2019em across the bracket · scored vs the model', 'pro'],
                  ['No rate limits on API-Football live polling', 'pro'],
                  ['Watchlists · early push alerts · ad-free', 'pro'],
                ].map(([t, badge], i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                    <I.Check size={14} style={{ color: badge === 'pro' ? 'var(--trophy)' : 'var(--success)', marginTop: 2, flexShrink: 0 }} />
                    <span style={{ flex: 1, color: 'var(--foreground-subtle)' }}>{t}</span>
                    {badge === 'pro' && <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', color: 'var(--trophy)', textTransform: 'uppercase', flexShrink: 0 }}>Pro</span>}
                  </div>
                ))}
              </div>

              <div style={{ marginTop: 24, padding: 12, background: 'var(--muted)', borderRadius: 'var(--radius-md)', display: 'flex', alignItems: 'center', gap: 10 }}>
                <I.Users size={14} style={{ color: 'var(--foreground-muted)' }} />
                <span className="subtle" style={{ fontSize: 12 }}>Joined by <span className="strong">182,400</span> fans this tournament.</span>
              </div>
            </div>

            {/* Right: forms */}
            <div style={{ padding: '36px 32px' }}>
              <div className="tabs-row" style={{ marginBottom: 22 }}>
                <button className={'tab-btn' + (tab === 'subscribe' ? ' active' : '')} onClick={() => setTab('subscribe')}>Subscribe</button>
                <button className={'tab-btn' + (tab === 'signin' ? ' active' : '')} onClick={() => setTab('signin')}>Sign in</button>
              </div>

              {tab === 'subscribe' ? (
                <>
                  <h3 style={{ margin: '0 0 4px', fontSize: 18, fontWeight: 600 }}>Choose a plan</h3>
                  <p className="subtle" style={{ fontSize: 12, margin: '0 0 18px' }}>7-day free trial · cancel any time.</p>

                  <div style={{ display: 'grid', gap: 8, marginBottom: 16 }}>
                    {[
                      { id: 'free',     name: 'Free',      price: '$0',     sub: 'forever', features: 'Live scores · history · daily challenge' },
                      { id: 'pro',      name: 'Pro',       price: '$4.99',  sub: '/month',  features: 'Forecast model · pick\u2019em · no ads', badge: 'Most popular' },
                      { id: 'pro-year', name: 'Pro Annual',price: '$39',    sub: '/year',   features: 'Save 35% · everything in Pro' },
                    ].map(p => {
                      const active = plan === p.id;
                      return (
                        <button key={p.id} onClick={() => setPlan(p.id)} style={{
                          display: 'grid',
                          gridTemplateColumns: 'auto 1fr auto',
                          alignItems: 'center', gap: 14,
                          padding: '14px 16px',
                          background: active ? 'color-mix(in oklch, var(--brand) 12%, var(--surface))' : 'var(--surface)',
                          border: '1px solid ' + (active ? 'var(--brand)' : 'var(--border)'),
                          borderRadius: 'var(--radius-md)',
                          cursor: 'pointer',
                          textAlign: 'left',
                          color: 'inherit',
                          fontFamily: 'inherit',
                          position: 'relative',
                        }}>
                          <span style={{
                            width: 16, height: 16, borderRadius: 999,
                            border: '2px solid ' + (active ? 'var(--brand)' : 'var(--border-hover)'),
                            background: active ? 'var(--brand)' : 'transparent',
                            boxShadow: active ? 'inset 0 0 0 3px var(--card)' : 'none',
                          }} />
                          <span>
                            <div className="strong" style={{ fontSize: 14, fontWeight: 600 }}>
                              {p.name}
                              {p.badge && <span style={{ marginLeft: 8, padding: '2px 8px', background: 'color-mix(in oklch, var(--trophy) 22%, transparent)', color: 'var(--trophy)', borderRadius: 999, fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{p.badge}</span>}
                            </div>
                            <div className="subtle" style={{ fontSize: 11, marginTop: 3 }}>{p.features}</div>
                          </span>
                          <span style={{ textAlign: 'right' }}>
                            <div className="strong" style={{ fontSize: 16, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{p.price}</div>
                            <div className="subtle" style={{ fontSize: 10 }}>{p.sub}</div>
                          </span>
                        </button>
                      );
                    })}
                  </div>

                  <div style={{ marginBottom: 12 }}>
                    <label className="label">Email</label>
                    <input className="input" type="email" placeholder="you@email.com" />
                  </div>

                  <button className="btn btn-primary" style={{ width: '100%', height: 40 }} onClick={subscribe} disabled={submitting}>
                    {submitting ? 'Creating account…' :
                     plan === 'free'      ? 'Continue with Free →' :
                     plan === 'pro'       ? 'Start 7-day Pro trial →' :
                                            'Get Pro Annual · $39 →'}
                  </button>

                  <div style={{ position: 'relative', textAlign: 'center', margin: '16px 0', fontSize: 11, color: 'var(--foreground-muted)' }}>
                    <span style={{ background: 'var(--card)', padding: '0 10px', position: 'relative' }}>or continue with</span>
                    <div style={{ position: 'absolute', top: '50%', left: 0, right: 0, height: 1, background: 'var(--border)', zIndex: -1 }} />
                  </div>

                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
                    {['Google','Apple','GitHub'].map(s => (
                      <button key={s} className="btn btn-secondary btn-sm" style={{ width: '100%' }}>{s}</button>
                    ))}
                  </div>

                  <p className="subtle" style={{ fontSize: 10, marginTop: 14, textAlign: 'center', lineHeight: 1.5 }}>
                    By continuing you agree to the Terms & Privacy Policy. Cancel any time — your trial doesn\u2019t auto-renew until day 7.
                  </p>
                </>
              ) : (
                <>
                  <h3 style={{ margin: '0 0 4px', fontSize: 18, fontWeight: 600 }}>Welcome back</h3>
                  <p className="subtle" style={{ fontSize: 12, margin: '0 0 22px' }}>Sign in to pick up your picks, streak and favourites.</p>

                  <div style={{ marginBottom: 14 }}>
                    <label className="label">Email</label>
                    <input className="input" type="email" placeholder="you@email.com" defaultValue="" />
                  </div>
                  <div style={{ marginBottom: 18 }}>
                    <label className="label" style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span>Password</span>
                      <a className="link" style={{ fontSize: 11 }}>Forgot?</a>
                    </label>
                    <input className="input" type="password" placeholder="••••••••" />
                  </div>
                  <button className="btn btn-primary" style={{ width: '100%', height: 40 }} onClick={signin} disabled={submitting}>
                    {submitting ? 'Signing in…' : 'Sign in'}
                  </button>

                  <div style={{ position: 'relative', textAlign: 'center', margin: '16px 0', fontSize: 11, color: 'var(--foreground-muted)' }}>
                    <span style={{ background: 'var(--card)', padding: '0 10px', position: 'relative' }}>or</span>
                    <div style={{ position: 'absolute', top: '50%', left: 0, right: 0, height: 1, background: 'var(--border)', zIndex: -1 }} />
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
                    {['Google','Apple','GitHub'].map(s => (
                      <button key={s} className="btn btn-secondary btn-sm" style={{ width: '100%' }}>{s}</button>
                    ))}
                  </div>
                  <p className="subtle" style={{ fontSize: 11, textAlign: 'center', marginTop: 18 }}>
                    No account? <a className="link strong" onClick={() => setTab('subscribe')}>Start free →</a>
                  </p>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

// Local animation keyframes (unused after the open animation was removed for
// reliability — the dialog now pops in instantly).

Object.assign(window, { Paywall });
