/**
 * CoinRush Lottery - React Implementation
 * Premium lottery with countdown, ticket purchases, and animated draws
 * No emoji icons - all SVG
 */

// ============================================
// SVG ICONS
// ============================================
const Icons = {
  trophy: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9V2h12v7a6 6 0 01-12 0z"/>
      <path d="M6 4H4a2 2 0 000 4h2M18 4h2a2 2 0 010 4h-2"/>
      <path d="M9 22h6M12 15v7"/>
    </svg>
  ),
  ticket: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"/>
      <path d="M13 5v2M13 17v2M13 11v2"/>
    </svg>
  ),
  clock: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10"/>
      <polyline points="12 6 12 12 16 14"/>
    </svg>
  ),
  star: (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <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>
  ),
  dollar: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="12" y1="1" x2="12" y2="23"/>
      <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
    </svg>
  ),
  gift: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 12 20 22 4 22 4 12"/>
      <rect x="2" y="7" width="20" height="5"/>
      <line x1="12" y1="22" x2="12" y2="7"/>
      <path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/>
      <path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/>
    </svg>
  ),
  cart: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="9" cy="21" r="1"/>
      <circle cx="20" cy="21" r="1"/>
      <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/>
    </svg>
  ),
  info: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10"/>
      <path d="M12 16v-4M12 8h.01"/>
    </svg>
  ),
  calendar: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
      <line x1="16" y1="2" x2="16" y2="6"/>
      <line x1="8" y1="2" x2="8" y2="6"/>
      <line x1="3" y1="10" x2="21" y2="10"/>
    </svg>
  ),
  target: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10"/>
      <circle cx="12" cy="12" r="6"/>
      <circle cx="12" cy="12" r="2"/>
    </svg>
  ),
  sparkles: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"/>
      <path d="M19 12l.5 1.5L21 14l-1.5.5L19 16l-.5-1.5L17 14l1.5-.5L19 12z"/>
      <path d="M5 18l.5 1.5L7 20l-1.5.5L5 22l-.5-1.5L3 20l1.5-.5L5 18z"/>
    </svg>
  ),
  check: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12"/>
    </svg>
  ),
  x: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"/>
      <line x1="6" y1="6" x2="18" y2="18"/>
    </svg>
  ),
  crown: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 4l3 12h14l3-12-6 7-4-7-4 7-6-7z"/>
      <path d="M5 20h14"/>
    </svg>
  ),
  minus: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round">
      <line x1="5" y1="12" x2="19" y2="12"/>
    </svg>
  ),
  plus: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round">
      <line x1="12" y1="5" x2="12" y2="19"/>
      <line x1="5" y1="12" x2="19" y2="12"/>
    </svg>
  ),
  loader: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
      <path d="M21 12a9 9 0 11-6.219-8.56"/>
    </svg>
  ),
  users: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <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>
  ),
  heart: (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  ),
  dice: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="2" width="20" height="20" rx="2"/>
      <circle cx="8" cy="8" r="1.5" fill="currentColor"/>
      <circle cx="16" cy="8" r="1.5" fill="currentColor"/>
      <circle cx="8" cy="16" r="1.5" fill="currentColor"/>
      <circle cx="16" cy="16" r="1.5" fill="currentColor"/>
      <circle cx="12" cy="12" r="1.5" fill="currentColor"/>
    </svg>
  ),
  percent: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="19" y1="5" x2="5" y2="19"/>
      <circle cx="6.5" cy="6.5" r="2.5"/>
      <circle cx="17.5" cy="17.5" r="2.5"/>
    </svg>
  )
};

