// anTee-Up landing page — sections (top of page).
// Motion-rich. See landing/motion.jsx for primitives.

const t = window.A;

// ─── Sticky nav (hides on scroll down, returns on scroll up) ─────
function Nav() {
  const [hidden, setHidden] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const lastY = React.useRef(0);
  React.useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      const dir = y > lastY.current && y > 120;
      setHidden(dir);
      setScrolled(y > 24);
      lastY.current = y;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      padding: scrolled ? '12px 48px' : '18px 48px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: scrolled
        ? 'rgba(9,25,16,0.85)'
        : 'linear-gradient(to bottom, rgba(9,25,16,0.92) 0%, rgba(9,25,16,0.0) 100%)',
      backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
      borderBottom: scrolled ? `1px solid ${t.divider}` : '1px solid transparent',
      transform: hidden ? 'translateY(-110%)' : 'translateY(0)',
      transition: `transform 350ms ${EASE_OUT_EXPO}, padding 220ms ${EASE_OUT_EXPO}, background 220ms linear, border-color 220ms linear`,
    }}>
      <a href="#top" style={{
        font: `700 22px/1 ${t.display}`, color: t.textPri,
        letterSpacing: '-0.3px', textDecoration: 'none',
        whiteSpace: 'nowrap', flexShrink: 0,
      }}>
        an<em style={{ color: t.gold, fontStyle: 'italic', fontWeight: 700 }}>Tee</em>-Up
      </a>
      <ul style={{ display: 'flex', gap: 32, listStyle: 'none', alignItems: 'center', margin: 0, padding: 0 }}>
        {[['Features','#features'],['Formats','#formats'],['How','#how'],['Pricing','#pricing'],['FAQ','#faq']].map(([l, h]) => (
          <li key={l}>
            <a href={h} style={{
              color: t.textSec, textDecoration: 'none',
              font: `400 13px/1 ${t.body}`,
              letterSpacing: '0.02em',
              position: 'relative',
              transition: `color 180ms ease`,
            }}
              onMouseEnter={e => e.currentTarget.style.color = t.gold}
              onMouseLeave={e => e.currentTarget.style.color = t.textSec}
            >{l}</a>
          </li>
        ))}
        <li>
          <MagneticButton href="https://app.anteeup.golf" target="_blank" rel="noopener noreferrer" strength={0.35} style={{
            background: t.gold, color: '#0E2219',
            padding: '10px 22px', borderRadius: 100,
            font: `600 13px/1 ${t.body}`, textDecoration: 'none', cursor: 'pointer',
            boxShadow: '0 1px 2px rgba(0,0,0,0.20), 0 8px 24px rgba(201,168,76,0.18)',
            letterSpacing: '0.01em',
          }}>Open the app</MagneticButton>
        </li>
      </ul>
    </nav>
  );
}

