// sections.jsx — Nav, Hero, Ticker, How-it-works, Footer
// (Battle, Gacha, Pokedex, Tournaments live in other files)

function Pokeball({ size = 240, shake = false, spin = false, red, white }) {
  return (
    <div className={`pokeball ${shake ? 'pokeball--shake' : ''} ${spin ? 'pokeball--spin' : ''}`}
         style={{ '--pb-size': `${size}px`, '--pb-red': red, '--pb-white': white }}>
      <div className="pokeball__top"></div>
      <div className="pokeball__bot"></div>
      <div className="pokeball__band"></div>
      <div className="pokeball__btn"></div>
    </div>
  );
}

function Nav({ onConnect, t }) {
  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(12,15,30,.78)',
      backdropFilter: 'blur(12px)',
      borderBottom: '3px solid var(--pd-line)',
    }}>
      <div className="pd-wrap row between center" style={{ padding: '14px 0' }}>
        <a href="#top" style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
          <Pokeball size={36} red="var(--pd-red)" white="var(--pd-paper)" />
          <span className="pixel" style={{ fontSize: 16, color: 'var(--pd-paper)' }}>
            POKE<span style={{ color: 'var(--pd-yellow)' }}>DEX</span>
          </span>
          <span className="pd-chip" style={{ color: 'var(--pd-cyan)', borderColor: 'var(--pd-cyan)', marginLeft: 6 }}>
            v.1 · SOLANA
          </span>
        </a>
        <div className="row" style={{ gap: 28 }}>
          {['Mechanic', 'Players', 'Dex', 'Battle', 'Gacha', 'Arena'].map(l => (
            <a key={l} href={`#${l.toLowerCase()}`} className="pixel"
               style={{ fontSize: 11, color: 'var(--pd-paper)', textDecoration: 'none', letterSpacing: '.1em' }}>
              {l.toUpperCase()}
            </a>
          ))}
        </div>
        <div className="row" style={{ gap: 10 }}>
          <a href="game/" className="pd-btn pd-btn--green pd-btn--sm" style={{ textDecoration: 'none' }}>▶ PLAY</a>
          <button className="pd-btn pd-btn--ghost pd-btn--sm nav-pumpfun">PUMP.FUN ↗</button>
          <button className="pd-btn pd-btn--yellow pd-btn--sm" onClick={onConnect}>
            {t.connected ? `◉ 7g${'…'}Kx9` : 'CONNECT'}
          </button>
        </div>
      </div>
    </nav>
  );
}

