/* ============================================
   COINRUSH ULTRA-MODERN LANDING PAGE - React Component
   ============================================ */

const { useState, useEffect, useRef } = React;

// ============================================
// ICONS
// ============================================
const Icons = {
  coin: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="10" />
      <path d="M12 6v12M9 9h6M9 15h6" />
    </svg>
  ),
  crash: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polyline points="22 7 13.5 15.5 8.5 10.5 2 17" />
      <polyline points="16 7 22 7 22 13" />
    </svg>
  ),
  plinko: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="4" r="2"/>
      <circle cx="6" cy="8" r="1.5"/>
      <circle cx="12" cy="8" r="1.5"/>
      <circle cx="18" cy="8" r="1.5"/>
      <circle cx="4" cy="12" r="1.5"/>
      <circle cx="9" cy="12" r="1.5"/>
      <circle cx="15" cy="12" r="1.5"/>
      <circle cx="20" cy="12" r="1.5"/>
      <path d="M2 20h20" strokeWidth="3"/>
    </svg>
  ),
  jackpot: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
    </svg>
  ),
  knights: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M14.5 17.5L3 6V3h3l11.5 11.5" />
      <path d="M13 19l6-6" />
      <path d="M16 16l4 4" />
      <path d="M19 21l2-2" />
    </svg>
  ),
  dice: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3" y="3" width="18" height="18" rx="2" />
      <circle cx="8" cy="8" r="1" fill="currentColor" />
      <circle cx="16" cy="8" r="1" fill="currentColor" />
      <circle cx="8" cy="16" r="1" fill="currentColor" />
      <circle cx="16" cy="16" r="1" fill="currentColor" />
      <circle cx="12" cy="12" r="1" fill="currentColor" />
    </svg>
  ),
  lottery: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="M3 10h18" />
      <path d="M7 15h4" />
    </svg>
  ),
  shield: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
      <path d="M9 12l2 2 4-4" />
    </svg>
  ),
  lightning: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
    </svg>
  ),
  users: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
      <path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
  ),
  arrowRight: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M5 12h14M12 5l7 7-7 7" />
    </svg>
  ),
  play: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="5 3 19 12 5 21 5 3" />
    </svg>
  ),
  btc: (
    <svg viewBox="0 0 24 24" fill="currentColor" stroke="none">
      <path d="M16.5 10.5C16.5 8.5 15 7.5 13.5 7.5H10V5H8V7.5H6V9.5H8V14.5H6V16.5H8V19H10V16.5H13.5C15.5 16.5 17 15.5 17 13.5C17 12.5 16.5 11.8 15.5 11.2C16.2 10.8 16.5 10.2 16.5 10.5ZM10 9.5H13.5C14.5 9.5 15 10 15 10.5C15 11 14.5 11.5 13.5 11.5H10V9.5ZM13.5 14.5H10V12.5H13.5C14.5 12.5 15 13 15 13.5C15 14 14.5 14.5 13.5 14.5Z" />
    </svg>
  ),
  eth: (
    <svg viewBox="0 0 24 24" fill="currentColor" stroke="none">
      <path d="M12 2L4.5 14.5L12 19L19.5 14.5L12 2Z" opacity="0.6"/>
      <path d="M12 2L4.5 14.5L12 16L19.5 14.5L12 2Z" />
      <path d="M12 22L4.5 14.5L12 16L19.5 14.5L12 22Z" opacity="0.6"/>
    </svg>
  ),
  usdt: (
    <svg viewBox="0 0 24 24" fill="currentColor" stroke="none">
      <path d="M13 10V2H11V10H2V12H11V12.5C11 16.5 9 17.5 8 17.5C7.5 17.5 7 17.4 6.5 17.2L5.5 19C6.2 19.3 7.1 19.5 8 19.5C11 19.5 13 17.5 13 12.5V12H22V10H13Z" />
    </svg>
  )
};

// ============================================
// COMPONENTS
// ============================================

