/* Hero with onboarding picker + phone capture — production wired */

function MLNav() {
  const t = window.mlTokens;
  const isMobile = window.useMobile();
  return (
    <header style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding:'20px 0', position:'relative', zIndex: 3,
    }}>
      <a href="/" style={{textDecoration:'none'}}>
        <window.MLLogo/>
      </a>
      {!isMobile && (
        <nav style={{display:'flex', gap: 32}}>
          <a href="#about" style={{fontSize:14, color:t.ink, fontWeight:500, textDecoration:'none', cursor:'pointer'}}>About</a>
          <a href="#how-it-works" style={{fontSize:14, color:t.ink, fontWeight:500, textDecoration:'none', cursor:'pointer'}}>How it works</a>
          <a href="#listen" style={{fontSize:14, color:t.ink, fontWeight:500, textDecoration:'none', cursor:'pointer'}}>Listen</a>
          <a href="#pricing" style={{fontSize:14, color:t.ink, fontWeight:500, textDecoration:'none', cursor:'pointer'}}>Pricing</a>
        </nav>
      )}
      <a href="#signup" onClick={(e)=>{e.preventDefault(); const el=document.getElementById('signup'); if(el) el.scrollIntoView({behavior:'smooth'});}} style={{
        background: t.ink, color: t.cream,
        padding: isMobile ? '10px 16px' : '12px 22px',
        borderRadius: 999,
        textDecoration:'none', fontSize: isMobile ? 13 : 14, fontWeight: 600, cursor:'pointer',
        minHeight: 44, display:'inline-flex', alignItems:'center',
      }}>Get Harold →</a>
    </header>
  );
}

