// Paywall — short, punchy, heavily animated one-screen Apollo pitch.
// Exponential scroll feel via aggressive easing; 3 tight scenes instead of 6 long ones.
function Paywall({ open, onClose, onSubscribe }) {
  const S = window.SOL;
  const scrollRef = React.useRef(null);
  const target = React.useRef(0);
  const current = React.useRef(0);
  const velocity = React.useRef(0);
  const raf = React.useRef(null);
  const progressBarRef = React.useRef(null);
  const [y, setY] = React.useState(0);
  const [closing, setClosing] = React.useState(false);
  const [purchasing, setPurchasing] = React.useState(false);

  // Reset transient state when reopened
  React.useEffect(() => {
    if (open) { setClosing(false); setPurchasing(false); }
  }, [open]);

  const animatedClose = () => {
    if (closing) return;
    setClosing(true);
    setTimeout(() => { onClose(); }, 420);
  };

  const handleBuy = async () => {
    if (purchasing || closing) return;
    setPurchasing(true);
    try {
      const token = localStorage.getItem('solunce_token');
      const r = await fetch('https://api.solunce.com/api/payments/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ plan: 'plus' }),
      });
      const d = await r.json();
      if (d.url) { window.location.href = d.url; return; }
    } catch {}
    setPurchasing(false);
  };

  React.useEffect(() => {
    if (!open) return;
    const el = scrollRef.current;
    if (!el) return;
    target.current = 0; current.current = 0; velocity.current = 0;
    el.scrollTop = 0; setY(0);

    // Exponential velocity scroll:
    //   wheel -> add impulse to velocity
    //   each frame: velocity *= BOOST (>1, exponential growth while active)
    //                then  *= DAMPING (<1, smooth decay)
    //                clamp to MAX_V so it can't run away
    const BOOST    = 1.04;   // per-frame growth factor while moving
    const DAMPING  = 0.88;   // per-frame decay
    const IMPULSE  = 0.55;   // fraction of wheel delta applied to velocity
    const MAX_V    = 140;    // px/frame cap
    const STOP_EPS = 0.15;   // velocity threshold to stop the loop

    const onWheel = (e) => {
      e.preventDefault();
      const impulse = e.deltaY * IMPULSE;
      // keep sign aligned with user intent; if reversing direction, reset exponent
      if (Math.sign(impulse) !== Math.sign(velocity.current)) {
        velocity.current = impulse;
      } else {
        velocity.current += impulse;
      }
      if (!raf.current) raf.current = requestAnimationFrame(tick);
    };

    const touch = { last: 0 };
    const onTS = (e) => { touch.last = e.touches[0].clientY; };
    const onTM = (e) => {
      const yT = e.touches[0].clientY;
      const dy = (touch.last - yT) * 1.4;
      touch.last = yT;
      if (Math.sign(dy) !== Math.sign(velocity.current)) velocity.current = dy;
      else velocity.current += dy * 0.6;
      if (!raf.current) raf.current = requestAnimationFrame(tick);
    };

    const tick = () => {
      const max = el.scrollHeight - el.clientHeight;

      // exponential growth while the user is still feeding it,
      // then damping pulls it back down
      velocity.current *= BOOST;
      velocity.current *= DAMPING;
      if (velocity.current >  MAX_V) velocity.current =  MAX_V;
      if (velocity.current < -MAX_V) velocity.current = -MAX_V;

      current.current += velocity.current;

      // clamp at edges and kill velocity against the wall
      if (current.current < 0)   { current.current = 0;   velocity.current = 0; }
      if (current.current > max) { current.current = max; velocity.current = 0; }

      el.scrollTop = current.current;

      // direct-write the progress bar to avoid React reconciliation jitter
      if (progressBarRef.current) {
        const p = max > 0 ? current.current / max : 0;
        progressBarRef.current.style.transform = `scaleX(${p})`;
      }

      setY(current.current);

      if (Math.abs(velocity.current) < STOP_EPS) {
        velocity.current = 0;
        raf.current = null;
        return;
      }
      raf.current = requestAnimationFrame(tick);
    };

    el.addEventListener('wheel', onWheel, { passive: false });
    el.addEventListener('touchstart', onTS, { passive: true });
    el.addEventListener('touchmove', onTM, { passive: false });
    return () => {
      el.removeEventListener('wheel', onWheel);
      el.removeEventListener('touchstart', onTS);
      el.removeEventListener('touchmove', onTM);
      if (raf.current) cancelAnimationFrame(raf.current);
      raf.current = null;
    };
  }, [open]);

  if (!open) return null;

  const vh = typeof window !== 'undefined' ? window.innerHeight : 900;
  const totalH = vh * 16; // longer overall so each scene's animation has more scroll to play out

  const clamp = (t) => Math.max(0, Math.min(1, t));
  const lerp = (a, b, t) => a + (b - a) * t;
  const range = (s, e) => clamp((y - s) / (e - s));
  const progress = clamp(y / Math.max(1, totalH - vh));

  // scene ranges — scene 2 gets extra room since there's a lot to read
  const s1 = range(0,          vh * 4);
  const s2 = range(vh * 4.7,   vh * 10.7);
  const s3 = range(vh * 11.5,  vh * 15.5);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 300, background: '#0E0C0A',
      animation: closing
        ? 'pw-close 0.42s cubic-bezier(0.55, 0, 0.1, 1) forwards'
        : 'sol-fade-in 0.32s ease',
      overflow: 'hidden',
      transformOrigin: '50% 55%',
    }}>
      <style>{`
        @keyframes pw-close {
          0%   { opacity: 1; transform: scale(1) translateY(0); filter: blur(0); }
          40%  { opacity: 1; transform: scale(0.96) translateY(8px); filter: blur(2px); }
          100% { opacity: 0; transform: scale(0.82) translateY(40px); filter: blur(8px); }
        }
        @keyframes pw-ember {
          0%   { transform: translateY(0) scale(0.6); opacity: 0; }
          30%  { opacity: 1; }
          100% { transform: translateY(-140px) scale(1.2); opacity: 0; }
        }
        @keyframes pw-star-twinkle {
          0%, 100% { opacity: 0.25; transform: scale(0.9); }
          50%      { opacity: 1; transform: scale(1.3); }
        }
        @keyframes pw-nebula-drift {
          0%, 100% { transform: translate(0, 0) scale(1); }
          50%      { transform: translate(40px, -20px) scale(1.08); }
        }
        @keyframes pw-shoot {
          0%    { transform: translate(0, 0) rotate(18deg); opacity: 0; }
          4%    { opacity: 0.9; }
          10%   { transform: translate(60vw, 30vh) rotate(18deg); opacity: 0.9; }
          14%   { transform: translate(120vw, 60vh) rotate(18deg); opacity: 0; }
          100%  { transform: translate(120vw, 60vh) rotate(18deg); opacity: 0; }
        }
      `}</style>

      {/* Ambient background — single animated sun + horizon, no orbit rings, no plum */}
      <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', overflow: 'hidden' }}>
        {/* horizon line that rises toward the top as you scroll */}
        <div style={{
          position: 'absolute', left: 0, right: 0,
          top: `${72 - progress * 30}%`,
          height: 1,
          background: `linear-gradient(to right, transparent 10%, rgba(244,199,123,${0.12 + progress * 0.12}) 50%, transparent 90%)`,
        }}/>

        {/* atmospheric haze on horizon */}
        <div style={{
          position: 'absolute', left: '-10%', right: '-10%',
          top: `${70 - progress * 30}%`, height: 280,
          transform: 'translateY(-50%)',
          background: `linear-gradient(to bottom, transparent, rgba(184,74,31,${0.06 + progress * 0.08}) 48%, transparent)`,
          filter: 'blur(20px)',
        }}/>

        {/* drifting nebula — two soft color washes that parallax on scroll */}
        <div style={{
          position: 'absolute', left: '15%', top: `${30 - progress * 14}%`,
          width: 520, height: 520, borderRadius: '50%',
          background: `radial-gradient(circle, rgba(244,199,123,0.12), transparent 62%)`,
          filter: 'blur(40px)', pointerEvents: 'none',
          animation: 'pw-nebula-drift 22s ease-in-out infinite',
        }}/>
        <div style={{
          position: 'absolute', right: '10%', top: `${55 + progress * 8}%`,
          width: 460, height: 460, borderRadius: '50%',
          background: `radial-gradient(circle, rgba(184,74,31,0.14), transparent 60%)`,
          filter: 'blur(50px)', pointerEvents: 'none',
          animation: 'pw-nebula-drift 28s ease-in-out -10s infinite reverse',
        }}/>

        {/* constellation — slow twinkling star field, spread evenly across viewport */}
        {[
          {x:8, y:22, s:1.5, d:0},{x:18, y:64, s:2, d:1.2},{x:26, y:38, s:1, d:2.1},
          {x:33, y:82, s:1.5, d:0.6},{x:42, y:18, s:2.5, d:1.8},{x:48, y:72, s:1, d:2.4},
          {x:55, y:44, s:1.5, d:0.3},{x:62, y:12, s:1, d:1.5},{x:68, y:58, s:2, d:2.7},
          {x:74, y:30, s:1.5, d:0.9},{x:82, y:76, s:1, d:2.0},{x:88, y:46, s:2, d:1.1},
          {x:14, y:48, s:1, d:3.0},{x:38, y:58, s:1, d:2.6},{x:58, y:88, s:1.5, d:1.4},
          {x:78, y:14, s:1.5, d:0.4},{x:92, y:66, s:1, d:2.2},{x:4, y:84, s:1, d:1.7},
        ].map((p, i) => (
          <div key={i} style={{
            position: 'absolute', left: `${p.x}%`, top: `${p.y - progress * 6}%`,
            width: p.s, height: p.s, borderRadius: '50%',
            background: S.cream,
            boxShadow: `0 0 ${4 + p.s * 3}px rgba(245,239,228,0.9), 0 0 ${12 + p.s * 4}px rgba(244,199,123,0.4)`,
            opacity: 0.4 + (i % 3) * 0.2,
            animation: `pw-star-twinkle ${4 + (i % 4)}s ease-in-out ${p.d}s infinite`,
          }}/>
        ))}

        {/* shooting star — one per ~12s, traverses upper third */}
        <div style={{
          position: 'absolute', left: '-10%', top: '22%',
          width: 100, height: 1,
          background: `linear-gradient(to right, transparent, ${S.cream}, ${S.sun}, transparent)`,
          animation: 'pw-shoot 14s linear infinite',
          opacity: 0.8,
        }}/>

        {/* subtle warm vignette bottom */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, height: '45%',
          background: `linear-gradient(to top, rgba(184,74,31,${0.25 + progress * 0.2}), transparent)`,
          opacity: 0.6,
        }}/>
      </div>

      {/* Progress bar */}
      <div style={{ position: 'fixed', top: 20, left: 32, right: 80, height: 2,
        background: 'rgba(245,239,228,0.08)', borderRadius: 2, zIndex: 320, overflow: 'hidden' }}>
        <div ref={progressBarRef} style={{
          width: '100%', height: '100%', borderRadius: 2,
          background: `linear-gradient(to right, ${S.sun}, ${S.amber})`,
          boxShadow: `0 0 10px ${S.sun}`,
          transformOrigin: '0 50%',
          transform: `scaleX(${progress})`,
          willChange: 'transform',
        }}/>
      </div>

      <button onClick={animatedClose} style={{
        position: 'fixed', top: 16, right: 24, width: 38, height: 38, borderRadius: 12,
        border: '1px solid rgba(245,239,228,0.18)', background: 'rgba(14,12,10,0.6)',
        backdropFilter: 'blur(12px)', cursor: 'pointer', zIndex: 330,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}><window.Icon name="close" size={17} color={S.cream}/></button>

      {/* Scroll container */}
      <div ref={scrollRef} style={{
        position: 'absolute', inset: 0, overflowY: 'scroll', zIndex: 3,
        scrollbarWidth: 'none',
      }} className="pw-scroll">
        <style>{`.pw-scroll::-webkit-scrollbar { display: none; }`}</style>
        <div style={{ height: totalH, position: 'relative' }}>

          {/* ============ SCENE 1 — HERO / THE SUN ============ */}
          <div style={{ position: 'sticky', top: 0, height: '100vh',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            pointerEvents: s1 < 1 ? 'auto' : 'none',
          }}>
            <div style={{
              textAlign: 'center', maxWidth: 620, padding: '0 32px',
              transform: `translateY(${s1 * -80}px) scale(${1 - s1 * 0.15})`,
              opacity: 1 - s1,
            }}>
              <div style={{
                display: 'flex', justifyContent: 'center', marginBottom: 20,
                position: 'relative', height: 56,
              }}>
                <div style={{
                  position: 'absolute', top: '50%', left: '50%',
                  transform: 'translate(-50%, -50%)',
                  width: 140, height: 140, borderRadius: '50%',
                  background: `radial-gradient(circle, rgba(244,199,123,0.28), transparent 65%)`,
                  filter: 'blur(14px)', animation: 'sol-breathe 4s ease-in-out infinite',
                  pointerEvents: 'none',
                }}/>
                <div style={{ animation: 'sol-breathe 5s ease-in-out infinite', position: 'relative' }}>
                  <window.SunMark size={48} variant="apollo"/>
                </div>
              </div>
              <div style={{
                fontFamily: S.mono, fontSize: 10, letterSpacing: 2.8, color: S.sun,
                textTransform: 'uppercase', marginBottom: 16,
              }}>— Solunce Plus —</div>
              <h1 style={{
                fontFamily: S.serif, fontSize: 'clamp(60px, 9vw, 104px)', lineHeight: 0.95,
                letterSpacing: -3, fontWeight: 400, color: S.cream,
                margin: '0 0 20px', textWrap: 'balance',
              }}>
                Meet <em style={{
                  fontStyle: 'italic',
                  color: S.sun,
                  textShadow: `0 0 40px rgba(244,199,123,0.5), 0 0 80px rgba(244,199,123,0.25)`,
                }}>Apollo.</em>
              </h1>
              <p style={{
                fontFamily: S.sans, fontSize: 17, lineHeight: 1.5,
                color: 'rgba(245,239,228,0.7)', margin: '0 auto', maxWidth: 420,
              }}>The unbounded sibling. Longer memory, sharper thinking.</p>
            </div>
          </div>

          {/* ============ SCENE 2 — THE THREE PROMISES (fan out) ============ */}
          <div style={{ position: 'sticky', top: 0, height: '100vh',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            pointerEvents: s2 > 0.05 && s2 < 0.95 ? 'auto' : 'none',
          }}>
            <div style={{
              textAlign: 'center', width: '100%', padding: '0 32px',
              opacity: s2 < 0.5 ? s2 * 2 : clamp(1 - (s2 - 0.5) * 2),
            }}>
              <div style={{
                fontFamily: S.mono, fontSize: 10, letterSpacing: 2.4, color: S.sun,
                textTransform: 'uppercase', marginBottom: 20,
              }}>— What's inside —</div>
              <h2 style={{
                fontFamily: S.serif, fontSize: 'clamp(44px, 6vw, 76px)',
                color: S.cream, fontWeight: 400, letterSpacing: -2, margin: '0 0 48px',
                lineHeight: 0.98,
              }}>
                Three things that <em style={{ fontStyle: 'italic', color: S.sun }}>change everything.</em>
              </h2>
              <div style={{
                display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
                gap: 16, maxWidth: 900, margin: '0 auto',
              }}>
                {[
                  { k: '1M', unit: 'tokens', label: 'Memory', desc: 'The whole book. The whole repo.', delay: 0 },
                  { k: '∞', unit: 'depth', label: 'Reasoning', desc: 'Thinks it through, shows its work.', delay: 0.08 },
                  { k: 'HD', unit: 'video', label: 'Vision', desc: 'Upload a clip. Ask about frame 00:42.', delay: 0.16 },
                ].map((it, i) => {
                  const t = clamp((s2 - it.delay) * 2.5);
                  return (
                    <div key={i} style={{
                      padding: '28px 20px', borderRadius: 18,
                      background: 'linear-gradient(160deg, rgba(244,199,123,0.08), rgba(245,239,228,0.02))',
                      border: '1px solid rgba(244,199,123,0.2)',
                      transform: `translateY(${lerp(60, 0, t)}px) rotate(${lerp((i-1) * 8, 0, t)}deg)`,
                      opacity: t,
                      boxShadow: `0 20px 50px rgba(0,0,0,${0.3 * t})`,
                      position: 'relative', overflow: 'hidden',
                    }}>
                      <div style={{
                        position: 'absolute', top: -20, right: -20, width: 80, height: 80,
                        background: `radial-gradient(circle, rgba(244,199,123,0.3), transparent 65%)`,
                      }}/>
                      <div style={{
                        fontFamily: S.serif, fontSize: 56, lineHeight: 1, letterSpacing: -2,
                        color: S.sun, textShadow: `0 0 30px rgba(244,199,123,${0.5 * t})`,
                        position: 'relative',
                      }}>{it.k}</div>
                      <div style={{
                        fontFamily: S.mono, fontSize: 9, letterSpacing: 1.4, color: 'rgba(245,239,228,0.5)',
                        textTransform: 'uppercase', margin: '4px 0 16px', position: 'relative',
                      }}>{it.unit}</div>
                      <div style={{
                        fontFamily: S.serif, fontSize: 22, color: S.cream, letterSpacing: -0.4,
                        marginBottom: 6, position: 'relative',
                      }}>{it.label}</div>
                      <div style={{
                        fontFamily: S.sans, fontSize: 13, lineHeight: 1.45,
                        color: 'rgba(245,239,228,0.65)', position: 'relative',
                      }}>{it.desc}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* ============ SCENE 3 — CTA ============ */}
          <div style={{ position: 'sticky', top: 0, height: '100vh',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            pointerEvents: s3 > 0.1 ? 'auto' : 'none',
          }}>
            <div style={{
              textAlign: 'center', maxWidth: 460, width: '100%', padding: '0 32px',
              transform: `scale(${lerp(0.85, 1, clamp(s3 * 1.8))})`,
              opacity: clamp(s3 * 2),
            }}>
              <div style={{
                display: 'flex', justifyContent: 'center', marginBottom: 22,
                animation: 'sol-breathe 3s ease-in-out infinite',
              }}><window.SunMark size={64} variant="apollo"/></div>
              <h2 style={{
                fontFamily: S.serif, fontSize: 'clamp(44px, 6vw, 72px)',
                color: S.cream, fontWeight: 400, letterSpacing: -2, margin: '0 0 14px',
                lineHeight: 0.98,
              }}>
                <em style={{ fontStyle: 'italic', color: S.sun }}>Ten dollars</em><br/>
                a month.
              </h2>
              <p style={{
                fontFamily: S.sans, fontSize: 15, color: 'rgba(245,239,228,0.7)',
                lineHeight: 1.5, margin: '0 0 28px',
              }}>Cancel any time. Apollo stays yours while you're in.</p>
              <div style={{
                padding: '22px 20px', borderRadius: 18,
                background: 'linear-gradient(160deg, rgba(245,239,228,0.06), rgba(245,239,228,0.02))',
                border: '1px solid rgba(244,199,123,0.28)',
                marginBottom: 18, position: 'relative', overflow: 'hidden',
              }}>
                <div style={{
                  position: 'absolute', top: -60, right: -60, width: 200, height: 200,
                  background: `radial-gradient(circle, rgba(244,199,123,0.3), transparent 65%)`,
                }}/>
                <div style={{
                  fontFamily: S.mono, fontSize: 9, letterSpacing: 1.4, color: 'rgba(245,239,228,0.5)',
                  textTransform: 'uppercase', marginBottom: 6, position: 'relative',
                }}>Monthly · Cancel anytime</div>
                <div style={{
                  fontFamily: S.serif, fontSize: 88, lineHeight: 1, letterSpacing: -3,
                  color: S.cream, display: 'inline-flex', alignItems: 'baseline', gap: 4,
                  position: 'relative',
                }}>
                  <span style={{ fontSize: 40, color: S.sun }}>$</span>10
                  <span style={{ fontSize: 22, color: 'rgba(245,239,228,0.45)', marginLeft: 4, letterSpacing: 0 }}>/mo</span>
                </div>
              </div>
              <button onClick={handleBuy} disabled={purchasing || closing} style={{
                width: '100%', height: 58, border: 'none', borderRadius: 16,
                cursor: purchasing || closing ? 'not-allowed' : 'pointer',
                background: purchasing || closing
                  ? 'rgba(245,239,228,0.08)'
                  : `linear-gradient(135deg, ${S.sun}, ${S.amber})`,
                border: '1px solid rgba(244,199,123,0.3)',
                fontFamily: S.sans, fontSize: 15, fontWeight: 600,
                color: purchasing || closing ? 'rgba(245,239,228,0.45)' : '#0E0C0A',
                transition: 'all 0.2s ease',
                boxShadow: purchasing || closing ? 'none' : `0 4px 24px rgba(244,199,123,0.35)`,
              }}>
                {purchasing ? 'Redirecting to checkout…' : 'Get Plus — $10/mo'}
              </button>
              <p style={{
                fontFamily: S.mono, fontSize: 10, letterSpacing: 1.2,
                color: 'rgba(245,239,228,0.35)', textAlign: 'center', marginTop: 10,
                textTransform: 'uppercase',
              }}>Secured by Stripe</p>
            </div>
          </div>

        </div>
      </div>

    </div>
  );
}
window.Paywall = Paywall;