function Hero({ t, marketCap, onCatch }) {
  const starters = [POKEDEX[0], POKEDEX[3], POKEDEX[6]];
  useHeroEntrance('.hero-stagger');
  return (
    <section id="top" className="hero-section" style={{ position: 'relative', overflow: 'hidden' }}>
      <GradientOrbs />
      <AnimatedGrid color="rgba(255,206,58,.05)" size={56} speed={50} />
      <Sparkles count={36} />
      <Spotlight color="rgba(255,206,58,.10)" size={700} />
      <div className="starfield" />
      <div className="pd-wrap hero-wrap" style={{ position: 'relative', zIndex: 3 }}>
        <div className="hero-grid">
          <div>
            <div className="row hero-stagger" style={{ gap: 8, marginBottom: 18 }}>
              <span className="pd-chip" style={{ color: 'var(--pd-yellow)' }}>
                <span className="pulse-dot" style={{ background: 'var(--pd-yellow)' }}></span>
                LIVE ON PUMP.FUN
              </span>
              <span className="pd-chip" style={{ color: 'var(--pd-paper)' }}>151 CREATURES</span>
              <span className="pd-chip" style={{ color: 'var(--pd-cyan)' }}>GEN&nbsp;1</span>
            </div>
            <h1 className="pd-h1 hero-stagger hero-title" style={{ margin: 0, color: 'var(--pd-paper)' }}>
              CATCH&nbsp;<span style={{ color: 'var(--pd-red)' }}>'EM</span><br/>
              TRADE&nbsp;<span style={{ color: 'var(--pd-yellow)' }}>'EM</span><br/>
              FLEX&nbsp;<Shimmer color="#ffce3a" from="#5ad8ff">'EM</Shimmer>
            </h1>
            <p className="hero-stagger hero-lede" style={{ lineHeight: 1.5, color: 'rgba(241,233,210,.78)', maxWidth: 520, marginTop: 18, marginBottom: 0 }}>
              One mainnet token. <b style={{ color: 'var(--pd-paper)' }}>151 creature tokens.</b> Buy a creature, the rest auto-rebalance. Battle, level up, and build your Dex.
            </p>
            <div className="row hero-stagger" style={{ gap: 12, marginTop: 22, flexWrap: 'wrap' }}>
              <Magnetic><a href="#dex" className="pd-btn">▶ ENTER THE DEX</a></Magnetic>
              <Magnetic><a href="#gacha" className="pd-btn pd-btn--yellow">◎ OPEN A POKEBALL</a></Magnetic>
              <a href="#mechanic" className="pd-btn pd-btn--ghost">HOW IT WORKS</a>
            </div>

            {/* Stat row */}
            <div className="row hero-stagger hero-stats" style={{ gap: 24, marginTop: 28, flexWrap: 'wrap' }}>
              {[
                { k: 'MARKET CAP', v: marketCap, prefix: '$', suffix: 'M', dec: 2, c: 'var(--pd-yellow)' },
                { k: 'HOLDERS',     v: 42118,    suffix: '',  dec: 0, c: 'var(--pd-cyan)' },
                { k: 'BATTLES /24H', v: 8704,     suffix: '',  dec: 0, c: 'var(--pd-green)' },
                { k: 'CAUGHT',      v: 623491,   suffix: '',  dec: 0, c: 'var(--pd-pink)' },
              ].map(s => (
                <div key={s.k} className="col" style={{ gap: 4 }}>
                  <span className="pixel" style={{ fontSize: 9, color: 'rgba(241,233,210,.55)', letterSpacing: '.12em' }}>{s.k}</span>
                  <span className="mono hero-stat-num" style={{ color: s.c }}>
                    <AnimatedNumber value={s.v} decimals={s.dec} prefix={s.prefix || ''} suffix={s.suffix} />
                  </span>
                </div>
              ))}
            </div>
          </div>

          {/* Right side: hero pokeball + starter trio */}
          <div className="col center hero-stagger hero-right" style={{ gap: 24 }}>
            <div className="float hero-pokeball">
              <Pokeball size={240} shake red="var(--pd-red)" white="var(--pd-paper)" />
            </div>
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, width: '100%', maxWidth: 460
            }}>
              {starters.map(s => (
                <TiltCard key={s.n} max={12}>
                  <StarterCard entry={s} onClick={() => onCatch(s)} />
                </TiltCard>
              ))}
            </div>
            <span className="pixel" style={{ fontSize: 10, color: 'var(--pd-yellow)', letterSpacing: '.16em' }}>
              ▼ CHOOSE YOUR STARTER ▼
            </span>
          </div>
        </div>
      </div>
    </section>
  );
}

function StarterCard({ entry, onClick }) {
  const primary = entry.types[0].color;
  const secondary = entry.types[1] && entry.types[1].color;
  return (
    <div className="pd-card" style={{ padding: 12, cursor: 'pointer' }} onClick={onClick}>
      <div className="row between" style={{ alignItems: 'center' }}>
        <span className="mono" style={{ fontSize: 14, opacity: .55 }}>#{String(entry.n).padStart(3, '0')}</span>
        <span className="pd-chip" style={{ color: primary, fontSize: 8 }}>{entry.types[0].name}</span>
      </div>
      <div className="center" style={{ display: 'flex', height: 90, marginTop: 4 }}>
        <Sprite seed={entry.seed} n={entry.n} primary={primary} secondary={secondary} size={50} />
      </div>
      <div className="pixel" style={{ fontSize: 10, textAlign: 'center', marginTop: 6 }}>
        {entry.name.toUpperCase()}
      </div>
      <div className="row between" style={{ marginTop: 6 }}>
        <span className="mono" style={{ fontSize: 13 }}>◎ {fmtPrice(entry.price)}</span>
        <span className="mono" style={{ fontSize: 12, color: entry.delta >= 0 ? 'var(--pd-up)' : 'var(--pd-down)' }}>
          {fmtDelta(entry.delta)}
        </span>
      </div>
    </div>
  );
}

function MarqueeTicker() {
  // Build ticker items dynamically from the live dex (uses real names after fetch)
  const items = React.useMemo(() => {
    const picks = [POKEDEX[0], POKEDEX[149], POKEDEX[143], POKEDEX[93], POKEDEX[24], POKEDEX[144], POKEDEX[6], POKEDEX[150]];
    const out = ['◉ POKEDEX  $0.00482  +14.2%'];
    picks.forEach(p => {
      if (!p) return;
      const sign = p.delta >= 0 ? '+' : '−';
      out.push(`#${String(p.n).padStart(3, '0')} ${p.name.toUpperCase()}  ◎${fmtPrice(p.price)}  ${sign}${Math.abs(p.delta).toFixed(1)}%`);
    });
    out.push('◉ 8,704 BATTLES IN LAST 24H');
    out.push('◉ NEXT POKEBALL DROP IN 02:14:33');
    return out;
  }, []);

  return (
    <div className="ticker">
      <div className="ticker__track">
        {[...items, ...items].map((s, i) => (
          <span className="ticker__item" key={i}>
            <span style={{ color: 'var(--pd-yellow)' }}>★</span>{s}
          </span>
        ))}
      </div>
    </div>
  );
}