// ============================================
// LOTTERY RULES MODAL
// ============================================
function LotteryRulesModal({ onClose }) {
  // Prevent body scroll when modal is open
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  return (
    <div className="lt-modal-overlay" onClick={onClose}>
      <div className="lt-modal" onClick={e => e.stopPropagation()}>
        <button className="lt-modal-close" onClick={onClose}>{Icons.x}</button>
        
        <div className="lt-modal-header">
          <div className="lt-modal-icon lt-icon-heart">{Icons.heart}</div>
          <h2 className="lt-modal-title">Monthly Lottery Rules</h2>
        </div>
        
        <div className="lt-modal-content">
          {/* Community Message */}
          <div className="lt-rules-community">
            <p>
              The CoinRush Monthly Lottery is <strong>100% funded by CoinRush</strong>. 
              We created this lottery as a way to give back to our amazing community 
              and thank you for being part of the CoinRush family. Every month, we set aside 
              a portion of our revenue to reward our loyal players with a chance to win big!
            </p>
          </div>
          
          {/* How to Get Tickets */}
          <div className="lt-rules-section">
            <div className="lt-rules-section-header">
              <span className="lt-rules-section-icon lt-icon-ticket">{Icons.ticket}</span>
              <h3>How to Get Tickets</h3>
            </div>
            <ul className="lt-rules-list">
              <li>
                <strong>Earn FREE tickets:</strong> For every $50 wagered on any CoinRush game, 
                you automatically receive 1 FREE lottery ticket.
              </li>
              <li>
                <strong>Buy tickets:</strong> Purchase additional tickets for $10 each 
                to increase your chances of winning.
              </li>
            </ul>
          </div>
          
          {/* How the Draw Works */}
          <div className="lt-rules-section">
            <div className="lt-rules-section-header">
              <span className="lt-rules-section-icon lt-icon-calendar">{Icons.calendar}</span>
              <h3>Monthly Draw</h3>
            </div>
            <ul className="lt-rules-list">
              <li>
                The lottery draw happens on the <strong>1st of every month at midnight UTC</strong>.
              </li>
              <li>
                A single winning ticket is randomly selected from all tickets in the pool.
              </li>
              <li>
                The more tickets you have, the higher your chance of winning!
              </li>
            </ul>
          </div>
          
          {/* Prize Pool */}
          <div className="lt-rules-section">
            <div className="lt-rules-section-header">
              <span className="lt-rules-section-icon lt-icon-trophy">{Icons.trophy}</span>
              <h3>Prize Pool</h3>
            </div>
            <ul className="lt-rules-list">
              <li>
                The prize pool consists of <strong>5% of the monthly platform revenue</strong> 
                plus all ticket purchase proceeds.
              </li>
              <li>
                <strong>One lucky winner takes the entire prize pool!</strong>
              </li>
              <li>
                Winnings are instantly credited to your CoinRush balance.
              </li>
            </ul>
          </div>
          
          {/* Win Chance */}
          <div className="lt-rules-section">
            <div className="lt-rules-section-header">
              <span className="lt-rules-section-icon lt-icon-target">{Icons.target}</span>
              <h3>Your Win Chance</h3>
            </div>
            <ul className="lt-rules-list">
              <li>
                Win chance = (Your Tickets / Total Tickets in Pool) × 100%
              </li>
              <li>
                Your current win chance is displayed on your ticket stats card.
              </li>
              <li>
                The draw is provably fair and uses a cryptographically secure random selection.
              </li>
            </ul>
          </div>
        </div>
        
        <div className="lt-modal-footer">
          <button className="lt-modal-btn" onClick={onClose}>Got it!</button>
        </div>
      </div>
    </div>
  );
}

// ============================================
// UTILITY FUNCTIONS
// ============================================
function formatCurrency(cents) {
  return (cents / 100).toFixed(2);
}

function formatWithCommas(num) {
  const parts = num.toString().split('.');
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join('.');
}