function Navbar() {
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 50);
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <nav className={`navbar ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href="/" className="topnav-logo">
          <span className="topnav-logo-icon">CR</span>
          <span className="topnav-logo-text">
            <span className="topnav-logo-title">COINRUSH</span>
            <span className="topnav-logo-subtitle">Crypto Casino</span>
          </span>
        </a>
        <div style={{ display: 'flex', gap: '16px' }}>
          <button className="btn btn-glass" onClick={() => window.openLoginModal()}>Log In</button>
          <button className="btn btn-primary" onClick={() => window.openRegisterModal()}>Sign Up</button>
        </div>
      </div>
    </nav>
  );
}

function LiveTicker() {
  // Simulated live wins
  const wins = [
    { user: "CryptoKing", game: "Crash", amount: "$1,240.50" },
    { user: "LuckyDoge", game: "Coinflip", amount: "$500.00" },
    { user: "MoonBoy", game: "Jackpot", amount: "$5,420.00" },
    { user: "Satoshi", game: "Dice", amount: "$120.00" },
    { user: "WhaleAlert", game: "Knights", amount: "$2,100.00" },
    { user: "HODLer", game: "Crash", amount: "$850.25" },
    { user: "ToTheMoon", game: "Lottery", amount: "$10,000.00" },
  ];

  return (
    <div className="live-ticker">
      <div className="ticker-track">
        {[...wins, ...wins, ...wins].map((win, i) => (
          <div className="ticker-item" key={i}>
            <strong>{win.user}</strong> won <span className="win-amount">{win.amount}</span> on {win.game}
          </div>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  const [gameState, setGameState] = useState({
    p1Health: 100,
    p2Health: 100,
    p1State: 'idle',
    p2State: 'idle',
    damage: null,
    winner: null,
    turn: 'p1',
    p1PotionUsed: false,
    p2PotionUsed: false
  });

  useEffect(() => {
    let mounted = true;
    
    const runBattle = async () => {
      while (mounted) {
        // Reset
        setGameState({ 
          p1Health: 100, 
          p2Health: 100, 
          p1State: 'idle', 
          p2State: 'idle', 
          damage: null, 
          winner: null,
          turn: Math.random() > 0.5 ? 'p1' : 'p2',
          p1PotionUsed: false,
          p2PotionUsed: false
        });
        await new Promise(r => setTimeout(r, 1000));

        let p1 = 100;
        let p2 = 100;
        let p1Potion = false;
        let p2Potion = false;
        let currentTurn = Math.random() > 0.5 ? 'p1' : 'p2';

        while (p1 > 0 && p2 > 0 && mounted) {
          const isP1Attacking = currentTurn === 'p1';
          const attacker = isP1Attacking ? 'p1' : 'p2';
          const defender = isP1Attacking ? 'p2' : 'p1';
          const attackerHealth = isP1Attacking ? p1 : p2;
          const attackerPotionUsed = isP1Attacking ? p1Potion : p2Potion;

          // Decide move: Attack or Potion (if health < 50 and potion not used)
          let move = 'attack';
          if (attackerHealth < 50 && !attackerPotionUsed && Math.random() > 0.3) {
            move = 'potion';
          }

          if (move === 'potion') {
            // Potion Animation
            setGameState(prev => ({ 
              ...prev, 
              [attacker === 'p1' ? 'p1State' : 'p2State']: 'potion',
              turn: currentTurn
            }));
            await new Promise(r => setTimeout(r, 600));

            // Heal Effect
            const heal = Math.floor(Math.random() * 10) + 20;
            if (isP1Attacking) { p1 = Math.min(100, p1 + heal); p1Potion = true; }
            else { p2 = Math.min(100, p2 + heal); p2Potion = true; }

            setGameState(prev => ({
              ...prev,
              p1Health: p1,
              p2Health: p2,
              [attacker === 'p1' ? 'p1State' : 'p2State']: 'idle',
              p1PotionUsed: p1Potion,
              p2PotionUsed: p2Potion,
              damage: { val: heal, target: attacker, type: 'heal' }
            }));
            
            // Potion doesn't end turn in real game, but for visual flow we can just proceed to attack or next turn
            // Let's make them attack immediately after potion for better flow
            await new Promise(r => setTimeout(r, 800));
            setGameState(prev => ({ ...prev, damage: null }));
          }

          // Attack Animation (Always happens unless game over, or if we want to simulate potion taking a turn slot - but usually it's a free action or part of turn)
          // For this visual, let's just do attack now.
          
          setGameState(prev => ({ 
            ...prev, 
            [attacker === 'p1' ? 'p1State' : 'p2State']: 'attack',
            turn: currentTurn
          }));
          await new Promise(r => setTimeout(r, 300));

          // Calculate damage
          const dmg = Math.floor(Math.random() * 20) + 10;
          if (isP1Attacking) p2 = Math.max(0, p2 - dmg);
          else p1 = Math.max(0, p1 - dmg);

          // Hit animation and damage display
          setGameState(prev => ({
            ...prev,
            p1Health: p1,
            p2Health: p2,
            [attacker === 'p1' ? 'p1State' : 'p2State']: 'idle',
            [defender === 'p1' ? 'p1State' : 'p2State']: 'hit',
            damage: { val: dmg, target: defender, type: 'damage' }
          }));

          await new Promise(r => setTimeout(r, 400));
          
          // Reset states
          setGameState(prev => ({ 
            ...prev, 
            p1State: 'idle', 
            p2State: 'idle', 
            damage: null 
          }));
          
          // Switch turn
          currentTurn = currentTurn === 'p1' ? 'p2' : 'p1';
          await new Promise(r => setTimeout(r, 600));
        }

        if (!mounted) break;
        setGameState(prev => ({ ...prev, winner: p1 > 0 ? 'p1' : 'p2' }));
        await new Promise(r => setTimeout(r, 3000));
      }
    };

    runBattle();
    return () => { mounted = false; };
  }, []);

  return (
    <section className="hero">
      <div className="container hero-grid">
        <div className="hero-content">
          <div className="hero-badge fade-in-up" style={{animationDelay: '0.1s'}}>
            <span className="pulse-dot"></span> LIVE ARENA ACTIVE
          </div>
          <h1 className="fade-in-up" style={{animationDelay: '0.2s'}}>
            NEXT GEN <br/>
            <span className="text-gradient-primary glitch-text" data-text="CRYPTO BATTLES">CRYPTO BATTLES</span>
          </h1>
          <p className="fade-in-up" style={{animationDelay: '0.3s'}}>
            The world's first provably fair RPG battle arena. Stake your claim, defeat your rivals, and earn real rewards in the metaverse.
          </p>
          
          <div className="hero-actions fade-in-up" style={{animationDelay: '0.4s'}}>
            <button className="btn btn-primary" onClick={() => window.openRegisterModal()}>
              ENTER THE ARENA {Icons.arrowRight}
            </button>
            <button className="btn btn-glass" onClick={() => document.getElementById('games').scrollIntoView({behavior: 'smooth'})}>
              VIEW GAMES
            </button>
          </div>
          
          <div className="hero-stats-strip fade-in-up" style={{animationDelay: '0.5s'}}>
            <div className="stat-item">
              <div className="stat-value">125k+</div>
              <div className="stat-label">Active Fighters</div>
            </div>
            <div className="stat-divider"></div>
            <div className="stat-item">
              <div className="stat-value">$45M+</div>
              <div className="stat-label">Total Wagered</div>
            </div>
            <div className="stat-divider"></div>
            <div className="stat-item">
              <div className="stat-value">0.5s</div>
              <div className="stat-label">Instant Payouts</div>
            </div>
          </div>
        </div>
        
        <div className="hero-visual fade-in-up" style={{animationDelay: '0.4s'}}>
          <div className="visual-card">
            <div className="battle-arena">
              <div className="battle-scene">
                {/* Left Knight (Blue) */}
                <div className={`knight-container knight-left`}>
                  <div className="health-bar-container">
                    <div className={`health-bar-fill ${gameState.p1Health < 30 ? 'low' : ''}`} style={{width: `${gameState.p1Health}%`}}></div>
                  </div>
                  <div className={`fighter-sprite-container left ${gameState.p1State === 'attack' ? 'attacking' : ''}`}>
                    <div className={`fighter-sprite creator sprite-${gameState.p1State} ${gameState.p1State === 'hit' ? 'shake' : ''}`}></div>
                    {gameState.damage?.target === 'p1' && (
                      <div className={`damage-number ${gameState.damage.type === 'heal' ? 'heal' : ''}`}>
                        {gameState.damage.type === 'heal' ? '+' : '-'}{gameState.damage.val}
                      </div>
                    )}
                    {gameState.winner === 'p1' && <div className="winner-crown">👑</div>}
                  </div>
                </div>

                <div className="vs-badge">VS</div>

                {/* Right Knight (Red) */}
                <div className={`knight-container knight-right`}>
                  <div className="health-bar-container">
                    <div className={`health-bar-fill ${gameState.p2Health < 30 ? 'low' : ''}`} style={{width: `${gameState.p2Health}%`}}></div>
                  </div>
                  <div className={`fighter-sprite-container right ${gameState.p2State === 'attack' ? 'attacking' : ''}`}>
                    <div className={`fighter-sprite opponent sprite-${gameState.p2State} ${gameState.p2State === 'hit' ? 'shake' : ''}`}></div>
                    {gameState.damage?.target === 'p2' && (
                      <div className={`damage-number ${gameState.damage.type === 'heal' ? 'heal' : ''}`}>
                        {gameState.damage.type === 'heal' ? '+' : '-'}{gameState.damage.val}
                      </div>
                    )}
                    {gameState.winner === 'p2' && <div className="winner-crown">👑</div>}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <LiveTicker />
    </section>
  );
}

function GameCard({ id, title, description, icon, link, color }) {
  return (
    <div className="game-card" onClick={() => window.location.href = link}>
      <div className={`game-card-visual visual-${id}`}>
        <div className="game-card-bg-pattern"></div>
        <div className="game-visual-element"></div>
        <div className="game-card-icon">
          {icon}
        </div>
      </div>
      <div className="game-card-content">
        <h3>{title}</h3>
        <p>{description}</p>
        <button className="btn btn-sm btn-outline">Play Now</button>
      </div>
    </div>
  );
}

function GamesSection() {
  const games = [
    { 
      id: "coinflip",
      title: "Coinflip", 
      description: "Double your money in a 50/50 clash.", 
      icon: Icons.coin, 
      link: "/coinflip"
    },
    { 
      id: "plinko",
      title: "Plinko", 
      description: "Drop the ball and win multipliers.", 
      icon: Icons.plinko || Icons.crash, 
      link: "/plinko"
    },
    { 
      id: "jackpot",
      title: "Jackpot", 
      description: "Winner takes all in this high stakes game.", 
      icon: Icons.jackpot, 
      link: "/jackpot"
    },
    { 
      id: "knights",
      title: "Knights", 
      description: "PvP battles in the arena.", 
      icon: Icons.knights, 
      link: "/barbarian"
    },
    { 
      id: "dice",
      title: "Dice", 
      description: "Roll the dice and predict the outcome.", 
      icon: Icons.dice, 
      link: "/slice-dice"
    },
    { 
      id: "lottery",
      title: "Lottery", 
      description: "Buy tickets for a chance to win big.", 
      icon: Icons.lottery, 
      link: "/lottery"
    },
  ];

  return (
    <section id="games" className="section">
      <div className="container">
        <div className="section-header">
          <h2 className="section-title">Our <span className="text-gradient-primary">Games</span></h2>
          <p className="section-subtitle">Provably fair games designed for thrill and transparency.</p>
        </div>
        <div className="games-grid">
          {games.map((game, i) => (
            <GameCard key={i} {...game} />
          ))}
        </div>
      </div>
    </section>
  );
}

function FeaturesSection() {
  return (
    <section className="section features-section">
      <div className="container">
        <div className="feature-row">
          <div className="feature-content">
            <h3>Provably Fair Gaming</h3>
            <p>Every game outcome is cryptographically verifiable. We use a transparent seed system that ensures no manipulation is possible. Verify any bet, any time.</p>
            <button className="btn btn-glass" onClick={() => window.location.href='/provably-fair'}>
              Learn More {Icons.arrowRight}
            </button>
          </div>
          <div className="feature-visual provably-fair-visual">
            <div className="code-block">
              <div className="code-line"><span className="code-keyword">const</span> <span className="code-var">serverSeed</span> = <span className="code-string">"d8b...3f2"</span>;</div>
              <div className="code-line"><span className="code-keyword">const</span> <span className="code-var">clientSeed</span> = <span className="code-string">"user_provided"</span>;</div>
              <div className="code-line"><span className="code-keyword">const</span> <span className="code-var">hash</span> = <span className="code-func">hmac_sha256</span>(serverSeed, clientSeed);</div>
              <div className="code-line"><span className="code-comment">// Result is deterministic</span></div>
              <div className="code-line"><span className="code-keyword">return</span> <span className="code-func">hexToDec</span>(hash);</div>
            </div>
            <div className="shield-icon-overlay">
              {Icons.shield}
            </div>
          </div>
        </div>

        <div className="feature-row reverse">
          <div className="feature-content">
            <h3>Instant Global Payouts</h3>
            <p>Withdraw your winnings instantly to your crypto wallet. No waiting periods, no hidden fees, just your money when you want it.</p>
            <button className="btn btn-glass" onClick={() => window.openLoginModal()}>
              Start Playing {Icons.arrowRight}
            </button>
          </div>
          <div className="feature-visual payouts-visual">
            <div className="floating-coins">
              <div className="float-coin coin-1">{Icons.coin}</div>
              <div className="float-coin coin-2">{Icons.coin}</div>
              <div className="float-coin coin-3">{Icons.coin}</div>
            </div>
            <div className="wallet-card">
              <div className="wallet-header">
                <div className="wallet-dot"></div>
                <span>Wallet Connected</span>
              </div>
              <div className="wallet-balance">$12,450.00</div>
              <div className="wallet-status">Transfer Complete</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="logo">
              <div className="logo-mark"></div>
              CoinRush
            </div>
            <p style={{ color: 'var(--text-muted)', marginTop: '20px' }}>The premier crypto casino experience. Fair, fast, and fun.</p>
          </div>
          <div className="footer-col">
            <h5>Games</h5>
            <ul>
              <li><a href="/coinflip">Coinflip</a></li>
              <li><a href="/plinko">Plinko</a></li>
              <li><a href="/jackpot">Jackpot</a></li>
              <li><a href="/barbarian">Knights</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Support</h5>
            <ul>
              <li><a href="/support">Help Center</a></li>
              <li><a href="/terms">Terms of Service</a></li>
              <li><a href="/privacy">Privacy Policy</a></li>
              <li><a href="/provably-fair">Provably Fair</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Community</h5>
            <ul>
              <li><a href="#">Discord</a></li>
              <li><a href="#">Twitter</a></li>
              <li><a href="#">Telegram</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          &copy; 2025 CoinRush. All rights reserved. Please gamble responsibly.
        </div>
      </div>
    </footer>
  );
}

function Stars() {
  // Generate static stars for background depth
  const [staticStars, setStaticStars] = useState('');
  
  // Generate twinkling stars
  const [twinklingStars, setTwinklingStars] = useState([]);

  useEffect(() => {
    // 1. Generate dense static star field using box-shadow
    let shadowValue = '';
    for (let i = 0; i < 400; i++) {
      const x = Math.random() * 100;
      const y = Math.random() * 100;
      const size = Math.random() * 1.5;
      shadowValue += `${x}vw ${y}vh ${size}px #fff, `;
    }
    setStaticStars(shadowValue.slice(0, -2));

    // 2. Generate animated twinkling stars
    const newStars = Array.from({ length: 60 }).map((_, i) => ({
      id: i,
      top: Math.random() * 100 + '%',
      left: Math.random() * 100 + '%',
      delay: Math.random() * 5 + 's',
      duration: Math.random() * 3 + 2 + 's',
      opacity: Math.random() * 0.7 + 0.3,
      size: Math.random() * 3 + 1 + 'px'
    }));
    setTwinklingStars(newStars);
  }, []);

  return (
    <div className="stars-container">
      <div className="static-stars" style={{ boxShadow: staticStars }}></div>
      {twinklingStars.map(star => (
        <div key={star.id} className="star-twinkle" style={{
          top: star.top,
          left: star.left,
          animationDelay: star.delay,
          animationDuration: star.duration,
          opacity: star.opacity,
          width: star.size,
          height: star.size
        }}></div>
      ))}
    </div>
  );
}

function Galaxy() {
  return (
    <div className="galaxy-wrapper">
      <div className="galaxy-spiral">
        <div className="galaxy-arm arm-1"></div>
        <div className="galaxy-arm arm-2"></div>
      </div>
      <div className="galaxy-core"></div>
    </div>
  );
}

function App() {
  return (
    <div className="landing-page">
      <div className="mesh-bg">
        <Stars />
        <div className="shooting-coin coin-btc star-1">{Icons.btc}</div>
        <div className="shooting-coin coin-eth star-2">{Icons.eth}</div>
        <div className="shooting-coin coin-usdt star-3">{Icons.usdt}</div>
        <div className="shooting-coin coin-btc star-4">{Icons.btc}</div>
        <div className="shooting-coin coin-eth star-5">{Icons.eth}</div>
        <div className="shooting-coin coin-usdt star-6">{Icons.usdt}</div>
        <div className="shooting-coin coin-btc star-7">{Icons.btc}</div>
        <div className="shooting-coin coin-eth star-8">{Icons.eth}</div>
      </div>
      <Navbar />
      <Hero />
      <GamesSection />
      <FeaturesSection />
      <Footer />
    </div>
  );
}

// Render
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);