/**
 * CoinRush React Navbar Component
 * Matches the existing navbar.html design
 */

const { useState, useEffect, useRef } = React;

// ============================================
// GLOBAL BALANCE SERVICE
// ============================================
// This service provides real-time balance updates across all components
// with floating +/- animations
window.CoinRushBalance = window.CoinRushBalance || {
  listeners: [],
  pendingAnimation: null, // Queue for delayed animations (wins during spin)
  
  // Subscribe to balance updates
  subscribe(callback) {
    this.listeners.push(callback);
    return () => {
      this.listeners = this.listeners.filter(cb => cb !== callback);
    };
  },
  
  // Update balance with optional delta animation
  // newBalance: balance in cents, delta: change in cents (positive or negative)
  // showAnimation: if false, queues the animation for later (use for wins during spin)
  update(newBalance, delta = null, showAnimation = true) {
    // Dispatch to all listeners (always update the displayed balance)
    this.listeners.forEach(cb => cb(newBalance, delta));
    
    // Dispatch global event for components not using subscription
    window.dispatchEvent(new CustomEvent('coinrush:balance', {
      detail: { balance: newBalance, delta }
    }));
    
    // Show or queue floating animation
    if (delta !== null && delta !== 0) {
      if (showAnimation) {
        this.showFloatingDelta(delta);
      } else {
        // Queue the animation for later (when game animation completes)
        this.pendingAnimation = delta;
      }
    }
  },
  
  // Show the pending animation (call this when game animation completes)
  showPendingAnimation() {
    if (this.pendingAnimation !== null) {
      this.showFloatingDelta(this.pendingAnimation);
      this.pendingAnimation = null;
    }
  },
  
  // Clear pending animation without showing it
  clearPendingAnimation() {
    this.pendingAnimation = null;
  },
  
  // Show floating +/- animation near the balance display
  showFloatingDelta(deltaCents) {
    const balanceEl = document.getElementById('navbarBalance');
    if (!balanceEl) return;
    
    const rect = balanceEl.getBoundingClientRect();
    const isPositive = deltaCents > 0;
    const displayAmount = Math.abs(deltaCents) / 100;
    
    // Create floating element
    const floater = document.createElement('div');
    floater.className = `balance-floater ${isPositive ? 'positive' : 'negative'}`;
    floater.textContent = `${isPositive ? '+' : '-'}${displayAmount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    
    // Position near the balance
    floater.style.position = 'fixed';
    floater.style.left = `${rect.left + rect.width / 2}px`;
    floater.style.top = `${rect.top}px`;
    floater.style.zIndex = '10000';
    
    document.body.appendChild(floater);
    
    // Remove after animation
    setTimeout(() => floater.remove(), 1500);
  }
};

// Global function for easy access
window.updateCoinRushBalance = (newBalance, delta, showAnimation = true) => {
  window.CoinRushBalance.update(newBalance, delta, showAnimation);
};

// Show pending animation (call after game animation completes)
window.showPendingBalanceAnimation = () => {
  window.CoinRushBalance.showPendingAnimation();
};

// ============================================
// UTILITIES
// ============================================
const colorFrom = (name) => {
  if (!name) return '#666';
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = ((hash << 5) - hash) + name.charCodeAt(i);
  }
  const hue = Math.abs(hash % 360);
  return `hsl(${hue}, 65%, 50%)`;
};

const fmt = (cents) => ((cents || 0) / 100).toLocaleString('en-US', { 
  minimumFractionDigits: 2, 
  maximumFractionDigits: 2 
});

const getAvatarBorderClass = (level) => {
  if (level >= 50) return 'border-challenger';
  if (level >= 40) return 'border-ruby';
  if (level >= 30) return 'border-diamond';
  if (level >= 20) return 'border-gold';
  if (level >= 10) return 'border-silver';
  return 'border-bronze';
};

// Get the PNG border image path based on level
const getBorderImage = (level) => {
  if (level >= 50) return '/static/img/borders/Challengerborder.png';
  if (level >= 40) return '/static/img/borders/Rubyborder.png';
  if (level >= 30) return '/static/img/borders/Diamondborder.png';
  if (level >= 20) return '/static/img/borders/Goldborder.png';
  if (level >= 10) return '/static/img/borders/Silverborder.png';
  return '/static/img/borders/Bronzeborder.png';
};

const getLevelClass = (level) => {
  if (level >= 50) return 'level-challenger';
  if (level >= 40) return 'level-ruby';
  if (level >= 30) return 'level-diamond';
  if (level >= 20) return 'level-gold';
  if (level >= 10) return 'level-silver';
  return 'level-bronze';
};

// ============================================
// GAMES DROPDOWN
// ============================================
function GamesDropdown({ activePage }) {
  const games = [
    { href: '/coinflip-react', name: 'Coinflip', key: 'coinflip', color: '#fbbf24' },
    { href: '/jackpot-react', name: 'Jackpot', key: 'jackpot', color: '#3b82f6' },
    { href: '/premium-jackpot', name: 'Premium', key: 'premium-jackpot', color: '#a855f7', badge: 'VIP' },
    { divider: true },
    { href: '/barbarian', name: 'Knights Arena', key: 'barbarian', color: '#ef4444' },
    { href: '/plinko', name: 'Plinko', key: 'plinko', color: '#ffd700' },
    { href: '/slice-dice', name: "Slice 'n Dice", key: 'slice_dice', color: '#ec4899' },
  ];

  return (
    <div className="nav-dropdown">
      <button className={`nav-dropdown-trigger ${['coinflip', 'jackpot', 'premium-jackpot', 'barbarian', 'plinko', 'slice_dice'].includes(activePage) ? 'is-active' : ''}`}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <rect x="2" y="6" width="20" height="12" rx="2"></rect>
          <circle cx="12" cy="12" r="2"></circle>
        </svg>
        Games
        <svg className="dropdown-chevron" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
          <polyline points="6 9 12 15 18 9"></polyline>
        </svg>
      </button>
      <div className="nav-dropdown-menu">
        {games.map((game, idx) => 
          game.divider ? (
            <div key={`div-${idx}`} className="dropdown-separator" />
          ) : (
            <a 
              key={game.key} 
              href={game.href} 
              className={`nav-dropdown-item ${game.key === 'premium-jackpot' ? 'premium' : ''} ${activePage === game.key ? 'is-active' : ''}`}
            >
              <span className="dropdown-item-dot" style={{ background: game.color }}></span>
              <span className="dropdown-item-name">{game.name}</span>
              {game.badge && <span className="dropdown-item-badge">{game.badge}</span>}
            </a>
          )
        )}
      </div>
    </div>
  );
}

// ============================================
// USER DROPDOWN
// ============================================
function UserDropdown({ user, onLogout, onBalanceUpdate }) {
  const [isOpen, setIsOpen] = useState(false);
  const [activeBonus, setActiveBonus] = useState(null);
  const [bonusCountdown, setBonusCountdown] = useState('');
  const [displayBalance, setDisplayBalance] = useState(user?.balance || 0);
  const dropdownRef = useRef(null);
  
  // Subscribe to global balance updates
  useEffect(() => {
    // Sync initial balance
    setDisplayBalance(user?.balance || 0);
  }, [user?.balance]);
  
  useEffect(() => {
    const unsubscribe = window.CoinRushBalance.subscribe((newBalance, delta) => {
      setDisplayBalance(newBalance);
      // Also call parent callback if provided
      if (onBalanceUpdate) onBalanceUpdate(newBalance);
    });
    
    // Also listen for legacy balance events
    const handleLegacyUpdate = (e) => {
      if (e.detail?.balance !== undefined) {
        setDisplayBalance(e.detail.balance);
      }
    };
    window.addEventListener('coinrush:balance', handleLegacyUpdate);
    
    return () => {
      unsubscribe();
      window.removeEventListener('coinrush:balance', handleLegacyUpdate);
    };
  }, [onBalanceUpdate]);
  
  const level = user?.level_info?.current_level || 1;
  const avatarClass = getAvatarBorderClass(level);
  const levelClass = getLevelClass(level);
  const borderImage = getBorderImage(level);
  const freeBattles = user?.free_battles_available || 0;
  
  // Level progress
  const levelInfo = user?.level_info || {};
  const levelGoal = Math.max(0, (levelInfo.next_level_wagered || 0) - (levelInfo.current_level_wagered || 0));
  const rawProgress = Math.max(0, levelInfo.progress_in_level || 0);
  const progressPct = levelGoal > 0 ? Math.min(100, (rawProgress / levelGoal) * 100) : 100;
  const progressLabel = levelGoal > 0 
    ? `${fmt(rawProgress)} / ${fmt(levelGoal)}` 
    : `${fmt(rawProgress)}`;

  // Fetch active bonuses for flame indicator
  useEffect(() => {
    const fetchBonuses = async () => {
      try {
        const res = await fetch('/api/daily-reward/status', { credentials: 'include' });
        if (res.ok) {
          const data = await res.json();
          console.log('Daily reward status:', data);
          
          // Check if XP boost is active
          if (data.active_bonuses?.xp_boost > 0 && data.active_bonuses?.xp_boost_expires) {
            // xp_boost_expires is a date string (YYYY-MM-DD) - expires at END of that day (midnight next day)
            const expiresDate = data.active_bonuses.xp_boost_expires;
            const expiresMidnight = new Date(expiresDate + 'T23:59:59');
            
            setActiveBonus({
              type: 'xp_boost',
              value: data.active_bonuses.xp_boost,
              expires: expiresMidnight
            });
          } else {
            setActiveBonus(null);
          }
        }
      } catch (err) {
        console.error('Failed to fetch bonus status:', err);
      }
    };
    
    fetchBonuses();
    // Refresh every 60 seconds
    const interval = setInterval(fetchBonuses, 60000);
    return () => clearInterval(interval);
  }, []);

  // Countdown timer for active bonus
  useEffect(() => {
    if (!activeBonus?.expires) {
      setBonusCountdown('');
      return;
    }
    
    const updateCountdown = () => {
      const now = new Date();
      const diff = activeBonus.expires - now;
      
      if (diff <= 0) {
        setActiveBonus(null);
        setBonusCountdown('');
        return;
      }
      
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      
      if (hours > 0) {
        setBonusCountdown(`${hours}h ${mins}m`);
      } else {
        const secs = Math.floor((diff % (1000 * 60)) / 1000);
        setBonusCountdown(`${mins}m ${secs}s`);
      }
    };
    
    updateCountdown();
    const interval = setInterval(updateCountdown, 1000);
    return () => clearInterval(interval);
  }, [activeBonus]);

  // Close on outside click
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  // Flame SVG icon
  const FlameIcon = () => (
    <svg viewBox="0 0 24 24" fill="currentColor" className="bonus-flame-svg">
      <path d="M12 23c-3.866 0-7-3.134-7-7 0-3.037 2.087-5.617 5-6.42V7.5C10 4.462 12 2 12 2s2 2.462 2 5.5v2.08c2.913.803 5 3.383 5 6.42 0 3.866-3.134 7-7 7zm0-2c2.761 0 5-2.239 5-5 0-2.21-1.5-4.07-3.54-4.684l-.46-.132V7.5c0-1.295-.476-2.496-1-3.368-.524.872-1 2.073-1 3.368v3.684l-.46.132C8.5 11.93 7 13.79 7 16c0 2.761 2.239 5 5 5z"/>
      <path d="M12 21c-1.657 0-3-1.343-3-3 0-1.306.835-2.417 2-2.83V13c0-.552.448-1 1-1s1 .448 1 1v2.17c1.165.413 2 1.524 2 2.83 0 1.657-1.343 3-3 3z"/>
    </svg>
  );

  // Handle flame click to open daily rewards
  const handleFlameClick = (e) => {
    e.stopPropagation();
    if (window.dailyRewardsModal?.open) {
      window.dailyRewardsModal.open();
    }
  };

  return (
    <div className="jackpot-player-card-container" ref={dropdownRef}>
      {/* Active Bonus Flame Indicator */}
      {activeBonus && (
        <div 
          className="active-bonus-indicator" 
          title={`+${activeBonus.value}% XP Boost Active! Click to view rewards.`}
          onClick={handleFlameClick}
        >
          <div className="bonus-flame-wrapper">
            <FlameIcon />
            <div className="bonus-flame-glow" />
          </div>
          <div className="bonus-countdown">{bonusCountdown}</div>
        </div>
      )}
      
      <div 
        className="jackpot-player-card" 
        onClick={() => setIsOpen(!isOpen)}
      >
        <div className="player-core">
          <div className={`player-avatar-wrapper ${avatarClass}`}>
            <div 
              className="player-avatar-inner" 
              style={{ background: colorFrom(user.username) }}
            >
              {user.username.slice(0, 2).toUpperCase()}
            </div>
            <img src={borderImage} alt="" className="player-avatar-border" />
          </div>
          <div className="player-info">
            <div className="player-name">{user.username}</div>
            <div className="player-balance">
              <span className="balance-value" id="navbarBalance">{fmt(displayBalance)}</span>
              {freeBattles > 0 && <span className="free-battles-chip">{freeBattles} FREE</span>}
              <img src="/static/coinrushlogos.png" alt="" className="coin-logo" />
            </div>
            <div className="level-progress-label">{progressLabel} coins</div>
            <div className="level-progress-bar">
              <div className="level-progress-fill" style={{ width: `${progressPct}%` }} />
            </div>
          </div>
        </div>
        <div className="player-actions">
          <span className={`level-badge ${levelClass}`}>LVL {level}</span>
          <div className={`dropdown-arrow ${isOpen ? 'open' : ''}`}>
            <svg width="12" height="8" viewBox="0 0 12 8" fill="none">
              <path d="M1 1L6 6L11 1" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
        </div>
      </div>
      
      {/* Dropdown Menu */}
      <div className={`user-dropdown-menu ${isOpen ? 'active' : ''}`}>
        <div className="dropdown-header">
          <div className="dropdown-user-info">
            <div className={`dropdown-avatar-wrapper ${avatarClass}`}>
              <div 
                className="dropdown-avatar-inner" 
                style={{ background: colorFrom(user.username) }}
              >
                {user.username.slice(0, 2).toUpperCase()}
              </div>
              <img src={borderImage} alt="" className="dropdown-avatar-border" />
            </div>
            <div>
              <div className="dropdown-username">{user.username}</div>
              <div className="dropdown-balance">{fmt(displayBalance)} coins</div>
            </div>
          </div>
        </div>
        
        <div className="dropdown-divider" />
        
        <div className="dropdown-options">
          <a href="#" className="dropdown-option" onClick={(e) => { e.preventDefault(); setIsOpen(false); window.openDepositModal?.(); }}>
            <div className="option-icon deposit-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="7 10 12 15 17 10"/>
                <line x1="12" y1="15" x2="12" y2="3"/>
              </svg>
            </div>
            <div className="option-content">
              <div className="option-title">Deposit</div>
            </div>
          </a>
          
          <a href="#" className="dropdown-option" onClick={(e) => { e.preventDefault(); setIsOpen(false); window.openWithdrawModal?.(); }}>
            <div className="option-icon withdraw-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="17 8 12 3 7 8"/>
                <line x1="12" y1="3" x2="12" y2="15"/>
              </svg>
            </div>
            <div className="option-content">
              <div className="option-title">Withdraw</div>
            </div>
          </a>
          
          <a href="/user/profile" className="dropdown-option">
            <div className="option-icon profile-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="3"/>
                <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-2 2 2 2 0 01-2-2v-.09A1.65 1.65 0 009 19.4"/>
              </svg>
            </div>
            <div className="option-content">
              <div className="option-title">Settings</div>
            </div>
          </a>
        </div>
        
        <div className="dropdown-divider" />
        
        <div className="dropdown-options">
          <a href="#" className="dropdown-option logout-option" onClick={(e) => { e.preventDefault(); onLogout?.(); }}>
            <div className="option-icon logout-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                <polyline points="16 17 21 12 16 7"/>
                <line x1="21" y1="12" x2="9" y2="12"/>
              </svg>
            </div>
            <div className="option-content">
              <div className="option-title">Log Out</div>
            </div>
          </a>
        </div>
      </div>
    </div>
  );
}

// ============================================
// AUTH BUTTONS (Logged Out)
// ============================================
function AuthButtons() {
  return (
    <div className="auth-buttons">
      <button 
        className="auth-btn login-btn"
        onClick={() => window.openAuthModal?.('login')}
      >
        Log In
      </button>
      <button 
        className="auth-btn register-btn"
        onClick={() => window.openAuthModal?.('register')}
      >
        Sign Up
      </button>
    </div>
  );
}

// ============================================
// MAIN NAVBAR COMPONENT
// ============================================
function CoinRushNavbar({ user, isConnected, activePage = 'jackpot', onLogout }) {
  const [missionCount, setMissionCount] = useState(0);
  
  // Check sessionStorage SYNCHRONOUSLY before any state is set
  // This ensures consistent behavior across page navigations
  const shouldPulseInitially = typeof window !== 'undefined' && 
    !sessionStorage.getItem('coinrush_mission_pulse_shown');
  
  const [missionPulse, setMissionPulse] = useState(false);
  
  // Handle pulse on first mount only - use a ref to track if we've handled this
  const pulseHandledRef = useRef(false);
  
  useEffect(() => {
    // Only run once per component mount, and only if we should pulse
    if (pulseHandledRef.current) return;
    pulseHandledRef.current = true;
    
    if (shouldPulseInitially && user) {
      // This is the first page load after login - start pulsing
      sessionStorage.setItem('coinrush_mission_pulse_shown', 'true');
      setMissionPulse(true);
      
      // Stop pulsing after 15 seconds
      const pulseTimer = setTimeout(() => {
        setMissionPulse(false);
      }, 15000);
      
      return () => clearTimeout(pulseTimer);
    }
  }, [user]); // Include user so we wait for auth to complete
  
  // Clear pulse flag when user logs out
  useEffect(() => {
    if (!user) {
      sessionStorage.removeItem('coinrush_mission_pulse_shown');
      setMissionPulse(false);
    }
  }, [user]);
  
  // Fetch mission count for logged-in users
  useEffect(() => {
    if (!user) {
      setMissionCount(0);
      return;
    }
    
    const fetchMissionCount = async () => {
      try {
        const res = await fetch('/api/missions', {
          credentials: 'include'
        });
        if (res.ok) {
          const data = await res.json();
          const unclaimed = [...(data.daily || []), ...(data.weekly || [])]
            .filter(m => !m.claimed).length;
          setMissionCount(unclaimed);
        }
      } catch (e) {
        console.error('Failed to fetch mission count:', e);
      }
    };
    
    fetchMissionCount();
    
    // Refresh mission count every 30 seconds
    const interval = setInterval(fetchMissionCount, 30000);
    
    return () => {
      clearInterval(interval);
    };
  }, [user]);
  
  // Determine navbar theme based on active page
  const getNavbarTheme = () => {
    if (activePage === 'slice_dice') return 'theme-neon-pink';
    if (activePage === 'lottery') return 'theme-golden-lottery';
    if (activePage === 'fame') return 'theme-emerald-fame';
    return '';
  };
  
  return (
    <div className={`jackpot-topnav ${getNavbarTheme()}`}>
      <div className="topnav-inner">
        {/* Left Side */}
        <div className="topnav-left">
          {/* Logo */}
          <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>
          
          {/* Live Badge */}
          {isConnected !== undefined && (
            <span className={`topnav-live ${isConnected ? 'connected' : ''}`}>
              <span className="topnav-live-dot" />
              {isConnected ? 'Live lobby' : 'Connecting...'}
            </span>
          )}
          
          {/* Games Dropdown */}
          <GamesDropdown activePage={activePage} />
        </div>
        
        {/* Right Side */}
        <div className="topnav-right">
          {/* Hall of Fame */}
          <a 
            href="/hall-of-fame" 
            className={`topnav-help-btn hof-btn ${activePage === 'fame' ? 'is-active' : ''}`} 
            title="Hall of Fame"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <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>
            <span>Fame</span>
          </a>
          
          {/* Missions */}
          <a 
            href="/missions" 
            className={`topnav-help-btn missions-btn ${activePage === 'missions' ? 'is-active' : ''} ${missionPulse && missionCount > 0 ? 'mission-pulse' : ''}`} 
            title="Daily & Weekly Missions"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="M9 11l3 3L22 4"/>
              <path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/>
            </svg>
            <span>Missions</span>
            {missionCount > 0 && (
              <span className={`mission-badge ${missionPulse ? 'pulse' : ''}`}>{missionCount}</span>
            )}
          </a>
          
          {/* Lottery */}
          <a 
            href="/lottery" 
            className={`topnav-help-btn lottery-btn ${activePage === 'lottery' ? 'is-active' : ''}`} 
            title="Lottery"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <rect x="3" y="3" width="18" height="18" rx="2"></rect>
              <path d="M3 9h18M9 21V9"></path>
            </svg>
            <span>Lottery</span>
          </a>
          
          {/* Social */}
          <a 
            href="/social" 
            className={`topnav-help-btn social-btn ${activePage === 'social' ? 'is-active' : ''}`} 
            title="Guilds & Friends"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
              <circle cx="9" cy="7" r="4"></circle>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
              <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
            </svg>
            <span>Social</span>
          </a>
          
          {/* Daily Rewards */}
          <button 
            className="topnav-help-btn daily-btn" 
            title="Daily Login Rewards"
            onClick={() => window.dailyRewardsModal?.open?.()}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="M20 12v10H4V12"/>
              <path d="M22 7H2v5h20V7z"/>
              <path d="M12 22V7"/>
              <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>
            <span>Daily</span>
          </button>
          
          {/* Rules */}
          <button 
            className="topnav-help-btn rules-btn" 
            title="Game Rules"
            onClick={() => {
              // Call the appropriate rules modal based on current page
              if (activePage === 'barbarian') {
                window.showBarbarianRules?.();
              } else if (activePage === 'premium') {
                window.showPremiumRules?.();
              } else if (activePage === 'slice_dice') {
                window.showSliceDiceRules?.();
              } else if (activePage === 'lottery') {
                window.showLotteryRules?.();
              } else if (activePage === 'fame') {
                window.showFameRules?.();
              } else {
                window.showJackpotRules?.();
              }
            }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14 2 14 8 20 8"/>
              <line x1="16" y1="13" x2="8" y2="13"/>
              <line x1="16" y1="17" x2="8" y2="17"/>
            </svg>
            <span>Rules</span>
          </button>
          
          {/* User Area */}
          <div className="topnav-auth">
            {user ? (
              <UserDropdown user={user} onLogout={onLogout} />
            ) : (
              <AuthButtons />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Export for use
window.CoinRushNavbar = CoinRushNavbar;