// ─── Hero ─────────────────────────────────────────────────────────
function Hero({ accentWord = '19th', heroVideoSrc, heroVideoPoster }) {
  const reduced = useReducedMotion();
  const heroRef = React.useRef(null);
  const glowRef = React.useRef(null);
  const phoneClusterRef = React.useRef(null);
  const copyRef = React.useRef(null);
  const [tiltRef, tiltTransform] = useTilt({ max: 5, perspective: 1400 });

  // Cursor glow — direct DOM mutation, no React state, no re-renders.
  React.useEffect(() => {
    if (reduced) return;
    let raf = null;
    const onMove = (e) => {
      if (!heroRef.current || !glowRef.current) return;
      const rect = heroRef.current.getBoundingClientRect();
      const x = e.clientX - rect.left - rect.width / 2;
      const y = Math.max(e.clientY - rect.top - 200, -200);
      if (raf) cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        if (glowRef.current) {
          glowRef.current.style.transform = `translate(${x - 260}px, ${y + 120}px)`;
        }
      });
    };
    window.addEventListener('pointermove', onMove, { passive: true });
    return () => {
      window.removeEventListener('pointermove', onMove);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [reduced]);

  // Scroll-driven parallax — direct DOM mutation.
  React.useEffect(() => {
    if (reduced) return;
    let raf = null;
    const update = () => {
      const y = window.scrollY;
      const phoneY = Math.min(y * 0.14, 100);
      const copyY = Math.min(y * 0.06, 40);
      if (phoneClusterRef.current) {
        phoneClusterRef.current.style.transform = `translate3d(0, ${-phoneY}px, 0)`;
      }
      if (copyRef.current) {
        copyRef.current.style.transform = `translate3d(0, ${-copyY * 0.5}px, 0)`;
      }
      raf = null;
    };
    const onScroll = () => { if (raf == null) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [reduced]);

  return (
    <section id="top" ref={heroRef} style={{
      minHeight: 'min(100vh, 940px)',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'flex-start',
      textAlign: 'center', padding: '128px 24px 60px',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Optional ambient video — golf course aerial, low opacity, tinted */}
      {heroVideoSrc && (
        <VideoBackdrop
          src={heroVideoSrc}
          poster={heroVideoPoster}
          opacity={0.32}
          blendMode="screen"
          filter="saturate(0.65) hue-rotate(-8deg) brightness(0.7)"
          overlay={`linear-gradient(180deg, rgba(9,25,16,0.55) 0%, rgba(9,25,16,0.74) 55%, ${t.bgDarkest} 100%)`}
          vignette
          style={{ animation: reduced ? 'none' : 'anteeFadeIn 1400ms ease-out both' }}
        />
      )}

      {/* grid */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage:
          'linear-gradient(rgba(201,168,76,0.06) 1px, transparent 1px),' +
          'linear-gradient(90deg, rgba(201,168,76,0.06) 1px, transparent 1px)',
        backgroundSize: '64px 64px',
        maskImage: 'radial-gradient(ellipse 80% 80% at 50% 40%, black 30%, transparent 100%)',
        WebkitMaskImage: 'radial-gradient(ellipse 80% 80% at 50% 40%, black 30%, transparent 100%)',
        pointerEvents: 'none',
      }}/>

      {/* static ambient glow */}
      <div style={{
        position: 'absolute', top: '8%', left: '50%', transform: 'translateX(-50%)',
        width: 900, height: 600,
        background: 'radial-gradient(ellipse, rgba(201,168,76,0.10) 0%, transparent 70%)',
        pointerEvents: 'none',
        animation: reduced ? 'none' : 'anteeDriftSlow 24s ease-in-out infinite',
      }}/>

      {/* cursor-following glow */}
      {!reduced && (
        <div ref={glowRef} style={{
          position: 'absolute', left: '50%', top: 0,
          width: 520, height: 520, pointerEvents: 'none',
          background: 'radial-gradient(circle, rgba(201,168,76,0.12) 0%, transparent 70%)',
          transform: 'translate(-260px, 120px)',
          transition: 'transform 1200ms cubic-bezier(0.16, 1, 0.3, 1)',
          willChange: 'transform',
        }}/>
      )}

      {/* hero copy block — eyebrow + headline + sub + CTAs all move together on scroll */}
      <div ref={copyRef} style={{
        position: 'relative',
        transition: 'transform 80ms linear',
        willChange: 'transform',
      }}>
      <BlurReveal delay={50} dy={10} duration={700} blur={3}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          font: `500 11px/1 ${t.body}`, letterSpacing: 3, textTransform: 'uppercase',
          color: t.gold,
          padding: '7px 18px',
          border: `1px solid rgba(201,168,76,0.28)`,
          borderRadius: 100,
          background: 'rgba(201,168,76,0.05)',
          position: 'relative',
        }}>
          <span style={{
            width: 6, height: 6, background: t.gold, borderRadius: 999,
            animation: 'anteeBlink 2.2s ease-in-out infinite',
            boxShadow: '0 0 8px rgba(201,168,76,0.55)',
          }}/>
          For the group that plays for money
        </div>
      </BlurReveal>

      <h1 style={{
        font: `700 clamp(54px, 8.6vw, 108px)/1.0 ${t.display}`,
        letterSpacing: '-2px', color: t.textPri,
        marginTop: 32, marginBottom: 0, position: 'relative',
        paddingBottom: '0.12em',
      }}>
        <WordReveal delay={180} step={85} duration={900} dy={28} blur={5}
          text={['Settle up']}/><br/>
        <WordReveal delay={180 + 2 * 85} step={85} duration={900} dy={28} blur={5}
          text={['before the ']}/>
        <WordReveal delay={180 + 4 * 85} step={0} duration={900} dy={28} blur={5}>
          <em style={{
            color: t.gold,
            fontStyle: 'italic',
            fontWeight: 700,
            display: 'inline-block',
            position: 'relative',
          }}>{accentWord}.</em>
        </WordReveal>
      </h1>

      <BlurReveal delay={620} dy={14} duration={900} blur={4}>
        <p style={{
          font: `400 clamp(16px, 1.4vw, 18px)/1.7 ${t.body}`,
          color: t.textSec, maxWidth: 580,
          margin: '24px auto 40px', position: 'relative',
        }}>
          Track Nassau, Skins, Wolf, and 10 other formats in real time.
          Live leaderboards, automatic wager settlement, and a wallet that handles every press, skin, and carry.
          Built for groups that have been doing this on paper.
        </p>
      </BlurReveal>

      <BlurReveal delay={780} dy={14} duration={800} blur={3}>
        <div style={{ display: 'flex', gap: 14, justifyContent: 'center', flexWrap: 'wrap', position: 'relative' }}>
          <Cta tone="gold" pre="No download · web app" name="Open anTee-Up" href="https://app.anteeup.golf" target="_blank" icon={<BrowserGlyph/>}/>
          <Cta tone="ghost" soon pre="Coming soon to" name="App Store"/>
          <Cta tone="ghost" soon pre="Coming soon to" name="Google Play"/>
        </div>
      </BlurReveal>

      <Reveal delay={920} dy={6} duration={700}>
        <div style={{
          font: `400 12px/1 ${t.body}`, color: t.textMuted,
          marginTop: 16, letterSpacing: '0.3px', position: 'relative',
        }}>Live now at <a href="https://app.anteeup.golf" target="_blank" rel="noopener noreferrer" style={{ color: t.gold, textDecoration: 'none', borderBottom: `1px solid rgba(201,168,76,0.4)` }}>app.anteeup.golf</a> · Free during early access · Cancel any time</div>
      </Reveal>
      </div>

      <BlurReveal delay={1040} dy={48} duration={1200} blur={8}>
        <div ref={phoneClusterRef} style={{
          display: 'flex', gap: 18, justifyContent: 'center', alignItems: 'flex-end',
          marginTop: 56, position: 'relative',
          transition: 'transform 80ms linear',
          willChange: 'transform',
        }}>
          <div style={{
            animation: reduced ? 'none' : 'anteeFloatGentle 7s ease-in-out infinite',
            animationDelay: '0s',
          }}>
            <PhoneShell w={180} h={380} image="assets/screens/home.png" alt="Today — round in progress"/>
          </div>
          <div ref={tiltRef} style={{
            transform: tiltTransform,
            transition: `transform 200ms ${EASE_OUT_EXPO}`,
            willChange: 'transform',
            transformStyle: 'preserve-3d',
          }}>
            <div style={{
              animation: reduced ? 'none' : 'anteeFloat 5.5s ease-in-out infinite',
            }}>
              <PhoneShell w={210} h={440} featured image="assets/screens/tourn.png" alt="Summer Series tournament leaderboard"/>
            </div>
          </div>
          <div style={{
            animation: reduced ? 'none' : 'anteeFloatGentle 7s ease-in-out infinite',
            animationDelay: '-3.5s',
          }}>
            <PhoneShell w={180} h={380} image="assets/screens/groups.png" alt="Saturday Crew — your group"/>
          </div>
        </div>
      </BlurReveal>
    </section>
  );
}