function Mechanic() {
  return (
    <section id="mechanic" className="section grid-bg">
      <div className="pd-wrap">
        <Reveal>
          <div className="section-label">The Mechanic</div>
          <h2 className="pd-h2" style={{ margin: '0 0 12px', color: 'var(--pd-paper)', maxWidth: 880 }}>
            ONE TOKEN PUMPS. THE WHOLE DEX MOVES.
          </h2>
          <p style={{ fontSize: 17, color: 'rgba(241,233,210,.7)', maxWidth: 680, marginBottom: 40 }}>
            Every creature has its own market. Trading directly impacts only that creature.
            But all 151 creatures share a single index — <b style={{color:'var(--pd-yellow)'}}>$POKEDEX</b> — which auto-rebalances based on each creature's share of total market cap. Fees from every trade flow into the index pool.
          </p>
        </Reveal>

        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 32 }}>
          {/* Left: live rebalance illustration */}
          <Reveal delay={0.1}>
            <BeamBorder color="#ffce3a" color2="#e53935" duration={5}>
              <RebalanceDiagram />
            </BeamBorder>
          </Reveal>

          {/* Right: rules */}
          <div className="col" style={{ gap: 14 }}>
            {[
              { n: '01', t: 'One PokeDex Index', d: 'The mainnet $POKEDEX token tracks the weighted market cap of all 151 creatures. Hold the Dex, hold the genre.' },
              { n: '02', t: '151 Creature Tokens', d: 'No mint, no whitelist, no rugs. Single-sided SOL pairs. One creature, one token, one address.' },
              { n: '03', t: 'Auto-Pondered Rebalance', d: 'Buy #006 Charizard? Its price moves. The rest of the dex rebalances proportional to their share. Trade fees flow back to $POKEDEX holders.' },
              { n: '04', t: 'Utility = Battle, Level, Flex', d: 'Holding a creature lets you fight, level it up, enter tournaments — and show off your roster on-chain.' },
            ].map((r, i) => (
              <Reveal key={r.n} delay={i * 0.05}>
                <TiltCard max={4} scale={1}>
                  <div className="pd-card pd-card--dark row" style={{ padding: 18, gap: 18, alignItems: 'flex-start' }}>
                    <div className="pixel" style={{ fontSize: 24, color: 'var(--pd-yellow)', lineHeight: 1, minWidth: 50 }}>{r.n}</div>
                    <div>
                      <div className="pixel" style={{ fontSize: 13, color: 'var(--pd-paper)', marginBottom: 6 }}>{r.t.toUpperCase()}</div>
                      <div style={{ fontSize: 14.5, color: 'rgba(241,233,210,.72)', lineHeight: 1.5 }}>{r.d}</div>
                    </div>
                  </div>
                </TiltCard>
              </Reveal>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function RebalanceDiagram() {
  const [hot, setHot] = React.useState(5);
  const tokens = React.useMemo(() => {
    const picks = [POKEDEX[149], POKEDEX[143], POKEDEX[150], POKEDEX[93], POKEDEX[129], POKEDEX[24]];
    const colors = ['#ffce3a', '#ff5a3c', '#4aa6ff', '#62c46b', '#7a87b8', '#a259ff'];
    const weights = [0.18, 0.14, 0.12, 0.10, 0.08, 0.06];
    const arr = picks.map((p, i) => ({
      id: i,
      name: (p?.name || `#${i+1}`).toUpperCase(),
      color: colors[i],
      weight: weights[i],
    }));
    arr.push({ id: 6, name: '...145 OTHERS', color: '#5ad8ff', weight: 0.32 });
    return arr;
  }, []);

  React.useEffect(() => {
    const i = setInterval(() => setHot(h => (h + 1) % tokens.length), 1800);
    return () => clearInterval(i);
  }, []);

  return (
    <div className="pd-card pd-card--dark" style={{ padding: 24 }}>
      <div className="row between" style={{ marginBottom: 18 }}>
        <div className="pixel" style={{ fontSize: 11, color: 'var(--pd-yellow)', letterSpacing: '.14em' }}>
          $POKEDEX · WEIGHTED INDEX
        </div>
        <div className="mono" style={{ fontSize: 14, color: 'var(--pd-cyan)' }}>
          <span className="pulse-dot" style={{ marginRight: 6 }}></span> AUTO-BALANCING
        </div>
      </div>

      {/* Stacked bar */}
      <div style={{
        display: 'flex', width: '100%', height: 36,
        border: '3px solid var(--pd-line)', borderRadius: 4, overflow: 'hidden',
      }}>
        {tokens.map((tk, i) => (
          <div
            key={tk.id}
            onMouseEnter={() => setHot(i)}
            style={{
              flex: tk.weight,
              background: tk.color,
              borderRight: i < tokens.length - 1 ? '2px solid var(--pd-line)' : 0,
              transition: 'filter .25s, flex .6s cubic-bezier(.4,0,.2,1)',
              filter: hot === i ? 'brightness(1.1)' : 'brightness(.78)',
              cursor: 'pointer',
            }}
            title={tk.name}
          />
        ))}
      </div>

      {/* Token list */}
      <div className="col" style={{ marginTop: 18, gap: 6 }}>
        {tokens.map((tk, i) => (
          <div key={tk.id} className="row between" style={{
            padding: '8px 12px',
            background: hot === i ? 'rgba(255,206,58,.08)' : 'transparent',
            borderRadius: 4,
            transition: 'background .2s',
          }}>
            <div className="row" style={{ gap: 10, alignItems: 'center' }}>
              <div style={{ width: 14, height: 14, background: tk.color, border: '2px solid var(--pd-line)' }} />
              <span className="pixel" style={{ fontSize: 10, color: 'var(--pd-paper)' }}>{tk.name}</span>
            </div>
            <div className="row" style={{ gap: 16, alignItems: 'center' }}>
              <span className="mono" style={{ fontSize: 14, color: 'rgba(241,233,210,.7)' }}>{(tk.weight * 100).toFixed(1)}%</span>
              <span className="mono" style={{
                fontSize: 13, width: 64, textAlign: 'right',
                color: hot === i ? 'var(--pd-up)' : 'rgba(241,233,210,.45)',
              }}>{hot === i ? '+8.42%' : '+0.12%'}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="mono" style={{ fontSize: 13, color: 'rgba(241,233,210,.45)', marginTop: 12 }}>
        // when one creature pumps, the others rebalance proportionally.<br/>
        // 1% trade fee → 0.6% to $POKEDEX holders, 0.4% to creature LP.
      </div>
    </div>
  );
}

function Footer() {
  return (
    <footer className="section-tight" style={{
      borderTop: '4px solid var(--pd-line)',
      background: 'var(--pd-bg-2)',
    }}>
      <div className="pd-wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 40 }}>
          <div className="col" style={{ gap: 16 }}>
            <div className="row" style={{ gap: 12, alignItems: 'center' }}>
              <Pokeball size={42} red="var(--pd-red)" white="var(--pd-paper)" />
              <span className="pixel" style={{ fontSize: 16, color: 'var(--pd-paper)' }}>
                POKE<span style={{ color: 'var(--pd-yellow)' }}>DEX</span>
              </span>
            </div>
            <p style={{ fontSize: 14, color: 'rgba(241,233,210,.55)', maxWidth: 380, lineHeight: 1.6 }}>
              The first auto-rebalanced creature index on Solana. 151 monsters, one Dex. Hold, battle, flex.
            </p>
            <div className="row" style={{ gap: 8 }}>
              {['X', 'TG', 'DEX', 'GH'].map(s => (
                <div key={s} className="pixel center" style={{
                  display: 'inline-flex', width: 38, height: 38,
                  fontSize: 9, border: '2px solid var(--pd-paper)', color: 'var(--pd-paper)',
                  borderRadius: 4, cursor: 'pointer',
                }}>{s}</div>
              ))}
            </div>
          </div>
          {[
            { h: 'PROTOCOL', l: ['Mechanic', 'Tokenomics', 'Audit', 'Whitepaper'] },
            { h: 'PLAY',     l: ['Pokedex',  'Battle',     'Gacha',  'Tournaments'] },
            { h: 'COMMUNITY', l: ['Telegram', 'Twitter',    'Discord', 'DEX Screener'] },
          ].map(c => (
            <div key={c.h} className="col" style={{ gap: 10 }}>
              <div className="pixel" style={{ fontSize: 11, color: 'var(--pd-yellow)', letterSpacing: '.14em' }}>{c.h}</div>
              {c.l.map(x => (
                <a key={x} href="#" style={{ fontSize: 14, color: 'rgba(241,233,210,.7)', textDecoration: 'none' }}>{x}</a>
              ))}
            </div>
          ))}
        </div>
        <div className="row between" style={{
          marginTop: 36, paddingTop: 18, borderTop: '2px dashed rgba(241,233,210,.15)',
          fontSize: 12, color: 'rgba(241,233,210,.45)',
        }}>
          <span className="mono">© 2026 POKEDEX PROTOCOL · NOT AFFILIATED WITH ANY EXISTING FRANCHISE</span>
          <span className="mono">SOLANA · BUILT WITH 🔥 ON PUMP.FUN</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Pokeball, Nav, Hero, MarqueeTicker, Mechanic, Footer });
