// plans.jsx — subscription tiers (space themed) + Profile plan card

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

// Three tiers: free (browse only), basic ($9.99), vip ($19.99). Monthly,
// 30-day periods. Benefits map 1:1 to entitlements in user.jsx / subscriptions.sql.
const PLANS = [
  {
    id: 'free',
    name: 'FREE',
    price: 0,
    priceDisplay: '0',
    short: 'no plan',
    tagline: 'Browse the community. Subscribe to join in.',
    altitude: 'GROUND CONTROL',
    coords: 'T-MINUS 10',
    perks: [
      'See the Feed, profiles & coaches',
      'No posting, liking or comments',
      'No chat or following',
      'Upgrade anytime to unlock everything',
    ],
    palette: ['#3A3F4A', '#0B0B0F'],
    glow: '#9AA3B2',
  },
  {
    id: 'basic',
    name: 'BASIC',
    price: 9.99,
    priceDisplay: '9.99',
    short: '$9.99 / mo',
    tagline: 'Join the community + a free quick review every month.',
    altitude: 'LOW EARTH ORBIT',
    coords: '400 KM · ALTITUDE',
    perks: [
      'Full Feed access — post, like, comment, upload & rate',
      'Earn & redeem community points',
      '1 free Quick Score review ($11) every month',
    ],
    palette: ['#5B6AC4', '#0B1030'],
    glow: '#7AA8FF',
    badge: 'POPULAR',
  },
  {
    id: 'vip',
    name: 'VIP',
    price: 19.99,
    priceDisplay: '19.99',
    short: '$19.99 / mo',
    tagline: 'Everything in Basic, plus pro reviews & a coach class.',
    altitude: 'DEEP SPACE',
    coords: 'ALL ACCESS',
    perks: [
      'Everything in Basic',
      '2 free In-Depth reviews ($40 each) every month',
      '1 free 20-min class with a coach every month',
    ],
    palette: ['#C72820', '#7A1A0A'],
    glow: '#FF7849',
    badge: 'BEST VALUE',
  },
];

// Format a plan expiry ISO date → 'JUN 30, 2026'.
function fmtPlanDate(iso) {
  if (!iso) return '';
  try {
    return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }).toUpperCase();
  } catch (e) { return ''; }
}

// SVG starfield + planet for plan cards
function PlanCelestial({ palette, glow, size = 110 }) {
  const [c1, c2] = palette;
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ flexShrink: 0 }}>
      <defs>
        <radialGradient id={`g-${glow.slice(1)}`} cx="35%" cy="35%">
          <stop offset="0%" stopColor={glow} stopOpacity="0.9"/>
          <stop offset="40%" stopColor={c1} stopOpacity="1"/>
          <stop offset="100%" stopColor={c2} stopOpacity="1"/>
        </radialGradient>
        <radialGradient id={`halo-${glow.slice(1)}`} cx="50%" cy="50%">
          <stop offset="50%" stopColor={glow} stopOpacity="0"/>
          <stop offset="70%" stopColor={glow} stopOpacity="0.18"/>
          <stop offset="100%" stopColor={glow} stopOpacity="0"/>
        </radialGradient>
      </defs>
      {/* halo */}
      <circle cx="50" cy="50" r="48" fill={`url(#halo-${glow.slice(1)})`}/>
      {/* stars */}
      {[[12,18,1],[88,22,1.2],[20,82,0.9],[82,78,1],[68,12,0.7],[10,52,0.6],[92,55,0.8]].map(([x,y,r], i) => (
        <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity={0.85}/>
      ))}
      {/* planet */}
      <circle cx="50" cy="50" r="28" fill={`url(#g-${glow.slice(1)})`}/>
      {/* ring (for tier 3) */}
      {glow === '#CAFF33' && (
        <ellipse cx="50" cy="50" rx="40" ry="8" fill="none" stroke={glow} strokeWidth="1.5" opacity="0.7" transform="rotate(-18 50 50)"/>
      )}
      {/* surface detail */}
      <ellipse cx="42" cy="44" rx="6" ry="3" fill={c2} opacity="0.35"/>
      <ellipse cx="58" cy="56" rx="8" ry="4" fill={c2} opacity="0.25"/>
      {/* shine */}
      <ellipse cx="40" cy="38" rx="6" ry="3" fill="#fff" opacity="0.35"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Compact plan card for Profile