function Cta({ tone, pre, name, href, soon, target, icon }) {
  const isGold = tone === 'gold';
  const isSoon = !!soon;
  const styles = isGold
    ? { background: t.gold, color: '#0E2219', boxShadow: '0 1px 2px rgba(0,0,0,0.20), 0 14px 36px rgba(201,168,76,0.22)' }
    : isSoon
    ? { background: 'transparent', color: 'rgba(244,240,225,0.55)', border: `1px solid rgba(201,168,76,0.16)`, cursor: 'default' }
    : { background: 'transparent', color: t.textPri, border: `1px solid rgba(201,168,76,0.30)` };
  return (
    <MagneticButton
      strength={isSoon ? 0 : 0.25}
      href={href}
      target={target}
      rel={target === '_blank' ? 'noopener noreferrer' : undefined}
      style={{
        padding: '13px 26px', borderRadius: 100, textDecoration: 'none', cursor: isSoon ? 'default' : 'pointer',
        transition: `box-shadow .25s ease, background .2s ease, transform 400ms ${EASE_OUT_EXPO}`,
        display: 'inline-flex', alignItems: 'center', gap: 12,
        ...styles,
      }}
    >
      {icon && (
        <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }} aria-hidden="true">
          {icon}
        </span>
      )}
      <span style={{ display: 'flex', flexDirection: 'column', textAlign: 'left' }}>
        <span style={{ font: `400 10px/1.1 ${t.body}`, opacity: 0.7, letterSpacing: 0.3 }}>{pre}</span>
        <span style={{ font: `600 17px/1.2 ${t.body}`, marginTop: 2 }}>{name}</span>
      </span>
    </MagneticButton>
  );
}