function MLHero() {
  const t = window.mlTokens;
  const isMobile = window.useMobile();
  const [step, setStep] = React.useState(1); // 1 = segments, 2 = phone/zip, 3 = plan
  const [segments, setSegments] = React.useState(new Set(['world','tech','sports','good']));
  const [phone, setPhone] = React.useState('');
  const [zip, setZip] = React.useState('');
  const [phoneError, setPhoneError] = React.useState('');
  const [submitError, setSubmitError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [pendingCheckoutUrl, setPendingCheckoutUrl] = React.useState('');
  // Referral attribution: a friend opening someone's shared briefing
  // hits "Start 7-Day Free Trial" which links here with ?ref=<shareToken>.
  // Read it once on mount and forward it to /api/subscribe so the new
  // subscriber row gets referral_subscriber_id + share_token_used set.
  const referralShareToken = React.useMemo(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      const ref = p.get('ref');
      return ref && ref.trim() ? ref.trim() : null;
    } catch (e) { return null; }
  }, []);

  const metroForZip = (z) => {
    if (!z || z.length < 3) return 'your metro area';
    const p = z.slice(0,3);
    const MAP = {
      '100':'New York','101':'New York','102':'New York','103':'New York','104':'New York',
      '112':'Brooklyn','113':'Queens',
      '200':'Washington DC','201':'Washington DC','202':'Washington DC',
      '300':'Atlanta','303':'Atlanta',
      '606':'Chicago','604':'Chicago',
      '770':'Houston','772':'Houston',
      '752':'Dallas',
      '800':'Denver','802':'Denver',
      '900':'Los Angeles','902':'Los Angeles','904':'Los Angeles',
      '941':'San Francisco','940':'San Francisco','945':'Oakland',
      '981':'Seattle','980':'Seattle',
      '331':'Miami','330':'Miami',
      '021':'Boston','022':'Boston',
      '191':'Philadelphia','190':'Philadelphia',
      '551':'Minneapolis',
      '631':'St. Louis',
      '972':'Portland',
      '850':'Phoenix',
      '891':'Las Vegas',
      '532':'Milwaukee',
      '432':'Columbus',
      '282':'Charlotte',
      '372':'Nashville',
      '370':'Nashville',
      '787':'Austin',
    };
    return MAP[p] || 'your metro area';
  };
  // 'monthly' | 'annual'. Defaults to annual to nudge visitors toward
  // the higher-LTV plan (and shows them the lower effective per-month
  // price first). Annual saves 25% off:
  //   Premium: $5/mo  -> $45/yr  ($3.75/mo effective)
  //   Basic:   $3.50  -> $31.50/yr ($2.63/mo effective)
  const [billing, setBilling] = React.useState('annual');
  const [plan, setPlan] = React.useState('harold'); // 'basic' | 'harold'

  const toggle = (id) => {
    setSegments(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  // Phone formatting: auto-format as (XXX) XXX-XXXX
  const formatPhone = (val) => {
    const digits = val.replace(/\D/g, '').slice(0, 10);
    if (digits.length <= 3) return digits;
    if (digits.length <= 6) return `(${digits.slice(0,3)}) ${digits.slice(3)}`;
    return `(${digits.slice(0,3)}) ${digits.slice(3,6)}-${digits.slice(6)}`;
  };

  const phoneDigits = phone.replace(/\D/g, '');
  const isPhoneValid = phoneDigits.length === 10;
  const isZipValid = zip.length === 0 || zip.length === 5;

  const SEGS = [
    // CORE (always on for everyone)
    {id:'us',    emoji:'🇺🇸', label:'U.S. News',    desc:'National headlines', core: true},
    {id:'world', emoji:'🌍', label:'World News',    desc:'Conflicts, elections, diplomacy', core: true},
    {id:'good',  emoji:'☀',  label:'Good News',     desc:'Always ends on a high note', core: true},
    {id:'local', emoji:'📍', label:'Local & Weather', desc:'Your city, your forecast', premium: true},
    // PREMIUM selectable
    {id:'politics', emoji:'🏛', label:'Politics',        desc:'Policy, elections, government'},
    {id:'business', emoji:'💼', label:'Business',        desc:'Markets, economy, companies'},
    {id:'tech',     emoji:'💻', label:'Technology',      desc:'AI, startups, gadgets'},
    {id:'science',  emoji:'🔬', label:'Science',         desc:'Research, space, discovery'},
    {id:'health',   emoji:'🩺', label:'Health',          desc:'Medicine, wellness, public health'},
    {id:'climate',  emoji:'🌱', label:'Climate & Environment', desc:'Planet, energy, nature'},
    {id:'sports',   emoji:'⚽', label:'Sports & Entertainment', desc:'Scores, shows, events near you'},
    {id:'freaky',   emoji:'👽', label:'Freaky & Fun', desc:"Paranormal, UAPs & far-out conspiracy theories"},
  ];

  const handleStep2Continue = async () => {
    if (!isPhoneValid) {
      setPhoneError('Please enter a valid 10-digit US phone number.');
      return;
    }
    setPhoneError('');
    // Save lead to DB (non-blocking, non-fatal). Send zip if provided & valid
    // so we capture metro context even if the user abandons before checkout.
    try {
      await fetch('/api/leads', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ phone, zip_code: (zip && zip.length === 5) ? zip : null, referralShareToken }),
      });
    } catch(e) { /* non-fatal */ }
    setStep(3);
  };

  const handleSubmit = async () => {
    setSubmitError('');
    setLoading(true);
    try {
      const tier = plan === 'harold' ? 'premium' : 'basic';
      const billingPeriod = billing === 'annual' ? 'yearly' : 'monthly';
      // Build segment list — filter out core/premium (they're auto-included)
      const optionalSegs = ['politics','business','tech','science','health','climate','sports','freaky'];
      const preferred = optionalSegs.filter(s => segments.has(s));

      const resp = await fetch('/api/subscribe', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
          phone,
          zip_code: zip || null,
          tier,
          billing: billingPeriod,
          preferred_segments: preferred,
          referralShareToken,
        }),
      });
      const data = await resp.json();
      if (!resp.ok || !data.success) {
        setSubmitError(data.error || 'Something went wrong. Please try again.');
        setLoading(false);
        return;
      }
      // Save phone for activation after Stripe redirect
      try { localStorage.setItem('harold_phone', phone); } catch(e) { /* non-fatal */ }
      // Redirect directly to Stripe checkout for all plans
      window.location.href = data.checkout_url;
    } catch (err) {
      setSubmitError('Network error — please check your connection and try again.');
      setLoading(false);
    }
  };

  // Time-of-day greeting using local time
  const todayStr = React.useMemo(() => {
    const d = new Date();
    const h = d.getHours();
    const greeting = h < 12 ? 'Good morning' : h < 17 ? 'Good afternoon' : 'Good evening';
    const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
    const months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    return `${greeting} — it's ${days[d.getDay()]}, ${months[d.getMonth()]} ${d.getDate()}`;
  }, []);

  const coreGridCols = isMobile ? '1fr 1fr' : '1fr 1fr 1fr 1fr';
  const segGridCols = isMobile ? '1fr 1fr' : '1fr 1fr 1fr';

  return (
    <section id="signup" style={{
      position:'relative', zIndex: 2,
      padding: isMobile ? '32px 0 48px' : '48px 0 72px',
      textAlign:'center',
      maxWidth: 980,
      margin:'0 auto',
    }}>
      <window.MLBadge>{todayStr}</window.MLBadge>

      <h1 style={{
        marginTop: 28,
        fontFamily: t.sans,
        fontSize: isMobile ? 42 : 80,
        lineHeight: 1.05,
        letterSpacing: '-0.04em', fontWeight: 700, color: t.ink,
      }}>
        <span style={{fontWeight:400, fontStyle:'italic', color: t.ink60}}>Skip the scroll.</span><br/>
        Spin-free news <span style={{color: t.coral}}>in your headphones.</span><br/>
        <span style={{fontWeight:400, fontStyle:'italic', color: t.ink60}}>No ads.</span>
      </h1>

      <p style={{
        marginTop: 28, fontSize: isMobile ? 16 : 19, lineHeight: 1.55,
        color: t.ink60, maxWidth: 680,
        marginLeft:'auto', marginRight:'auto',
      }}>
        Harold is your personal AI news anchor that reads hundreds of news sources 24/7, and texts
        you a short, balanced, upbeat <strong style={{color: t.ink}}>audio brief 1–2×/day</strong>.
        <br/>
        <span style={{fontStyle:'italic'}}>No doom-scrolling. No ads. No spin. Just your custom headlines.</span>
      </p>

      {/* ONBOARDING + PHONE CARD */}
      <div style={{
        marginTop: 44,
        background: t.paper,
        borderRadius: 28,
        padding: isMobile ? 4 : 8,
        border:'1px solid rgba(42,24,16,0.08)',
        boxShadow: t.card,
        maxWidth: 780,
        marginLeft:'auto', marginRight:'auto',
        textAlign:'left',
      }}>
        {/* step header */}
        <div style={{
          display:'flex', alignItems:'center', justifyContent:'space-between',
          padding: isMobile ? '12px 14px 4px' : '14px 20px 4px',
          overflow:'hidden',
        }}>
          <div style={{display:'flex', gap: isMobile ? 4 : 8, alignItems:'center', flex:1, minWidth:0}}>
            <span style={{
              width: 24, height:24, borderRadius:999, flexShrink:0,
              background: step===1 ? t.coral : t.ink,
              color: t.cream, display:'inline-flex', alignItems:'center', justifyContent:'center',
              fontSize: 12, fontWeight: 700,
            }}>1</span>
            {!isMobile && <span style={{fontSize: 13, fontWeight: 600, color: t.ink, whiteSpace:'nowrap'}}>Segments</span>}
            <span style={{flex:1, height:1, background:'rgba(42,24,16,0.12)', minWidth: 8, margin:`0 ${isMobile?4:8}px`}}/>
            <span style={{
              width: 24, height:24, borderRadius:999, flexShrink:0,
              background: step===2 ? t.coral : step>2 ? t.ink : 'rgba(42,24,16,0.1)',
              color: step>=2 ? t.cream : t.ink40,
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              fontSize: 12, fontWeight: 700,
            }}>2</span>
            {!isMobile && <span style={{fontSize: 13, fontWeight: 600, color: step>=2 ? t.ink : t.ink40, whiteSpace:'nowrap'}}>Phone &amp; zip</span>}
            <span style={{flex:1, height:1, background:'rgba(42,24,16,0.12)', minWidth: 8, margin:`0 ${isMobile?4:8}px`}}/>
            <span style={{
              width: 24, height:24, borderRadius:999, flexShrink:0,
              background: step===3 ? t.coral : 'rgba(42,24,16,0.1)',
              color: step===3 ? t.cream : t.ink40,
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              fontSize: 12, fontWeight: 700,
            }}>3</span>
            {!isMobile && <span style={{fontSize: 13, fontWeight: 600, color: step===3 ? t.ink : t.ink40, whiteSpace:'nowrap'}}>Pick your plan</span>}
          </div>
          {!isMobile && <span style={{
            fontFamily: t.mono, fontSize: 10, letterSpacing:'0.15em',
            color: t.ink40, marginLeft: 12, whiteSpace:'nowrap',
          }}>{step===3 ? 'ALMOST THERE' : '30 SECONDS'}</span>}
        </div>

        {step === 1 && (
          <div style={{padding: isMobile ? '10px 14px 16px' : '12px 20px 20px'}}>
            {/* CORE label */}
            <div style={{
              display:'flex', alignItems:'center', gap: 10, margin:'4px 0 10px',
            }}>
              <span style={{
                fontFamily: t.mono, fontSize: 10, letterSpacing:'0.2em',
                color: t.ink40, fontWeight: 600, whiteSpace:'nowrap',
              }}>CORE NEWS · THE BASICS</span>
              <span style={{flex:1, height:1, background:'rgba(42,24,16,0.08)'}}/>
            </div>
            <div style={{
              display:'grid', gridTemplateColumns: coreGridCols, gap: isMobile ? 8 : 10,
            }}>
              {SEGS.filter(s=>s.core||s.premium).map(s => {
                return (
                  <div key={s.id} style={{
                    display:'flex', flexDirection:'column',
                    alignItems:'flex-start', textAlign:'left', gap: 4,
                    padding: isMobile ? '10px 10px 8px' : '14px 14px 12px', borderRadius: 16,
                    border: '2px solid rgba(42,24,16,0.08)',
                    background: s.premium ? 'rgba(255,243,230,0.5)' : '#FFF3E6',
                    position:'relative',
                    opacity: s.premium ? 0.85 : 1,
                  }}>
                    <div style={{display:'flex', alignItems:'center', gap:8, width:'100%'}}>
                      <span style={{fontSize: 18}}>{s.emoji}</span>
                      <span style={{flex:1, fontSize: isMobile ? 12 : 13, fontWeight: 700, color: t.ink, lineHeight: 1.2}}>{s.label}</span>
                    </div>
                    <span style={{fontSize: 10, color: t.ink40}}>{s.desc}</span>
                    <span style={{
                      position:'absolute', top:6, right:6,
                      fontFamily: t.mono, fontSize: isMobile ? 7 : 8, letterSpacing:'0.1em',
                      color: s.premium ? t.coral : t.ink40, fontWeight: 700,
                    }}>{s.premium ? 'HAROLD ONLY' : 'ALWAYS ON'}</span>
                  </div>
                );
              })}
            </div>

            {/* PREMIUM label */}
            <div style={{display:'flex', alignItems:'center', gap: 10, margin:'16px 0 10px'}}>
              <span style={{
                fontFamily: t.mono, fontSize: 10, letterSpacing:'0.2em',
                color: t.coral, fontWeight: 600, whiteSpace:'nowrap',
              }}>CHOOSE YOUR SEGMENTS</span>
              <span style={{flex:1, height:1, background:'rgba(42,24,16,0.08)'}}/>
              {!isMobile && <span style={{fontSize: 11, color: t.ink40, fontStyle:'italic', whiteSpace:'nowrap'}}>
                As many or few as you like — change anytime
              </span>}
            </div>
            <div style={{
              display:'grid', gridTemplateColumns: segGridCols, gap: isMobile ? 8 : 10,
            }}>
              {SEGS.filter(s=>!s.core && !s.premium).map(s => {
                const on = segments.has(s.id);
                return (
                  <button key={s.id}
                    onClick={()=>toggle(s.id)}
                    style={{
                      display:'flex', flexDirection:'column',
                      alignItems:'flex-start', textAlign:'left', gap: 4,
                      padding: isMobile ? '10px 10px 8px' : '14px 14px 12px', borderRadius: 16,
                      border: on ? `2px solid ${t.coral}` : '2px solid rgba(42,24,16,0.08)',
                      background: on ? '#FFF3E6' : '#fff',
                      cursor:'pointer', transition:'all 0.12s', position:'relative',
                      fontFamily: t.sans,
                      minHeight: 44,
                    }}>
                    <div style={{display:'flex', alignItems:'center', gap:8, width:'100%'}}>
                      <span style={{fontSize: 18}}>{s.emoji}</span>
                      <span style={{flex:1, fontSize: isMobile ? 12 : 13, fontWeight: 700, color: t.ink, lineHeight: 1.2}}>{s.label}</span>
                      {on && (
                        <span style={{
                          width: 18, height:18, borderRadius:999, background: t.coral,
                          color:'#fff', display:'inline-flex', alignItems:'center', justifyContent:'center',
                          flexShrink:0,
                        }}>
                          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>
                        </span>
                      )}
                    </div>
                    <span style={{fontSize: 10, color: t.ink40}}>{s.desc}</span>
                  </button>
                );
              })}
            </div>

            <button
              onClick={()=>setStep(2)}
              style={{
                marginTop: 14, width:'100%',
                background: t.coral, color: t.cream,
                border:'none', padding:'16px', borderRadius: 14,
                fontSize: 15, fontWeight: 700, cursor:'pointer',
                boxShadow: t.btn, fontFamily: t.sans,
                display:'inline-flex', alignItems:'center', justifyContent:'center', gap: 10,
                minHeight: 44,
              }}>
              Continue →
            </button>
          </div>
        )}

        {step === 2 && (
          <div style={{padding: isMobile ? '10px 14px 16px' : '12px 20px 20px'}}>
            <div style={{
              padding:'12px 14px', borderRadius: 14,
              background:'#FFF3E6', marginBottom: 14,
              display:'flex', alignItems:'center', gap: 10,
            }}>
              <button onClick={()=>setStep(1)} style={{
                width: 36, height: 36, borderRadius: 999, border:'none',
                background: t.paper, cursor:'pointer', flexShrink:0,
                display:'flex', alignItems:'center', justifyContent:'center',
                minHeight: 44, minWidth: 36,
              }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#2A1810" strokeWidth="2.5" strokeLinecap="round"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
              </button>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize: 13, fontWeight: 600, color: t.ink, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>
                  {[...segments].map(id => { const s = SEGS.find(x=>x.id===id); return s ? s.label : ''; }).filter(Boolean).join(' · ')}
                </div>
                <div style={{fontSize: 11, color: t.ink40, marginTop: 2, fontFamily: t.mono, letterSpacing:'0.06em'}}>
                  {segments.size} SEGMENTS · ~5 MIN BRIEFING
                </div>
              </div>
            </div>
            <form onSubmit={(e)=>e.preventDefault()}>
              <div style={{display:'flex', flexDirection: isMobile ? 'column' : 'row', gap: 10, alignItems:'stretch'}}>
                <div style={{
                  flex: 1.6, display:'flex', alignItems:'center',
                  background: '#fff', borderRadius: 14, paddingLeft: 14,
                  border: phoneError ? '1.5px solid #FF5A2D' : '1.5px solid rgba(42,24,16,0.12)',
                  minHeight: 54,
                }}>
                  <span style={{fontSize: 14, color: t.ink60, paddingRight: 10, borderRight:'1px solid rgba(42,24,16,0.12)', marginRight: 10, fontWeight: 500, whiteSpace:'nowrap'}}>🇺🇸 +1</span>
                  <input
                    autoFocus
                    value={phone}
                    onChange={(e)=>{setPhone(formatPhone(e.target.value)); setPhoneError('');}}
                    style={{
                      flex:1, border:'none', outline:'none', background:'transparent',
                      padding:'16px 10px', fontSize: 16, color: t.ink, fontFamily: 'inherit',
                      width: '100%',
                    }}
                    placeholder="(555) 123-4567"
                    type="tel"
                    inputMode="tel"
                  />
                </div>
                <div style={{
                  flex: 1, display:'flex', alignItems:'center',
                  background: '#fff', borderRadius: 14,
                  border:`1.5px solid ${zip.length > 0 && !isZipValid ? '#FF5A2D' : 'rgba(42,24,16,0.12)'}`,
                  minHeight: 54,
                }}>
                  <input
                    value={zip}
                    onChange={(e)=>setZip(e.target.value.replace(/\D/g,'').slice(0,5))}
                    inputMode="numeric"
                    style={{
                      flex:1, border:'none', outline:'none', background:'transparent',
                      padding:'16px 14px', fontSize: 16, color: t.ink, fontFamily: 'inherit',
                      width: '100%', letterSpacing: '0.05em',
                    }}
                    placeholder="ZIP code (optional)"
                  />
                </div>
              </div>

              {phoneError && (
                <div style={{marginTop: 6, fontSize: 12, color: t.coral, paddingLeft: 4}}>{phoneError}</div>
              )}
              {zip.length > 0 && !isZipValid && (
                <div style={{marginTop: 6, fontSize: 12, color: t.coral, paddingLeft: 4}}>ZIP must be 5 digits</div>
              )}

              <div style={{
                display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1.6fr 1fr', gap: 6,
                marginTop: 8,
              }}>
                <div style={{fontSize: 11.5, color: t.ink60, lineHeight: 1.4, paddingLeft: 4}}>
                  Harold texts you — no emails, ever.
                </div>
                <div style={{fontSize: 11.5, color: t.ink60, lineHeight: 1.4, paddingLeft: 4}}>
                  For local news, events &amp; weather.
                </div>
              </div>

              <button style={{
                marginTop: 14, width:'100%',
                background: isPhoneValid ? t.coral : 'rgba(255,90,45,0.4)',
                color: t.cream,
                border:'none', padding:'16px 26px', borderRadius: 14,
                fontSize: 15, fontWeight: 700,
                cursor: isPhoneValid ? 'pointer' : 'not-allowed',
                boxShadow: isPhoneValid ? t.btn : 'none',
                fontFamily: t.sans,
                display:'inline-flex', alignItems:'center', justifyContent:'center', gap: 10,
                whiteSpace:'nowrap', minHeight: 44,
              }}
                type="button"
                disabled={!isPhoneValid}
                onClick={handleStep2Continue}>
                Continue
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
              </button>
            </form>
            <p style={{marginTop: 12, fontSize: 12, color: t.ink40, textAlign:'center'}}>
              Next: pick your plan. Takes another 10 seconds.
            </p>
          </div>
        )}

        {step === 3 && (
          <div style={{padding: isMobile ? '10px 14px 16px' : '12px 20px 20px'}}>
            {/* recap bar */}
            <div style={{
              padding:'12px 14px', borderRadius: 14,
              background:'#FFF3E6', marginBottom: 16,
              display:'flex', alignItems:'center', gap: 10,
            }}>
              <button onClick={()=>setStep(2)} style={{
                width: 32, height: 32, borderRadius: 999, border:'none',
                background: t.paper, cursor:'pointer', flexShrink:0,
                display:'flex', alignItems:'center', justifyContent:'center',
                minHeight: 44, minWidth: 32,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#2A1810" strokeWidth="2.5" strokeLinecap="round"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
              </button>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize: 12, color: t.ink60, fontFamily: t.mono, letterSpacing:'0.08em'}}>
                  YOU PICKED · {segments.size} SEGMENTS
                </div>
                <div style={{fontSize: 13, fontWeight: 600, color: t.ink, marginTop: 2, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>
                  {[...segments].map(id => {
                    const s = SEGS.find(x=>x.id===id);
                    return s ? s.label : '';
                  }).filter(Boolean).join(' · ')}
                </div>
              </div>
            </div>

            {/* billing-period toggle */}
            <div style={{
              display:'flex', justifyContent:'center', marginBottom: 16,
            }}>
              <div style={{
                display:'inline-flex', alignItems:'center',
                background:'#FFF3E6', borderRadius: 999, padding: 4,
                border:'1px solid rgba(42,24,16,0.08)',
                position:'relative',
              }}>
                <button
                  type="button"
                  onClick={()=>setBilling('monthly')}
                  style={{
                    fontFamily: t.sans,
                    background: billing==='monthly' ? '#fff' : 'transparent',
                    color: billing==='monthly' ? t.ink : t.ink60,
                    border:'none', cursor:'pointer',
                    padding:'8px 18px', borderRadius: 999,
                    fontSize: 13, fontWeight: 700,
                    boxShadow: billing==='monthly' ? '0 2px 6px rgba(42,24,16,0.08)' : 'none',
                    minHeight: 44,
                  }}>
                  Monthly
                </button>
                <button
                  type="button"
                  onClick={()=>setBilling('annual')}
                  style={{
                    fontFamily: t.sans,
                    background: billing==='annual' ? t.coral : 'transparent',
                    color: billing==='annual' ? t.cream : t.ink60,
                    border:'none', cursor:'pointer',
                    padding:'8px 14px 8px 18px', borderRadius: 999,
                    fontSize: 13, fontWeight: 700,
                    boxShadow: billing==='annual' ? '0 4px 12px rgba(255,90,45,0.3)' : 'none',
                    minHeight: 44,
                    display:'inline-flex', alignItems:'center', gap: 8,
                  }}>
                  <span>Annual</span>
                  <span style={{
                    fontFamily: t.mono, fontSize: 10, letterSpacing:'0.08em',
                    background: billing==='annual' ? 'rgba(255,243,230,0.22)' : t.coral,
                    color: billing==='annual' ? t.cream : t.cream,
                    padding:'3px 7px', borderRadius: 999, fontWeight: 800,
                  }}>SAVE 25%</span>
                </button>
              </div>
            </div>

            {/* plans */}
            <div style={{display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 12}}>
              {/* BASIC */}
              <button type="button" onClick={()=>setPlan('basic')} style={{
                textAlign:'left', cursor:'pointer', fontFamily: t.sans,
                border: plan==='basic' ? `2px solid ${t.ink}` : '2px solid rgba(42,24,16,0.1)',
                background:'#fff', borderRadius: 18, padding:'18px 18px 16px',
                display:'flex', flexDirection:'column', gap: 8,
                minHeight: 44,
              }}>
                <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
                  <span style={{fontSize: 14, fontWeight: 700, color: t.ink}}>Basic</span>
                  <span style={{fontFamily: t.mono, fontSize: 9, letterSpacing:'0.12em', color: t.ink40, fontWeight:700}}>STARTER</span>
                </div>
                {billing === 'annual' ? (
                  <React.Fragment>
                    <div style={{display:'flex', alignItems:'baseline', gap: 6}}>
                      <span style={{fontSize: 32, fontWeight: 800, color: t.ink, letterSpacing:'-0.03em', lineHeight: 1}}>
                        $2.63
                      </span>
                      <span style={{fontSize: 12, color: t.ink60}}>/ month</span>
                    </div>
                    <div style={{fontSize: 11, color: t.ink60, marginTop: 4, lineHeight: 1.3}}>
                      <strong style={{color: t.coral}}>You're saving 25%</strong> — billed <strong>$31.50/yr</strong>
                    </div>
                  </React.Fragment>
                ) : (
                  <div style={{display:'flex', alignItems:'baseline', gap: 6}}>
                    <span style={{fontSize: 32, fontWeight: 800, color: t.ink, letterSpacing:'-0.03em', lineHeight: 1}}>
                      $3.50
                    </span>
                    <span style={{fontSize: 12, color: t.ink60}}>/ month</span>
                  </div>
                )}
                <div style={{height:1, background:'rgba(42,24,16,0.08)', margin:'2px 0 4px'}}/>
                <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:6}}>
                  {[
                    {y:true,  t:'U.S., World & Good News'},
                    {y:false, t:'No custom segments'},
                    {y:false, t:'No local news, weather or events'},
                    {y:false, t:'No personalization'},
                    {y:true,  t:'One 3-min brief each morning'},
                  ].map((item,i)=>(
                    <li key={i} style={{display:'flex', alignItems:'flex-start', gap:8, fontSize: 12.5, color: item.y ? t.ink80 : t.ink40, lineHeight: 1.4}}>
                      <span style={{
                        width: 14, height: 14, borderRadius: 999, flexShrink:0, marginTop: 2,
                        background: item.y ? 'rgba(42,24,16,0.08)' : 'transparent',
                        border: item.y ? 'none' : '1px solid rgba(42,24,16,0.2)',
                        color: t.ink, display:'inline-flex', alignItems:'center', justifyContent:'center',
                      }}>
                        {item.y ? (
                          <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>
                        ) : (
                          <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
                        )}
                      </span>
                      <span style={{textDecoration: item.y ? 'none' : 'line-through'}}>{item.t}</span>
                    </li>
                  ))}
                </ul>
              </button>

              {/* HAROLD */}
              <button type="button" onClick={()=>setPlan('harold')} style={{
                textAlign:'left', cursor:'pointer', fontFamily: t.sans,
                border: plan==='harold' ? `2px solid ${t.coral}` : '2px solid rgba(42,24,16,0.1)',
                background: plan==='harold' ? 'linear-gradient(180deg, #FFF3E6 0%, #FFFCF6 60%)' : '#fff',
                borderRadius: 18, padding:'18px 18px 16px',
                display:'flex', flexDirection:'column', gap: 8, position:'relative',
                boxShadow: plan==='harold' ? '0 8px 24px rgba(255,90,45,0.15)' : 'none',
                minHeight: 44,
              }}>
                <div style={{
                  position:'absolute', top: -10, right: 14,
                  background: t.coral, color: t.cream,
                  fontFamily: t.mono, fontSize: 9, letterSpacing:'0.12em',
                  padding:'4px 10px', borderRadius: 999, fontWeight: 800,
                }}>RECOMMENDED</div>
                <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
                  <span style={{fontSize: 14, fontWeight: 700, color: t.ink, display:'inline-flex', alignItems:'center', gap:6}}>
                    <span style={{fontSize: 16}}>🦉</span> Premium
                  </span>
                  <span style={{fontFamily: t.mono, fontSize: 9, letterSpacing:'0.12em', color: t.coral, fontWeight:700}}>EVERYTHING</span>
                </div>
                {billing === 'annual' ? (
                  <React.Fragment>
                    <div style={{display:'flex', alignItems:'baseline', gap: 6}}>
                      <span style={{fontSize: 32, fontWeight: 800, color: t.ink, letterSpacing:'-0.03em', lineHeight: 1}}>
                        $3.75
                      </span>
                      <span style={{fontSize: 12, color: t.ink60}}>/ month</span>
                    </div>
                    <div style={{fontSize: 11, color: t.ink60, marginTop: 4, lineHeight: 1.3}}>
                      <strong style={{color: t.coral}}>You're saving 25%</strong> — billed <strong>$45/yr</strong>
                    </div>
                  </React.Fragment>
                ) : (
                  <div style={{display:'flex', alignItems:'baseline', gap: 6}}>
                    <span style={{fontSize: 32, fontWeight: 800, color: t.ink, letterSpacing:'-0.03em', lineHeight: 1}}>
                      $5
                    </span>
                    <span style={{fontSize: 12, color: t.ink60}}>/ month</span>
                  </div>
                )}
                <div style={{height:1, background:'rgba(42,24,16,0.08)', margin:'2px 0 4px'}}/>
                <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:6}}>
                  {[
                    `All of your selected segments — change anytime`,
                    `Local news, weather & events for ${metroForZip(zip)}`,
                    'Greeted by name each morning',
                    'Full personalization & tone',
                    '7-day free trial — cancel anytime',
                  ].map((item,i)=>(
                    <li key={i} style={{display:'flex', alignItems:'flex-start', gap:8, fontSize: 12.5, color: t.ink80, lineHeight: 1.4}}>
                      <span style={{
                        width: 14, height: 14, borderRadius: 999, flexShrink:0, marginTop: 2,
                        background: t.coral, color: t.cream,
                        display:'inline-flex', alignItems:'center', justifyContent:'center',
                      }}>
                        <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>
                      </span>
                      <span>{item}</span>
                    </li>
                  ))}
                </ul>
              </button>
            </div>

            {submitError && (
              <div style={{marginTop: 10, padding:'10px 14px', borderRadius: 10, background:'rgba(255,90,45,0.08)', border:'1px solid rgba(255,90,45,0.2)', fontSize: 13, color: t.coral}}>
                {submitError}
              </div>
            )}

            <button
              onClick={handleSubmit}
              disabled={loading}
              style={{
                marginTop: 16, width:'100%',
                background: loading ? 'rgba(255,90,45,0.6)' : t.coral, color: t.cream,
                border:'none', padding:'16px', borderRadius: 14,
                fontSize: 15, fontWeight: 700, cursor: loading ? 'default' : 'pointer',
                boxShadow: t.btn, fontFamily: t.sans,
                display:'inline-flex', alignItems:'center', justifyContent:'center', gap: 10,
                minHeight: 44,
              }}>
              {loading ? 'Redirecting to checkout…' : (() => {
                const isAnnual = billing === 'annual';
                if (plan === 'harold') {
                  return isAnnual
                    ? 'Start 7-day free trial — then $45/year'
                    : 'Start 7-day free trial — then $5/month';
                }
                return isAnnual
                  ? 'Continue with Basic — $31.50/year'
                  : 'Continue with Basic — $3.50/month';
              })()}
              {!loading && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>}
            </button>
            <p style={{marginTop: 10, fontSize: 11.5, color: t.ink40, textAlign:'center'}}>
              First briefing arrives tomorrow morning. Cancel anytime by texting STOP.
            </p>
          </div>
        )}
      </div>

      <div style={{
        marginTop: 18, display:'flex', justifyContent:'center',
        gap: 18, flexWrap:'wrap',
      }}>
        <span style={{fontSize:12, color: t.ink40}}>✓ 7‑day free trial</span>
        <span style={{fontSize:12, color: t.ink40}}>✓ Cancel by texting STOP</span>
        <span style={{fontSize:12, color: t.ink40}}>✓ First briefing tomorrow</span>
      </div>

    </section>
  );
}

window.MLNav = MLNav;
window.MLHero = MLHero;