// ─────────────────────────────────────────────────────────────
function ProfilePlanCard({ theme, currentPlanId, expiresAt, active, onOpen }) {
  const plan = PLANS.find(p => p.id === currentPlanId) || PLANS[0];
  const isFree = plan.id === 'free' || !active;
  // Memberships are now buyable inside the native app too (App Store / Play
  // billing), so there's no reason left to send anyone to the website.
  const subline = isFree
    ? 'NO PLAN · TAP TO SUBSCRIBE'
    : `$${plan.priceDisplay}/MO · RENEWS ${fmtPlanDate(expiresAt)}`;
  return (
    <button onClick={onOpen} style={{
      width: '100%', padding: 0, border: 'none', cursor: 'pointer',
      borderRadius: 18, overflow: 'hidden', textAlign: 'left',
      background: `linear-gradient(135deg, ${plan.palette[0]} 0%, ${plan.palette[1]} 100%)`,
      position: 'relative', color: '#fff',
    }}>
      {/* starfield bg */}
      <svg width="100%" height="100%" viewBox="0 0 400 200" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, opacity: 0.6, pointerEvents: 'none' }}>
        {[[40,30,1],[120,60,0.7],[200,20,1.2],[280,80,0.8],[340,40,0.9],
          [70,140,0.6],[160,180,1],[230,150,0.8],[310,170,1.1],[380,120,0.7],
          [20,90,0.5],[100,110,0.9],[180,100,0.6]].map(([x,y,r], i) => (
          <circle key={i} cx={x} cy={y} r={r} fill="#fff"/>
        ))}
      </svg>
      <div style={{ position: 'relative', padding: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
        <PlanCelestial palette={plan.palette} glow={plan.glow} size={86} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: theme.fontMono, fontSize: 10, color: plan.glow,
            letterSpacing: 1, fontWeight: 700,
          }}>YOUR PLAN</div>
          <div style={{
            fontFamily: theme.fontDisplay, fontSize: 22, color: '#fff',
            letterSpacing: 0.2, lineHeight: 1, marginTop: 4,
            textTransform: 'uppercase',
          }}>{plan.name}</div>
          <div style={{
            fontFamily: theme.fontMono, fontSize: 10, color: 'rgba(255,255,255,0.65)',
            letterSpacing: 0.5, marginTop: 4, fontWeight: 600,
          }}>{subline}</div>
        </div>
        <div style={{
          padding: '8px 12px', borderRadius: 99,
          background: 'rgba(255,255,255,0.15)',
          backdropFilter: 'blur(10px)',
          fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
          letterSpacing: 1, color: '#fff', whiteSpace: 'nowrap',
        }}>{isFree ? 'SUBSCRIBE →' : 'MANAGE →'}</div>
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Full plans screen
// ─────────────────────────────────────────────────────────────
function PlansScreen({ theme, currentPlanId, onBack, onSubscribe }) {
  const U = window.LAUNCH_USER;
  const [selected, setSelected] = useStateP(currentPlanId === 'free' ? 'basic' : currentPlanId);
  // Inside the native app, memberships are sold through the App Store / Play
  // Store (App Store guideline 3.1.1 — a membership the app unlocks has to be
  // buyable in the app). On the web we keep charging with Stripe.
  const native = !!(U && U.isNativeApp && U.isNativeApp());
  const canIAP = !!(U && U.canBuyInApp && U.canBuyInApp());
  // Native build without store billing wired up: we can't sell, and we must not
  // point people to the website to buy either — that's the 3.1.1 violation.
  const lockPaid = (id) => native && !canIAP && id !== 'free';

  const [busy, setBusy] = useStateP(null);      // plan id being purchased
  const [notice, setNotice] = useStateP(null);  // { kind:'error'|'ok', text }
  const [prices, setPrices] = useStateP({});    // store-formatted prices
  const [manageUrl, setManageUrl] = useStateP(null);

  // Real localized store prices ("$9.99", "9,99 €"…). Apple requires we show
  // what the store will actually charge, not a hardcoded number.
  React.useEffect(() => {
    if (!canIAP) return;
    let alive = true;
    U.iapPrices().then((p) => { if (alive && p) setPrices(p); }).catch(() => {});
    U.iapManagementURL().then((u) => { if (alive) setManageUrl(u); }).catch(() => {});
    return () => { alive = false; };
  }, [canIAP]);

  // An active store subscription means cancelling has to happen in the App
  // Store, not here — otherwise we'd strip the benefits while Apple keeps
  // charging them every month.
  const storeSubActive = !!manageUrl;

  const openManage = () => { if (manageUrl) window.open(manageUrl, '_blank'); };

  const choosePlan = async (planId) => {
    if (planId === currentPlanId || busy) return;
    setNotice(null);

    if (planId === 'free' && storeSubActive) { openManage(); return; }
    if (lockPaid(planId)) {
      setNotice({ kind: 'error', text: 'Memberships are unavailable in the app right now. Please try again later.' });
      return;
    }
    if (!onSubscribe) return;

    setBusy(planId);
    try {
      const res = await onSubscribe(planId);
      if (res && res.cancelled) return;               // user backed out — stay quiet
      if (res && res.error) { setNotice({ kind: 'error', text: res.error }); return; }
      if (res && res.ok && planId !== 'free') {
        setNotice({ kind: 'ok', text: 'You\'re in. Your membership is active.' });
        U.iapManagementURL().then(setManageUrl).catch(() => {});
      }
    } finally { setBusy(null); }
  };

  const restore = async () => {
    if (busy) return;
    setNotice(null); setBusy('restore');
    try {
      const res = await U.restorePurchasesInApp();
      if (res && res.error) setNotice({ kind: 'error', text: res.error });
      else if (res && res.nothingToRestore) setNotice({ kind: 'error', text: 'No previous purchases found on this Apple ID.' });
      else setNotice({ kind: 'ok', text: 'Your membership has been restored.' });
      U.iapManagementURL().then(setManageUrl).catch(() => {});
    } finally { setBusy(null); }
  };

  // Store price when we have it, our own copy as fallback.
  const priceOf = (p) => (prices[p.id] && prices[p.id].price) || null;

  return (
    <div style={{
      paddingBottom: 130,
      background: '#03050E',
      minHeight: '100%', color: '#fff',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Starfield background */}
      <svg width="100%" height="100%" viewBox="0 0 400 1200" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, opacity: 0.7, pointerEvents: 'none' }}>
        <defs>
          <radialGradient id="bgGlow" cx="20%" cy="10%">
            <stop offset="0%" stopColor="#7A5AE0" stopOpacity="0.25"/>
            <stop offset="100%" stopColor="#03050E" stopOpacity="0"/>
          </radialGradient>
          <radialGradient id="bgGlow2" cx="90%" cy="40%">
            <stop offset="0%" stopColor="#C72820" stopOpacity="0.18"/>
            <stop offset="100%" stopColor="#03050E" stopOpacity="0"/>
          </radialGradient>
        </defs>
        <rect width="400" height="1200" fill="url(#bgGlow)"/>
        <rect width="400" height="1200" fill="url(#bgGlow2)"/>
        {Array.from({ length: 80 }, (_, i) => {
          const x = (i * 73) % 400;
          const y = (i * 137) % 1200;
          const r = (i % 5 === 0) ? 1.4 : (i % 3 === 0) ? 1 : 0.6;
          return <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity={(i % 4) * 0.25 + 0.3}/>;
        })}
      </svg>

      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        position: 'relative',
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.12)',
          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="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 10, color: 'rgba(255,255,255,0.5)',
          letterSpacing: 1, fontWeight: 700,
        }}>MISSION CONTROL</div>
      </div>

      {/* Hero */}
      <div style={{ padding: `4px ${theme.pad}px 0`, position: 'relative' }}>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 10, color: '#CAFF33',
          letterSpacing: 1.5, fontWeight: 700, marginBottom: 8,
        }}>★ CHOOSE YOUR ALTITUDE</div>
        <div style={{
          fontFamily: theme.fontDisplay, fontSize: 40, color: '#fff',
          letterSpacing: 0.2, lineHeight: 0.9, textTransform: 'uppercase',
        }}>
          HOW FAR<br/>YOU GOING?
        </div>
        <div style={{
          fontFamily: theme.fontBody, fontSize: 14, color: 'rgba(255,255,255,0.65)',
          marginTop: 12, lineHeight: 1.5,
        }}>
          Three orbits. Cancel anytime. The further out you go, the more we put behind your launch.
        </div>
      </div>

      {/* Purchase feedback (store errors, restore results…) */}
      {notice && (
        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0`, position: 'relative' }}>
          <div style={{
            padding: 14, borderRadius: 14,
            background: notice.kind === 'ok' ? 'rgba(202,255,51,0.08)' : 'rgba(199,40,32,0.12)',
            border: `1px solid ${notice.kind === 'ok' ? 'rgba(202,255,51,0.3)' : 'rgba(255,120,73,0.4)'}`,
          }}>
            <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.88)', lineHeight: 1.5 }}>
              {notice.text}
            </div>
          </div>
        </div>
      )}

      {/* Native build with no store billing configured: we can't sell here, and
          we must NOT send people to the website to buy (guideline 3.1.1). */}
      {native && !canIAP && (
        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0`, position: 'relative' }}>
          <div style={{
            padding: 14, borderRadius: 14,
            background: 'rgba(255,255,255,0.05)',
            border: '1px solid rgba(255,255,255,0.14)',
          }}>
            <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.82)', lineHeight: 1.5 }}>
              Memberships are temporarily unavailable in the app. Please try again later.
            </div>
          </div>
        </div>
      )}

      {/* Plan cards */}
      <div style={{ padding: `${theme.gap + 8}px ${theme.pad}px 0`, display: 'flex', flexDirection: 'column', gap: 12, position: 'relative' }}>
        {PLANS.map((p, i) => {
          const isCurrent = p.id === currentPlanId;
          const isSelected = p.id === selected;
          return (
            <button
              key={p.id}
              onClick={() => {
                setSelected(p.id);
                // Tapping a plan goes straight to checkout (or activates Free).
                // On native that checkout is the App Store / Play sheet.
                if (p.id !== currentPlanId) choosePlan(p.id);
              }}
              style={{
                padding: 0, border: 'none', cursor: 'pointer',
                borderRadius: 20, overflow: 'hidden', textAlign: 'left',
                position: 'relative',
                background: `linear-gradient(160deg, ${p.palette[0]}40 0%, ${p.palette[1]} 70%, #03050E 100%)`,
                boxShadow: isSelected
                  ? `0 0 0 2px ${p.glow}, 0 12px 40px ${p.glow}35`
                  : `0 0 0 1px rgba(255,255,255,0.08)`,
                transition: 'box-shadow .25s ease',
              }}
            >
              {/* badge */}
              {p.badge && (
                <div style={{
                  position: 'absolute', top: 14, right: 14, zIndex: 2,
                  padding: '5px 10px', borderRadius: 99,
                  background: p.glow, color: '#0A0A0A',
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 9, fontWeight: 700,
                  letterSpacing: 1,
                }}>{p.badge}</div>
              )}

              <div style={{ padding: 18, display: 'flex', alignItems: 'flex-start', gap: 14, position: 'relative' }}>
                <PlanCelestial palette={p.palette} glow={p.glow} size={88} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: p.glow,
                    letterSpacing: 1.2, fontWeight: 700, textTransform: 'uppercase',
                  }}>{p.short} · {p.coords}</div>
                  <div style={{
                    fontFamily: theme.fontDisplay, fontSize: 26, color: '#fff',
                    letterSpacing: 0.3, lineHeight: 1, marginTop: 4,
                    textTransform: 'uppercase',
                  }}>{p.name}</div>
                  <div style={{
                    fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.75)',
                    marginTop: 6, lineHeight: 1.4, fontStyle: 'italic',
                  }}>{p.tagline}</div>
                  <div style={{ marginTop: 10, display: 'flex', alignItems: 'baseline', gap: 6 }}>
                    <span style={{ fontFamily: theme.fontDisplay, fontSize: 32, color: '#fff', lineHeight: 1, letterSpacing: -0.5 }}>
                      {priceOf(p)
                        // Store price, already formatted for the user's storefront.
                        ? priceOf(p)
                        : <React.Fragment><span style={{ fontSize: 16, opacity: 0.7 }}>$</span>{p.priceDisplay}</React.Fragment>}
                    </span>
                    <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'rgba(255,255,255,0.55)', letterSpacing: 0.5, fontWeight: 600 }}>
                      /MO
                    </span>
                  </div>
                </div>
              </div>

              {/* perks */}
              <div style={{
                padding: '0 18px 18px',
                borderTop: '1px solid rgba(255,255,255,0.08)',
                marginTop: 4, paddingTop: 14,
                display: 'flex', flexDirection: 'column', gap: 8,
              }}>
                {p.perks.map((perk, j) => (
                  <div key={j} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                    <div style={{
                      width: 16, height: 16, borderRadius: 99,
                      background: `${p.glow}30`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0, marginTop: 1,
                    }}>
                      <svg width="9" height="9" viewBox="0 0 14 14" fill="none">
                        <path d="M2 7l3.5 3.5L12 4" stroke={p.glow} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </div>
                    <span style={{
                      fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.85)',
                      lineHeight: 1.4, fontWeight: 500,
                    }}>{perk}</span>
                  </div>
                ))}
              </div>

              {/* À la carte add-ons (Launch Pad + Orbit) */}
              {p.addons && (
                <div style={{
                  margin: '0 18px 16px', padding: 12, borderRadius: 12,
                  background: 'rgba(0,0,0,0.25)',
                  border: '1px dashed rgba(255,255,255,0.15)',
                }}>
                  <div style={{
                    fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: p.glow,
                    letterSpacing: 1.2, fontWeight: 700, marginBottom: 8,
                  }}>
                    ★ À LA CARTE {p.id === 'orbit' && '· 30% OFF'}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                    {p.addons.map((a, k) => (
                      <div key={k} style={{
                        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                      }}>
                        <span style={{
                          fontFamily: theme.fontBody, fontSize: 12, color: 'rgba(255,255,255,0.7)',
                        }}>{a.l}</span>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                          {a.strike && (
                            <span style={{
                              fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                              color: 'rgba(255,255,255,0.35)', textDecoration: 'line-through',
                              fontWeight: 600,
                            }}>{a.strike}</span>
                          )}
                          <span style={{
                            fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                            color: '#fff', fontWeight: 700,
                          }}>{a.p}</span>
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Nashville HQ callout (Stratosphere) */}
              {p.location && (
                <div style={{
                  margin: '0 18px 16px', padding: 14, borderRadius: 12,
                  background: `linear-gradient(135deg, ${p.glow}25 0%, transparent 100%)`,
                  border: `1px solid ${p.glow}40`,
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 10,
                    background: p.glow, color: '#0A0A0A',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                      <path d="M12 22s-7-7-7-13a7 7 0 0114 0c0 6-7 13-7 13z" stroke="#0A0A0A" strokeWidth="2" strokeLinejoin="round"/>
                      <circle cx="12" cy="9" r="2.5" stroke="#0A0A0A" strokeWidth="2"/>
                    </svg>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: p.glow,
                      letterSpacing: 1.2, fontWeight: 700,
                    }}>BASED IN</div>
                    <div style={{
                      fontFamily: theme.fontDisplay, fontSize: 20, color: '#fff',
                      letterSpacing: 0.2, lineHeight: 1, marginTop: 2,
                      textTransform: 'uppercase',
                    }}>NASHVILLE HQ</div>
                    <div style={{
                      fontFamily: theme.fontBody, fontSize: 11, color: 'rgba(255,255,255,0.7)',
                      marginTop: 4, lineHeight: 1.4,
                    }}>
                      In-person sessions · studio time · co-writing rooms
                    </div>
                  </div>
                </div>
              )}

              {/* status pill */}
              <div style={{ padding: '0 18px 18px' }}>
                <div style={{
                  padding: '10px 14px', borderRadius: 10, textAlign: 'center',
                  background: isCurrent
                    ? 'rgba(255,255,255,0.08)'
                    : isSelected
                      ? p.glow
                      : 'rgba(255,255,255,0.06)',
                  color: isCurrent
                    ? 'rgba(255,255,255,0.7)'
                    : isSelected
                      ? '#0A0A0A'
                      : '#fff',
                  border: !isCurrent && !isSelected ? '1px solid rgba(255,255,255,0.12)' : 'none',
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 11, fontWeight: 700,
                  letterSpacing: 1, textTransform: 'uppercase',
                }}>
                  {busy === p.id ? 'ONE MOMENT…' :
                   isCurrent ? '★ CURRENT PLAN' :
                   p.id === 'free' ? (storeSubActive ? 'CANCEL IN THE APP STORE' : 'SWITCH TO FREE') :
                   lockPaid(p.id) ? 'UNAVAILABLE' :
                   `GET ${p.name} →`}
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {/* FAQ-ish strip */}
      <div style={{ padding: `${theme.gap + 8}px ${theme.pad}px 0`, position: 'relative' }}>
        <Card theme={{ ...theme, surface: 'rgba(255,255,255,0.05)', border: 'rgba(255,255,255,0.12)' }}
          style={{ padding: 14, background: 'rgba(255,255,255,0.05)', borderColor: 'rgba(255,255,255,0.12)' }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgba(255,255,255,0.5)',
            letterSpacing: 1, fontWeight: 700, marginBottom: 8,
          }}>★ THE FINE PRINT</div>
          <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.8)', lineHeight: 1.5 }}>
            {native
              ? "Cancel anytime from your store account. Your membership stays active until the end of the period you've already paid for, and refunds are handled by the store."
              : "Cancel anytime. Your membership stays active until the end of the period you've already paid for."}
          </div>
        </Card>
      </div>

      {/* Store billing block. App Store review requires all of this to live in
          the app itself: a working Restore Purchases action, the auto-renewal
          terms, and links to the Terms of Use and Privacy Policy. */}
      {native && canIAP && (
        <div style={{ padding: `${theme.gap + 8}px ${theme.pad}px 0`, position: 'relative' }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <button onClick={restore} disabled={!!busy} style={{
              flex: 1, padding: '13px 12px', borderRadius: 12,
              background: 'rgba(255,255,255,0.06)', color: '#fff',
              border: '1px solid rgba(255,255,255,0.16)',
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11, fontWeight: 700,
              letterSpacing: 1, textTransform: 'uppercase',
              cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.6 : 1,
            }}>
              {busy === 'restore' ? 'RESTORING…' : 'RESTORE PURCHASES'}
            </button>
            {storeSubActive && (
              <button onClick={openManage} style={{
                flex: 1, padding: '13px 12px', borderRadius: 12,
                background: 'rgba(255,255,255,0.06)', color: '#fff',
                border: '1px solid rgba(255,255,255,0.16)',
                fontFamily: 'JetBrains Mono, monospace', fontSize: 11, fontWeight: 700,
                letterSpacing: 1, textTransform: 'uppercase', cursor: 'pointer',
              }}>
                MANAGE SUBSCRIPTION
              </button>
            )}
          </div>

          <div style={{
            marginTop: 12,
            fontFamily: theme.fontBody, fontSize: 11,
            color: 'rgba(255,255,255,0.55)', lineHeight: 1.55,
          }}>
            Basic and VIP are monthly auto-renewing subscriptions. Payment is charged
            to your store account at confirmation of purchase. The subscription renews
            automatically for the same price and period unless you turn off auto-renew
            at least 24 hours before the end of the current period. You can manage or
            cancel it any time in your store account settings.
            {' '}
            <a href="https://www.launchnash.com/terms-of-service" target="_blank" rel="noreferrer"
              style={{ color: 'rgba(255,255,255,0.8)', textDecoration: 'underline' }}>Terms of Use</a>
            {' · '}
            <a href="https://www.launchnash.com/english-privacy-policy" target="_blank" rel="noreferrer"
              style={{ color: 'rgba(255,255,255,0.8)', textDecoration: 'underline' }}>Privacy Policy</a>
          </div>
        </div>
      )}

      {/* Sticky CTA */}
      <div style={{
        position: 'absolute', bottom: 24, left: theme.pad, right: theme.pad,
        background: 'rgba(10,10,20,0.85)',
        backdropFilter: 'blur(20px)',
        borderRadius: 16, padding: 12,
        border: '1px solid rgba(255,255,255,0.12)',
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        {/* The same notice also renders at the top of the screen, but by the
            time you tap SUBSCRIBE you're looking at the bottom of a long page:
            an error up there reads as the button doing nothing at all. */}
        {notice && (
          <div style={{
            padding: '9px 11px', borderRadius: 10,
            background: notice.kind === 'ok' ? 'rgba(202,255,51,0.10)' : 'rgba(199,40,32,0.16)',
            border: `1px solid ${notice.kind === 'ok' ? 'rgba(202,255,51,0.35)' : 'rgba(255,120,73,0.45)'}`,
            fontFamily: theme.fontBody, fontSize: 12, lineHeight: 1.45,
            color: 'rgba(255,255,255,0.92)',
          }}>{notice.text}</div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: 'rgba(255,255,255,0.5)', letterSpacing: 1, fontWeight: 700 }}>
            SELECTED ALTITUDE
          </div>
          <div style={{ fontFamily: theme.fontDisplay, fontSize: 18, color: '#fff', lineHeight: 1, marginTop: 2, letterSpacing: 0.2 }}>
            {(() => {
              const sel = PLANS.find(p => p.id === selected);
              return `${sel.name} · ${priceOf(sel) || '$' + sel.priceDisplay}/MO`;
            })()}
          </div>
        </div>
        {(() => {
          const disabled = selected === currentPlanId || lockPaid(selected) || !!busy;
          return (
            <button
              onClick={() => choosePlan(selected)}
              disabled={disabled}
              style={{
                background: disabled ? 'rgba(255,255,255,0.1)' : '#CAFF33',
                color: disabled ? 'rgba(255,255,255,0.5)' : '#0A0A0A',
                fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
                padding: '14px 18px', borderRadius: 12, border: 'none',
                cursor: disabled ? 'default' : 'pointer',
                textTransform: 'uppercase', whiteSpace: 'nowrap',
              }}>
              {busy === selected ? 'ONE MOMENT…' :
               selected === currentPlanId ? 'CURRENT' :
               lockPaid(selected) ? 'UNAVAILABLE' :
               selected === 'free' ? (storeSubActive ? 'MANAGE' : 'SWITCH TO FREE') : 'SUBSCRIBE →'}
            </button>
          );
        })()}
        </div>
      </div>
    </div>
  );
}

window.LAUNCH_SCREENS_4 = { PlansScreen, ProfilePlanCard, PLANS };