// Browser glyph for the "Open the web app" CTA
function BrowserGlyph({ color = '#0E2219' }) {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2"/>
      <path d="M3 9h18"/>
      <circle cx="6.5" cy="7" r="0.6" fill={color} stroke="none"/>
      <circle cx="8.7" cy="7" r="0.6" fill={color} stroke="none"/>
    </svg>
  );
}

// ─── Trust bar (counts-up) ────────────────────────────────────────
function TrustBar() {
  const items = [
    { num: 60,    suffix: 's',  label: 'round setup time' },
    { num: 13,    suffix: '',   label: 'game formats' },
    { num: 4200,  suffix: '+',  label: 'rounds tracked' },
    { num: 100,   suffix: '%',  label: 'auto-settled bets' },
  ];
  return (
    <div style={{
      background: t.bgDark,
      borderTop: `1px solid ${t.divider}`, borderBottom: `1px solid ${t.divider}`,
      padding: '32px 48px',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 1,
        background: 'linear-gradient(90deg, transparent 0%, rgba(27,58,45,0.10) 50%, transparent 100%)',
      }}/>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        maxWidth: 1080, margin: '0 auto', flexWrap: 'wrap', gap: 24,
      }}>
        {items.map((it, i) => (
          <React.Fragment key={it.label}>
            <TrustItem {...it} delay={i * 100}/>
            {i < items.length - 1 && (
              <div style={{ width: 1, height: 44, background: t.divider }}/>
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function TrustItem({ num, suffix, label, delay }) {
  const [ref, value] = useCounter(num, { duration: 1600 });
  return (
    <Reveal delay={delay} dy={20} duration={700}>
      <div ref={ref} style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
        padding: '0 32px', minWidth: 180,
      }}>
        <div style={{
          font: `700 44px/1 ${t.display}`, color: t.gold,
          letterSpacing: '-1.2px', display: 'flex', alignItems: 'baseline', gap: 1,
          fontVariantNumeric: 'tabular-nums',
        }}>
          <span>{value.toLocaleString()}</span>
          <span style={{ fontFamily: t.display, fontStyle: 'italic', fontWeight: 500, fontSize: 26, lineHeight: 1, color: t.gold }}>{suffix}</span>
        </div>
        <div style={{
          font: `500 11px/1.3 ${t.body}`, color: t.textSec,
          textTransform: 'uppercase', letterSpacing: 2.5,
        }}>{label}</div>
      </div>
    </Reveal>
  );
}

// ─── Section scaffolding ───────────────────────────────────────────
function Section({ id, bg, children, padX = 24, padY = 108 }) {
  return (
    <section id={id} style={{
      padding: `${padY}px ${padX}px`, background: bg, position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 1,
        background: 'linear-gradient(90deg, transparent 0%, rgba(27,58,45,0.10) 50%, transparent 100%)',
      }}/>
      {children}
    </section>
  );
}

function SectionHead({ eyebrow, title, body, align = 'center' }) {
  return (
    <div style={{ textAlign: align, marginBottom: 64 }}>
      <BlurReveal dy={10} duration={700} blur={3}>
        <div style={{
          font: `500 11px/1 ${t.body}`, letterSpacing: 3, textTransform: 'uppercase',
          color: t.gold, marginBottom: 22,
        }}>{eyebrow}</div>
      </BlurReveal>
      <BlurReveal delay={120} dy={22} duration={900} blur={5}>
        <h2 style={{
          font: `700 clamp(36px, 5.2vw, 64px)/1.05 ${t.display}`,
          color: t.textPri, letterSpacing: '-1.2px',
          margin: '0 auto 22px', maxWidth: 800,
        }}>{title}</h2>
      </BlurReveal>
      <BlurReveal delay={260} dy={14} duration={800} blur={3}>
        <p style={{
          font: `300 17px/1.65 ${t.body}`, color: t.textSec,
          maxWidth: 560, margin: align === 'center' ? '0 auto' : '0',
        }}>{body}</p>
      </BlurReveal>
    </div>
  );
}

// ─── Features ──────────────────────────────────────────────────────
function FeatureCard({ icon, title, body }) {
  const [hovered, setHovered] = React.useState(false);
  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        background: hovered ? t.cardBgRaised : t.cardBg,
        border: `1px solid ${hovered ? t.cardBorderHover : t.cardBorder}`,
        borderRadius: 22, padding: '36px 32px',
        transform: hovered ? 'translateY(-5px)' : 'translateY(0)',
        boxShadow: hovered
          ? '0 1px 2px rgba(0,0,0,0.30), 0 20px 56px rgba(0,0,0,0.40)'
          : '0 1px 2px rgba(0,0,0,0.20)',
        transition: `border-color .35s ease, box-shadow .35s ease, transform .35s ${EASE_OUT_EXPO}, background .35s ease`,
        position: 'relative', overflow: 'hidden',
      }}>
      {/* hover sheen */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(circle 260px at 50% 0%, rgba(201,168,76,0.12), transparent)',
        opacity: hovered ? 1 : 0,
        transition: 'opacity .35s ease',
      }}/>
      <div style={{
        width: 52, height: 52, borderRadius: 14,
        background: hovered ? 'rgba(201,168,76,0.14)' : 'rgba(201,168,76,0.08)',
        border: `1px solid ${hovered ? 'rgba(201,168,76,0.32)' : 'rgba(201,168,76,0.18)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: t.gold, marginBottom: 24, position: 'relative',
        transform: hovered ? 'rotate(-4deg)' : 'rotate(0)',
        transition: `transform .35s ${EASE_OUT_EXPO}, background .35s ease, border-color .35s ease`,
      }}>{icon}</div>
      <div style={{ font: `600 22px/1.25 ${t.display}`, color: t.textPri, marginBottom: 10, position: 'relative', letterSpacing: '-0.2px' }}>{title}</div>
      <p style={{ font: `300 14px/1.7 ${t.body}`, color: t.textSec, margin: 0, position: 'relative' }}>{body}</p>
    </div>
  );
}

function Features() {
  const cards = [
    [<AIcons.flag/>,     '13 game formats',         "Nassau, Skins, Wolf, Stableford, Presses, Birdie Pool, Vegas, Bingo Bango Bongo, Snake, Hammer, and more. Stack multiple games in the same round — every hole is tracked automatically."],
    [<AIcons.activity/>, 'Live leaderboards',      "Scores sync instantly across every player's phone — iOS and Android. The moment a score drops, the leaderboard updates for everyone."],
    [<AIcons.wallet/>,   'Wager wallet',           "A running ledger for every side bet, press, and carryover skin. When the round ends, the app shows exactly who owes who."],
    [<AIcons.shield/>,   'Handicap-aware scoring', "Each player enters their index once. anTee-Up allocates strokes per-hole automatically using the course handicap — every player competes on a level field, no manual math."],
    [<AIcons.users/>,    'Groups & seasons',       "Create your crew, schedule recurring rounds, track season standings. Running a Saturday game? Set it up once."],
    [<AIcons.clock/>,    'Round setup in 60s',     "Set your course, choose your format, name your stakes, send invites. Nobody waits on the first tee while you configure a scoring app."],
  ];
  return (
    <Section id="features" bg={t.bgPrimary}>
      <SectionHead
        eyebrow="Everything your group needs"
        title={<>Built for the way<br/>serious golfers play</>}
        body="Thirteen formats. Live leaderboards. Automatic settlement. Everything your group has been doing on paper or in a group chat — done right."
      />
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20,
        maxWidth: 1080, margin: '0 auto',
      }}>
        <Stagger step={80} dy={32}>
          {cards.map(([icon, ttl, body]) => (
            <FeatureCard key={ttl} icon={icon} title={ttl} body={body}/>
          ))}
        </Stagger>
      </div>
    </Section>
  );
}

// ─── Formats (interactive picker with animated indicator) ─────────
function Formats() {
  const formats = [
    { name: 'Nassau',      desc: 'Three matches in one — front nine, back nine, overall 18. The classic. Bet $5 / $5 / $5 and your front-nine loss can carry into the back.' },
    { name: 'Skins',       desc: 'Lowest net score wins the hole. Tied holes "carry" until somebody wins outright. By the back nine, the pot can be huge.' },
    { name: 'Wolf',        desc: 'A rotating "wolf" each hole picks a partner off the tee — or goes solo for double points. Almost impossible to track on paper. anTee-Up does it for you.' },
    { name: 'Match Play',  desc: 'Player vs. player, hole by hole. Win the hole, you go 1-up. Lose, you go 1-down. First to be up by more holes than remain wins.' },
    { name: 'Stroke Play', desc: 'Total strokes over 18. Net or gross. The straightforward one. Use it when nobody wants to think about side games.' },
    { name: 'Stableford',  desc: "Points per hole based on net score relative to par. Triple bogey doesn't blow up your card — it just stops scoring." },
    { name: 'Presses',     desc: 'A new bet inside the existing one. Down 2 going into the 6th? Press — start a new match worth half the original stake from this hole on.' },
    { name: 'Snake',       desc: "Whoever three-putts last is \"holding the snake\" — pays a small amount at round's end. The most-feared putt in golf isn't the four-footer for par." },
    { name: 'Birdie Pool', desc: 'Pre-round pot. Most birdies wins. Tied → split. Some groups add: bogey-free 18 doubles your share.' },
    { name: 'Bingo Bango Bongo', desc: 'Three points per hole: first on, closest once all are on, first in. Rewards short game and pace, not just length. Beloved among mixed-handicap groups.' },
  ];
  const [active, setActive] = React.useState(0);
  const listRef = React.useRef(null);
  const [indicator, setIndicator] = React.useState({ top: 0, height: 0 });
  React.useLayoutEffect(() => {
    const el = listRef.current?.children[active];
    if (!el) return;
    setIndicator({ top: el.offsetTop, height: el.offsetHeight });
  }, [active]);

  return (
    <Section id="formats" bg={t.bgDarkest}>
      <SectionHead
        eyebrow="Thirteen formats. One app."
        title={<>Pick the game.<br/>The rest is automatic.</>}
        body="From the classic Nassau to formats most apps don't touch — Wolf, Vegas, Hammer, Snake. Tap any to see how it works."
      />
      <div className="split-grid" style={{
        display: 'grid', gridTemplateColumns: '320px 1fr', gap: 28,
        maxWidth: 1080, margin: '0 auto',
      }}>
        {/* picker */}
        <div ref={listRef} style={{
          display: 'flex', flexDirection: 'column', gap: 6, position: 'relative',
        }}>
          {/* animated indicator */}
          <div style={{
            position: 'absolute', left: 0, right: 0,
            top: indicator.top, height: indicator.height,
            background: 'rgba(201,168,76,0.08)',
            border: '1px solid rgba(201,168,76,0.30)',
            borderRadius: 14,
            transition: `top 450ms ${EASE_OUT_EXPO}, height 450ms ${EASE_OUT_EXPO}`,
            pointerEvents: 'none',
            boxShadow: '0 1px 2px rgba(0,0,0,0.25)',
          }}/>
          {formats.map((f, i) => (
            <button key={f.name}
              onClick={() => setActive(i)}
              style={{
                textAlign: 'left', cursor: 'pointer',
                background: 'transparent',
                border: '1px solid transparent',
                borderRadius: 14, padding: '15px 20px',
                font: `500 16px/1 ${t.body}`,
                color: i === active ? t.gold : t.textSec,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                transition: `color 280ms ease`,
                position: 'relative', zIndex: 1,
                letterSpacing: '0.005em',
              }}
              onMouseEnter={e => i !== active && (e.currentTarget.style.color = t.textPri)}
              onMouseLeave={e => i !== active && (e.currentTarget.style.color = t.textSec)}>
              {f.name}
              <span style={{
                color: t.gold,
                opacity: i === active ? 1 : 0,
                transform: i === active ? 'translateX(0)' : 'translateX(-6px)',
                transition: `opacity 280ms ease, transform 280ms ${EASE_OUT_EXPO}`,
              }}><AIcons.arrow/></span>
            </button>
          ))}
        </div>

        {/* description card with crossfade swap */}
        <div style={{
          background: `
            radial-gradient(ellipse at 80% -10%, rgba(201,168,76,0.18), transparent 55%),
            radial-gradient(ellipse at 10% 110%, rgba(60,140,90,0.16), transparent 60%),
            linear-gradient(165deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 35%, rgba(0,0,0,0.18) 100%),
            ${t.cardBg}
          `,
          border: `1px solid ${t.cardBorder}`,
          borderRadius: 22, padding: 40,
          boxShadow: `
            0 1px 2px rgba(0,0,0,0.30),
            0 24px 60px rgba(0,0,0,0.45),
            0 0 0 1px rgba(201,168,76,0.06) inset,
            0 1px 0 rgba(255,255,255,0.06) inset,
            0 -40px 80px rgba(0,0,0,0.25) inset
          `,
          display: 'flex', flexDirection: 'column', justifyContent: 'center',
          minHeight: 380, position: 'relative', overflow: 'hidden',
        }}>
          {/* faint grid texture — anchors depth */}
          <div style={{
            position: 'absolute', inset: 0,
            backgroundImage: 'linear-gradient(rgba(201,168,76,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(201,168,76,0.04) 1px, transparent 1px)',
            backgroundSize: '40px 40px',
            maskImage: 'radial-gradient(ellipse at 50% 50%, black 30%, transparent 75%)',
            WebkitMaskImage: 'radial-gradient(ellipse at 50% 50%, black 30%, transparent 75%)',
            pointerEvents: 'none',
            opacity: 0.55,
          }}/>
          {/* gold radial bloom — anchored top-right */}
          <div style={{
            position: 'absolute', top: -80, right: -100, width: 380, height: 380,
            background: 'radial-gradient(circle, rgba(201,168,76,0.22), transparent 65%)',
            filter: 'blur(8px)',
            pointerEvents: 'none',
          }}/>
          {/* hairline gold edge along the top */}
          <div style={{
            position: 'absolute', top: 0, left: '12%', right: '12%', height: 1,
            background: 'linear-gradient(90deg, transparent, rgba(201,168,76,0.55), transparent)',
            pointerEvents: 'none',
          }}/>
          <FormatDescription key={active} format={formats[active]} index={active} total={formats.length}/>
        </div>
      </div>
    </Section>
  );
}

// Description block re-mounts on key change → entry animation re-runs.
function FormatDescription({ format, index, total }) {
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => {
    let raf2;
    const raf1 = requestAnimationFrame(() => {
      raf2 = requestAnimationFrame(() => setMounted(true));
    });
    return () => { cancelAnimationFrame(raf1); if (raf2) cancelAnimationFrame(raf2); };
  }, []);
  const baseStyle = {
    opacity: mounted ? 1 : 0,
    transform: mounted ? 'translateY(0px)' : 'translateY(14px)',
    transition: `opacity 500ms ${EASE_OUT_EXPO}, transform 500ms ${EASE_OUT_EXPO}`,
    willChange: 'opacity, transform',
  };
  return (
    <>
      <div style={{
        font: `500 11px/1 ${t.body}`, letterSpacing: 3,
        textTransform: 'uppercase', color: t.gold, marginBottom: 18,
        ...baseStyle,
        transitionDelay: '0ms',
      }}>Format · {String(index + 1).padStart(2, '0')} of {total}</div>
      <h3 style={{
        font: `700 44px/1.05 ${t.display}`, color: t.textPri,
        letterSpacing: '-1px', margin: 0, marginBottom: 20,
        ...baseStyle,
        transition: `opacity 600ms ${EASE_OUT_EXPO} 60ms, transform 600ms ${EASE_OUT_EXPO} 60ms`,
      }}>{format.name}</h3>
      <p style={{
        font: `300 17px/1.7 ${t.body}`, color: t.textSec, margin: 0, maxWidth: 520,
        ...baseStyle,
        transition: `opacity 600ms ${EASE_OUT_EXPO} 130ms, transform 600ms ${EASE_OUT_EXPO} 130ms`,
      }}>{format.desc}</p>
      <div style={{
        display: 'flex', gap: 14, marginTop: 32,
        paddingTop: 24, borderTop: `1px solid ${t.divider}`,
        flexWrap: 'wrap',
        ...baseStyle,
        transition: `opacity 600ms ${EASE_OUT_EXPO} 200ms, transform 600ms ${EASE_OUT_EXPO} 200ms`,
      }}>
        <Badge>Auto-scored</Badge>
        <Badge>Handicap-aware</Badge>
        <Badge>Settled in-app</Badge>
      </div>
    </>
  );
}

function Badge({ children }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '6px 14px', borderRadius: 999,
      background: 'rgba(201,168,76,0.10)',
      border: '1px solid rgba(201,168,76,0.28)',
      color: t.gold, font: `500 11px/1 ${t.body}`, letterSpacing: 0.3,
    }}>
      <span style={{ color: t.gold }}><AIcons.check/></span>
      {children}
    </div>
  );
}

Object.assign(window, { Nav, Hero, TrustBar, Section, SectionHead, Features, Formats, Cta, Badge });