// ============================================
// COUNTDOWN TIMER COMPONENT
// ============================================
function CountdownTimer({ drawAt }) {
  const [timeLeft, setTimeLeft] = React.useState({ days: 0, hours: 0, minutes: 0, seconds: 0 });
  const [isDrawing, setIsDrawing] = React.useState(false);

  React.useEffect(() => {
    if (!drawAt) return;

    const updateTimer = () => {
      const now = new Date();
      const drawTime = new Date(drawAt);
      const diff = Math.max(0, drawTime - now);

      if (diff <= 0) {
        setIsDrawing(true);
        setTimeLeft({ days: 0, hours: 0, minutes: 0, seconds: 0 });
        return;
      }

      setIsDrawing(false);
      setTimeLeft({
        days: Math.floor(diff / (1000 * 60 * 60 * 24)),
        hours: Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
        minutes: Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)),
        seconds: Math.floor((diff % (1000 * 60)) / 1000)
      });
    };

    updateTimer();
    const interval = setInterval(updateTimer, 1000);
    return () => clearInterval(interval);
  }, [drawAt]);

  return (
    <div className="lt-card lt-countdown-card">
      <div className="lt-card-header">
        <div className="lt-card-icon lt-icon-clock">{Icons.clock}</div>
        <h3 className="lt-card-title">Next Draw</h3>
        <span className={`lt-badge ${isDrawing ? 'lt-badge-drawing' : 'lt-badge-open'}`}>
          {isDrawing ? 'DRAWING' : 'OPEN'}
        </span>
      </div>
      <div className="lt-countdown-timer">
        <div className="lt-time-unit">
          <div className="lt-time-value">{String(timeLeft.days).padStart(2, '0')}</div>
          <div className="lt-time-label">DAYS</div>
        </div>
        <div className="lt-time-sep">:</div>
        <div className="lt-time-unit">
          <div className="lt-time-value">{String(timeLeft.hours).padStart(2, '0')}</div>
          <div className="lt-time-label">HRS</div>
        </div>
        <div className="lt-time-sep">:</div>
        <div className="lt-time-unit">
          <div className="lt-time-value">{String(timeLeft.minutes).padStart(2, '0')}</div>
          <div className="lt-time-label">MIN</div>
        </div>
        <div className="lt-time-sep">:</div>
        <div className="lt-time-unit">
          <div className="lt-time-value lt-time-seconds">{String(timeLeft.seconds).padStart(2, '0')}</div>
          <div className="lt-time-label">SEC</div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// PRIZE POOL COMPONENT
// ============================================
function PrizePool({ prizePool, totalTickets }) {
  const formattedPrize = formatWithCommas(formatCurrency(prizePool));
  
  return (
    <div className="lt-card lt-prize-card">
      <div className="lt-prize-glow" />
      <div className="lt-card-header">
        <div className="lt-card-icon lt-icon-trophy">{Icons.trophy}</div>
        <h3 className="lt-card-title">Prize Pool</h3>
      </div>
      <div className="lt-prize-amount">
        <span className="lt-prize-currency">$</span>
        <span className="lt-prize-value">{formattedPrize}</span>
      </div>
      <div className="lt-prize-meta">
        <div className="lt-meta-item">
          <span className="lt-meta-icon">{Icons.ticket}</span>
          <span>{formatWithCommas(totalTickets)} tickets</span>
        </div>
      </div>
    </div>
  );
}

// ============================================
// USER STATS COMPONENT
// ============================================
function UserStats({ stats, totalTickets }) {
  if (!stats) {
    return (
      <div className="lt-card lt-stats-card lt-login-prompt">
        <div className="lt-card-icon lt-icon-ticket">{Icons.ticket}</div>
        <h3>Your Tickets</h3>
        <p>Log in to view your lottery tickets and stats</p>
      </div>
    );
  }

  const winChance = stats.win_chance || 0;
  
  return (
    <div className="lt-card lt-stats-card">
      <div className="lt-card-header">
        <div className="lt-card-icon lt-icon-ticket">{Icons.ticket}</div>
        <h3 className="lt-card-title">Your Tickets</h3>
      </div>
      
      <div className="lt-stats-main">
        <div className="lt-stat-big">
          <span className="lt-stat-value">{stats.total_tickets || 0}</span>
          <span className="lt-stat-label">Total Tickets</span>
        </div>
        
        <div className="lt-chance-section">
          <div className="lt-chance-bar-container">
            <div className="lt-chance-bar">
              <div 
                className="lt-chance-fill" 
                style={{ width: `${Math.min(winChance, 100)}%` }}
              />
            </div>
            <span className="lt-chance-percent">{winChance.toFixed(2)}%</span>
          </div>
          <span className="lt-chance-label">Win Chance</span>
        </div>
      </div>
      
      <div className="lt-stats-breakdown">
        <div className="lt-breakdown-item">
          <span className="lt-breakdown-icon lt-icon-gift">{Icons.gift}</span>
          <div className="lt-breakdown-content">
            <span className="lt-breakdown-value">{stats.wagered_tickets || 0}</span>
            <span className="lt-breakdown-label">Earned (Free)</span>
          </div>
        </div>
        <div className="lt-breakdown-item">
          <span className="lt-breakdown-icon lt-icon-cart">{Icons.cart}</span>
          <div className="lt-breakdown-content">
            <span className="lt-breakdown-value">{stats.purchased_tickets || 0}</span>
            <span className="lt-breakdown-label">Purchased</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// BUY TICKETS COMPONENT
// ============================================
function BuyTickets({ ticketPrice, onPurchase, userLoggedIn }) {
  const [quantity, setQuantity] = React.useState(1);
  const [loading, setLoading] = React.useState(false);

  const totalCost = quantity * ticketPrice;
  const pricePerTicket = formatCurrency(ticketPrice);

  const handleQuantityChange = (delta) => {
    setQuantity(prev => Math.max(1, Math.min(100, prev + delta)));
  };

  const handleInputChange = (e) => {
    const val = parseInt(e.target.value) || 1;
    setQuantity(Math.max(1, Math.min(100, val)));
  };

  const handleBuy = async () => {
    if (!userLoggedIn) {
      if (window.showAuthModal) window.showAuthModal('login');
      return;
    }
    
    setLoading(true);
    try {
      await onPurchase(quantity);
      setQuantity(1);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="lt-card lt-buy-card">
      <div className="lt-card-header">
        <div className="lt-card-icon lt-icon-cart">{Icons.cart}</div>
        <h3 className="lt-card-title">Buy Tickets</h3>
        <span className="lt-price-tag">${pricePerTicket} / ticket</span>
      </div>
      
      <div className="lt-buy-content">
        <div className="lt-quantity-row">
          <span className="lt-qty-label">Quantity</span>
          <div className="lt-quantity-controls">
            <button 
              className="lt-qty-btn" 
              onClick={() => handleQuantityChange(-1)}
              disabled={quantity <= 1}
            >
              {Icons.minus}
            </button>
            <input 
              type="number" 
              className="lt-qty-input"
              value={quantity}
              onChange={handleInputChange}
              min="1"
              max="100"
            />
            <button 
              className="lt-qty-btn" 
              onClick={() => handleQuantityChange(1)}
              disabled={quantity >= 100}
            >
              {Icons.plus}
            </button>
          </div>
        </div>
        
        <div className="lt-total-row">
          <span className="lt-total-label">Total</span>
          <span className="lt-total-value">${formatCurrency(totalCost)}</span>
        </div>
        
        <button 
          className={`lt-buy-btn ${loading ? 'lt-loading' : ''}`}
          onClick={handleBuy}
          disabled={loading}
        >
          {loading ? (
            <>
              <span className="lt-spinner">{Icons.loader}</span>
              <span>Processing...</span>
            </>
          ) : (
            <>
              <span className="lt-buy-icon">{Icons.ticket}</span>
              <span>Purchase {quantity} Ticket{quantity > 1 ? 's' : ''}</span>
            </>
          )}
        </button>
      </div>
    </div>
  );
}

// ============================================
// WAGER PROGRESS COMPONENT
// ============================================
function WagerProgress({ stats, wagerPerTicket }) {
  const targetDollars = formatCurrency(wagerPerTicket);
  
  // If not logged in, show the card with 0 progress
  const progressInCycle = stats ? (stats.wager_progress || 0) % wagerPerTicket : 0;
  const percentage = (progressInCycle / wagerPerTicket) * 100;
  const progressDollars = formatCurrency(progressInCycle);

  return (
    <div className="lt-card lt-wager-card">
      <div className="lt-card-header">
        <div className="lt-card-icon lt-icon-star">{Icons.star}</div>
        <h3 className="lt-card-title">Earn Free Tickets</h3>
      </div>
      
      <p className="lt-wager-desc">
        Wager <strong>${targetDollars}</strong> on any game to earn <strong>1 FREE</strong> lottery ticket!
      </p>
      
      <div className="lt-wager-progress">
        <div className="lt-progress-track">
          <div 
            className="lt-progress-fill" 
            style={{ width: `${percentage}%` }}
          />
        </div>
        <div className="lt-progress-stats">
          <span className="lt-progress-current">${progressDollars}</span>
          <span className="lt-progress-target">/ ${targetDollars}</span>
        </div>
      </div>
    </div>
  );
}

// ============================================
// HOW IT WORKS COMPONENT
// ============================================
function HowItWorks() {
  const steps = [
    {
      icon: Icons.star,
      iconClass: 'lt-icon-star',
      title: 'Earn Free Tickets',
      desc: 'For every $50 wagered on any game, you automatically earn 1 FREE lottery ticket.'
    },
    {
      icon: Icons.cart,
      iconClass: 'lt-icon-cart',
      title: 'Buy Extra Tickets',
      desc: 'Want more chances? Buy additional tickets for just $10 each to boost your odds!'
    },
    {
      icon: Icons.calendar,
      iconClass: 'lt-icon-calendar',
      title: 'Monthly Draw',
      desc: 'Drawings happen on the 1st of every month at midnight UTC. Watch the countdown!'
    },
    {
      icon: Icons.trophy,
      iconClass: 'lt-icon-trophy',
      title: 'Win the Prize Pool',
      desc: 'Prize pool is 5% of monthly revenue. One lucky ticket wins 100% of it!'
    }
  ];

  return (
    <div className="lt-section lt-how-section">
      <div className="lt-section-header">
        <div className="lt-section-icon lt-icon-info">{Icons.info}</div>
        <h2 className="lt-section-title">How It Works</h2>
      </div>
      
      <div className="lt-steps-grid">
        {steps.map((step, i) => (
          <div key={i} className="lt-step-card">
            <div className="lt-step-number">{i + 1}</div>
            <div className={`lt-step-icon ${step.iconClass}`}>{step.icon}</div>
            <h4 className="lt-step-title">{step.title}</h4>
            <p className="lt-step-desc">{step.desc}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================
// RECENT WINNERS COMPONENT
// ============================================
function RecentWinners({ winners }) {
  return (
    <div className="lt-section lt-winners-section">
      <div className="lt-section-header">
        <div className="lt-section-icon lt-icon-crown">{Icons.crown}</div>
        <h2 className="lt-section-title">Recent Winners</h2>
      </div>
      
      {winners.length === 0 ? (
        <div className="lt-empty-state">
          <div className="lt-empty-icon">{Icons.sparkles}</div>
          <p>No draws yet. Be the first winner!</p>
        </div>
      ) : (
        <div className="lt-winners-grid">
          {winners.map((winner, i) => (
            <div key={i} className="lt-winner-card">
              <div className="lt-winner-rank">#{i + 1}</div>
              <div className="lt-winner-info">
                <div className="lt-winner-period">{winner.period}</div>
                <div className="lt-winner-name">{winner.winner_username || 'Anonymous'}</div>
              </div>
              <div className="lt-winner-prize">
                <span className="lt-winner-prize-label">Won</span>
                <span className="lt-winner-prize-value">${formatCurrency(winner.prize_pool)}</span>
              </div>
              <div className="lt-winner-ticket">
                <span className="lt-ticket-icon">{Icons.ticket}</span>
                <span className="lt-ticket-num">#{winner.winning_ticket_number}</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ============================================
// TOAST NOTIFICATION
// ============================================
function Toast({ message, type, onClose }) {
  React.useEffect(() => {
    const timer = setTimeout(onClose, 4000);
    return () => clearTimeout(timer);
  }, [onClose]);

  const icon = type === 'success' ? Icons.check : type === 'error' ? Icons.x : Icons.info;

  return (
    <div className={`lt-toast lt-toast-${type}`}>
      <span className="lt-toast-icon">{icon}</span>
      <span className="lt-toast-message">{message}</span>
      <button className="lt-toast-close" onClick={onClose}>{Icons.x}</button>
    </div>
  );
}

// ============================================
// MAIN LOTTERY APP
// ============================================
function LotteryApp() {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [showRules, setShowRules] = React.useState(false);
  const [lotteryState, setLotteryState] = React.useState({
    status: 'open',
    prizePool: 0,
    totalTickets: 0,
    ticketPrice: 1000,
    wagerPerTicket: 5000,
    drawAt: null,
    userStats: null
  });
  const [winners, setWinners] = React.useState([]);
  const [toast, setToast] = React.useState(null);

  // Expose rules modal to navbar
  React.useEffect(() => {
    window.showLotteryRules = () => setShowRules(true);
    return () => { delete window.showLotteryRules; };
  }, []);

  // Fetch user
  const fetchUser = React.useCallback(async () => {
    try {
      const res = await fetch('/me', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setUser(data);
      }
    } catch (e) {
      console.error('Failed to fetch user:', e);
    }
  }, []);

  // Fetch lottery state
  const fetchLotteryState = React.useCallback(async () => {
    try {
      const res = await fetch('/api/lottery/state', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setLotteryState({
          status: data.status,
          prizePool: data.prize_pool,
          totalTickets: data.total_tickets,
          ticketPrice: data.ticket_price,
          wagerPerTicket: data.wager_per_ticket,
          drawAt: data.draw_at,
          userStats: data.user_stats
        });
      }
    } catch (e) {
      console.error('Failed to fetch lottery state:', e);
    }
  }, []);

  // Fetch winners history
  const fetchHistory = React.useCallback(async () => {
    try {
      const res = await fetch('/api/lottery/history', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setWinners(data.draws || []);
      }
    } catch (e) {
      console.error('Failed to fetch history:', e);
    }
  }, []);

  // Initial load
  React.useEffect(() => {
    Promise.all([fetchUser(), fetchLotteryState(), fetchHistory()])
      .finally(() => setLoading(false));
    
    // Refresh state every 30 seconds
    const interval = setInterval(fetchLotteryState, 30000);
    return () => clearInterval(interval);
  }, [fetchUser, fetchLotteryState, fetchHistory]);

  // Buy tickets handler
  const handlePurchase = async (quantity) => {
    try {
      const res = await fetch('/api/lottery/buy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ quantity })
      });
      
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.detail || 'Failed to purchase tickets');
      }
      
      // Update state
      setLotteryState(prev => ({
        ...prev,
        prizePool: data.prize_pool,
        totalTickets: data.total_tickets,
        userStats: data.user_stats
      }));
      
      // Update navbar balance
      if (window.updateBalanceDisplay && data.balance !== undefined) {
        window.updateBalanceDisplay(data.balance);
      }
      
      // Refresh user
      fetchUser();
      
      setToast({ 
        message: `Successfully purchased ${quantity} ticket${quantity > 1 ? 's' : ''}! 🎉`, 
        type: 'success' 
      });
      
    } catch (error) {
      setToast({ message: error.message, type: 'error' });
      throw error;
    }
  };

  if (loading) {
    return (
      <div className="lt-app">
        <div className="lt-loading">
          <div className="lt-loading-spinner">{Icons.loader}</div>
          <span>Loading lottery...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="lt-app">
      {/* Floating Glowing Orbs Background */}
      <div className="lt-orbs">
        <div className="lt-orb lt-orb-1"></div>
        <div className="lt-orb lt-orb-2"></div>
        <div className="lt-orb lt-orb-3"></div>
        <div className="lt-orb lt-orb-4"></div>
        <div className="lt-orb lt-orb-5"></div>
        <div className="lt-orb lt-orb-6"></div>
        <div className="lt-orb lt-orb-7"></div>
        <div className="lt-orb lt-orb-8"></div>
      </div>
      
      {/* Animated Floating Particles */}
      <div className="lt-particles">
        {[...Array(35)].map((_, i) => (
          <div 
            key={i} 
            className="lt-particle" 
            style={{
              '--delay': `${i * 0.2}s`,
              '--x': `${Math.random() * 100}%`,
              '--duration': `${4 + Math.random() * 5}s`,
              '--size': `${2 + Math.random() * 4}px`
            }}
          />
        ))}
      </div>
      
      {/* Rules Modal */}
      {showRules && <LotteryRulesModal onClose={() => setShowRules(false)} />}
      
      {/* Toast Notifications */}
      {toast && (
        <Toast 
          message={toast.message} 
          type={toast.type} 
          onClose={() => setToast(null)} 
        />
      )}
      
      {/* Navbar */}
      <CoinRushNavbar 
        user={user} 
        activePage="lottery"
        isConnected={true}
        onLogout={() => { setUser(null); fetchLotteryState(); }}
      />
      
      <main className="lt-main">
        {/* Hero Section - Compact */}
        <div className="lt-hero-compact">
          <h1 className="lt-hero-title">Monthly Lottery</h1>
          <p className="lt-hero-subtitle">Get tickets, win big!</p>
        </div>

        {/* Top Row - Prize, Countdown, Earn Free */}
        <div className="lt-top-row-3">
          <PrizePool 
            prizePool={lotteryState.prizePool} 
            totalTickets={lotteryState.totalTickets} 
          />
          <CountdownTimer drawAt={lotteryState.drawAt} />
          <WagerProgress 
            stats={lotteryState.userStats}
            wagerPerTicket={lotteryState.wagerPerTicket}
          />
        </div>

        {/* Main Content Grid - Stats & Buy */}
        <div className="lt-content-grid">
          <div className="lt-col">
            <UserStats 
              stats={lotteryState.userStats} 
              totalTickets={lotteryState.totalTickets}
            />
          </div>
          
          <div className="lt-col">
            <BuyTickets 
              ticketPrice={lotteryState.ticketPrice}
              onPurchase={handlePurchase}
              userLoggedIn={!!user}
            />
          </div>
        </div>

        {/* How It Works */}
        <HowItWorks />

        {/* Recent Winners */}
        <RecentWinners winners={winners} />
      </main>
    </div>
  );
}

// ============================================
// RENDER APP
// ============================================
const lotteryRoot = ReactDOM.createRoot(document.getElementById('root'));
lotteryRoot.render(<LotteryApp />);
