// ============================================
// COINRUSH CHAT - React Component
// Modern, responsive chat with channels
// ============================================

const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ============================================
// SVG ICONS
// ============================================
const ChatIcons = {
  send: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="22" y1="2" x2="11" y2="13"></line>
      <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
    </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"></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>
  ),
  crown: (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 1L9 9L1 8L6 14L4 22H20L18 14L23 8L15 9L12 1Z"/>
    </svg>
  ),
  lock: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
      <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
    </svg>
  ),
  chat: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
    </svg>
  ),
  minimize: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="5" y1="12" x2="19" y2="12"></line>
    </svg>
  ),
  close: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"></line>
      <line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>
  ),
  wifi: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12.55a11 11 0 0 1 14.08 0"></path>
      <path d="M1.42 9a16 16 0 0 1 21.16 0"></path>
      <path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path>
      <line x1="12" y1="20" x2="12.01" y2="20"></line>
    </svg>
  ),
  wifiOff: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="1" y1="1" x2="23" y2="23"></line>
      <path d="M16.72 11.06A10.94 10.94 0 0 1 19 12.55"></path>
      <path d="M5 12.55a10.94 10.94 0 0 1 5.17-2.39"></path>
      <path d="M10.71 5.05A16 16 0 0 1 22.58 9"></path>
      <path d="M1.42 9a15.91 15.91 0 0 1 4.7-2.88"></path>
      <path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path>
      <line x1="12" y1="20" x2="12.01" y2="20"></line>
    </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"></polygon>
    </svg>
  ),
  sparkles: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3L14.5 8.5L20 9L16 13L17 19L12 16L7 19L8 13L4 9L9.5 8.5L12 3Z"></path>
    </svg>
  ),
  chevronDown: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="6 9 12 15 18 9"></polyline>
    </svg>
  ),
};

// ============================================
// UTILITY FUNCTIONS
// ============================================

// Generate consistent color for username
function generateUserColor(username) {
  if (!username) return '#94a3b8';
  const colors = [
    '#f472b6', '#fb7185', '#f97316', '#facc15', 
    '#a3e635', '#4ade80', '#2dd4bf', '#22d3ee',
    '#60a5fa', '#818cf8', '#a78bfa', '#c084fc',
    '#e879f9', '#fb923c', '#fbbf24', '#34d399'
  ];
  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = username.charCodeAt(i) + ((hash << 5) - hash);
  }
  return colors[Math.abs(hash) % colors.length];
}

// Format timestamp for display
function formatTime(timestamp) {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const now = new Date();
  const diffMs = now - date;
  const diffMins = Math.floor(diffMs / 60000);
  
  if (diffMins < 1) return 'now';
  if (diffMins < 60) return `${diffMins}m`;
  
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return `${diffHours}h`;
  
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

// Get level badge info
function getLevelBadge(level) {
  if (!level || level < 1) return { class: 'newbie', label: 'LV1', title: null, color: '#94a3b8' };
  
  if (level >= 50) {
    return { class: 'legendary', label: `LV${level}`, title: 'LEGEND', color: '#f472b6' };
  } else if (level >= 30) {
    return { class: 'master', label: `LV${level}`, title: 'MASTER', color: '#a78bfa' };
  } else if (level >= 20) {
    return { class: 'expert', label: `LV${level}`, title: 'EXPERT', color: '#60a5fa' };
  } else if (level >= 10) {
    return { class: 'vip', label: `LV${level}`, title: 'VIP', color: '#fbbf24' };
  } else if (level >= 5) {
    return { class: 'regular', label: `LV${level}`, title: null, color: '#4ade80' };
  }
  return { class: 'newbie', label: `LV${level}`, title: null, color: '#94a3b8' };
}

// Get avatar border class based on level
function getAvatarBorderClass(level) {
  if (!level || level < 5) return 'avatar-rookie';
  if (level < 10) return 'avatar-bronze';
  if (level < 15) return 'avatar-silver';
  if (level < 20) return 'avatar-gold';
  if (level < 30) return 'avatar-platinum'; // Ruby/Platinum
  if (level < 40) return 'avatar-diamond';
  return 'avatar-challenger'; // Mythic/Legendary
}

// Storage keys
const STORAGE_KEYS = {
  coinrush: 'cr_chat_coinrush_v2',
  vip: 'cr_chat_vip_v2',
};

// ============================================
// MESSAGE COMPONENT
// ============================================
function ChatMessage({ message, isOwnMessage, currentUser }) {
  const userColor = useMemo(() => generateUserColor(message.username), [message.username]);
  const levelBadge = useMemo(() => getLevelBadge(message.level), [message.level]);
  const timeAgo = useMemo(() => formatTime(message.timestamp), [message.timestamp]);
  const borderClass = useMemo(() => getAvatarBorderClass(message.level), [message.level]);
  
  const isSystem = message.username === 'system' || message.type === 'system';
  
  if (isSystem) {
    return (
      <div className="cr-chat-message system">
        <div className="cr-chat-system-content">
          <span className="cr-chat-system-icon">{ChatIcons.sparkles}</span>
          <span className="cr-chat-system-text">{message.message}</span>
        </div>
      </div>
    );
  }
  
  return (
    <div className={`cr-chat-message ${isOwnMessage ? 'own' : ''}`}>
      <div className={`cr-chat-avatar-wrapper ${borderClass}`}>
        <div className="cr-chat-message-avatar" style={{ background: userColor }}>
          {message.username?.charAt(0).toUpperCase() || '?'}
        </div>
      </div>
      <div className="cr-chat-message-content">
        <div className="cr-chat-message-header">
          <span className="cr-chat-username" style={{ color: userColor }}>
            {message.username}
          </span>
          {levelBadge && (
            <span className={`cr-chat-level-badge ${levelBadge.class}`} style={{ borderColor: levelBadge.color }}>
              {levelBadge.label}
            </span>
          )}
          {levelBadge && levelBadge.title && (
            <span className={`cr-chat-title-badge ${levelBadge.class}`} style={{ borderColor: levelBadge.color }}>
              {levelBadge.title}
            </span>
          )}
          <span className="cr-chat-time">{timeAgo}</span>
        </div>
        <div className="cr-chat-message-text">
          {message.message}
        </div>
      </div>
    </div>
  );
}

// ============================================
// MAIN CHAT COMPONENT
// ============================================
function CoinRushChatApp({ currentUser, theme = 'gold' }) {
  const [messages, setMessages] = useState({ coinrush: [], vip: [] });
  const [currentChannel, setCurrentChannel] = useState('coinrush');
  const [inputValue, setInputValue] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [onlineCount, setOnlineCount] = useState(0);
  const [isMinimized, setIsMinimized] = useState(false);
  const [showNewMessage, setShowNewMessage] = useState(false);
  const [banInfo, setBanInfo] = useState(null);
  
  const wsRef = useRef(null);
  const messagesContainerRef = useRef(null);
  const inputRef = useRef(null);
  const reconnectTimeoutRef = useRef(null);
  const reconnectAttemptsRef = useRef(0);
  const handleWSMessageRef = useRef(null);
  
  const userLevel = currentUser?.level || currentUser?.level_info?.current_level || 0;
  const isVIPUnlocked = userLevel >= 10;
  
  // Load messages from localStorage
  const loadStoredMessages = useCallback((channel) => {
    try {
      const key = STORAGE_KEYS[channel];
      const stored = localStorage.getItem(key);
      if (!stored) return [];
      
      const msgs = JSON.parse(stored);
      const cutoff = Date.now() - (4 * 60 * 60 * 1000); // 4 hours
      
      return msgs.filter(m => {
        const ts = m.timestamp ? new Date(m.timestamp).getTime() : 0;
        return ts >= cutoff;
      }).slice(-100);
    } catch {
      return [];
    }
  }, []);
  
  // Save messages to localStorage
  const saveMessages = useCallback((channel, msgs) => {
    try {
      const key = STORAGE_KEYS[channel];
      const cutoff = Date.now() - (4 * 60 * 60 * 1000);
      const filtered = msgs.filter(m => {
        const ts = m.timestamp ? new Date(m.timestamp).getTime() : 0;
        return ts >= cutoff;
      }).slice(-100);
      localStorage.setItem(key, JSON.stringify(filtered));
    } catch (e) {
      console.error('Failed to save chat messages:', e);
    }
  }, []);
  
  // Initialize messages from storage
  useEffect(() => {
    setMessages({
      coinrush: loadStoredMessages('coinrush'),
      vip: loadStoredMessages('vip'),
    });
  }, [loadStoredMessages]);
  
  // Scroll to bottom when new messages arrive
  const scrollToBottom = useCallback(() => {
    if (messagesContainerRef.current) {
      const { scrollHeight, clientHeight } = messagesContainerRef.current;
      messagesContainerRef.current.scrollTo({
        top: scrollHeight,
        behavior: 'smooth'
      });
    }
  }, []);
  
  // Handle incoming WebSocket messages
  const handleWSMessage = useCallback((event) => {
    try {
      const data = JSON.parse(event.data);
      
      if (data.type === 'chat') {
        const channel = data.channel || 'coinrush';
        const newMessage = {
          id: Date.now() + Math.random(),
          username: data.username,
          message: data.message,
          level: data.level,
          timestamp: data.timestamp || new Date().toISOString(),
        };
        
        setMessages(prev => {
          const currentList = prev[channel] || [];
          
          // Prevent duplicate messages (same content/user within 500ms)
          const isDuplicate = currentList.some(m => 
            m.username === newMessage.username && 
            m.message === newMessage.message && 
            Math.abs(new Date(m.timestamp).getTime() - new Date(newMessage.timestamp).getTime()) < 500
          );
          
          if (isDuplicate) return prev;

          const updated = {
            ...prev,
            [channel]: [...currentList, newMessage].slice(-100),
          };
          saveMessages(channel, updated[channel]);
          return updated;
        });
        
        // Show notification if minimized or different channel
        if (isMinimized || channel !== currentChannel) {
          setShowNewMessage(true);
        }
        
        // Scroll if on current channel
        if (channel === currentChannel && !isMinimized) {
          setTimeout(scrollToBottom, 50);
        }
      } else if (data.type === 'online_count') {
        setOnlineCount(data.count || 0);
      } else if (data.type === 'chat_moderation') {
        if (data.status === 'banned' || data.action === 'ban') {
          setBanInfo({
            until: data.until,
            hours: data.hours,
          });
        }
      } else if (data.type === 'system') {
        // System messages go to coinrush channel
        const sysMessage = {
          id: Date.now() + Math.random(),
          username: 'system',
          message: data.msg || data.message,
          type: 'system',
          timestamp: data.ts || new Date().toISOString(),
        };
        setMessages(prev => ({
          ...prev,
          coinrush: [...prev.coinrush, sysMessage].slice(-100),
        }));
      }
    } catch (e) {
      console.error('Failed to parse chat message:', e);
    }
  }, [currentChannel, isMinimized, saveMessages, scrollToBottom]);

  // Update ref whenever handler changes
  useEffect(() => {
    handleWSMessageRef.current = handleWSMessage;
  }, [handleWSMessage]);
  
  // WebSocket connection
  const connectWS = useCallback(() => {
    if (wsRef.current?.readyState === WebSocket.OPEN) return;
    
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const ws = new WebSocket(`${protocol}//${window.location.host}/ws/lobby`);
    
    ws.onopen = () => {
      console.log('Chat connected');
      setIsConnected(true);
      reconnectAttemptsRef.current = 0;
    };
    
    ws.onmessage = (event) => {
      if (handleWSMessageRef.current) {
        handleWSMessageRef.current(event);
      }
    };
    
    ws.onerror = () => {
      console.error('Chat connection error');
      setIsConnected(false);
    };
    
    ws.onclose = () => {
      console.log('Chat disconnected');
      setIsConnected(false);
      wsRef.current = null;
      
      // Reconnect with exponential backoff
      if (reconnectAttemptsRef.current < 5) {
        const delay = Math.min(1000 * Math.pow(2, reconnectAttemptsRef.current), 30000);
        reconnectAttemptsRef.current++;
        reconnectTimeoutRef.current = setTimeout(connectWS, delay);
      }
    };
    
    wsRef.current = ws;
  }, []);
  
  // Connect on mount
  useEffect(() => {
    connectWS();
    return () => {
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
      }
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, [connectWS]);
  
  // Send message
  const sendMessage = useCallback(() => {
    if (!inputValue.trim() || !currentUser || !wsRef.current) return;
    
    // Check if banned
    if (banInfo) {
      const banEnd = new Date(banInfo.until);
      if (banEnd > new Date()) {
        return; // Still banned
      }
      setBanInfo(null);
    }
    
    // Check VIP access
    if (currentChannel === 'vip' && !isVIPUnlocked) {
      return;
    }
    
    const messageData = {
      type: 'chat',
      channel: currentChannel,
      message: inputValue.trim(),
    };
    
    try {
      wsRef.current.send(JSON.stringify(messageData));
      setInputValue('');
      inputRef.current?.focus();
    } catch (e) {
      console.error('Failed to send message:', e);
    }
  }, [inputValue, currentUser, currentChannel, banInfo, isVIPUnlocked]);
  
  // Handle Enter key
  const handleKeyPress = useCallback((e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  }, [sendMessage]);
  
  // Switch channel
  const switchChannel = useCallback((channel) => {
    if (channel === 'vip' && !isVIPUnlocked) return;
    setCurrentChannel(channel);
    setShowNewMessage(false);
    setTimeout(scrollToBottom, 50);
  }, [isVIPUnlocked, scrollToBottom]);
  
  // Toggle minimize
  const toggleMinimize = useCallback(() => {
    setIsMinimized(prev => !prev);
    setShowNewMessage(false);
    if (isMinimized) {
      setTimeout(scrollToBottom, 100);
    }
  }, [isMinimized, scrollToBottom]);
  
  const currentMessages = messages[currentChannel] || [];
  
  // Render minimized state
  if (isMinimized) {
    return (
      <div className={`cr-chat-minimized ${theme}`} onClick={toggleMinimize}>
        <div className="cr-chat-minimized-icon">
          {ChatIcons.chat}
        </div>
        <span className="cr-chat-minimized-label">Chat</span>
        {showNewMessage && <div className="cr-chat-notification-dot" />}
        <div className="cr-chat-online-badge">
          <div className="cr-chat-online-pulse" />
          {onlineCount}
        </div>
      </div>
    );
  }
  
  return (
    <div className={`cr-chat-container ${theme}`}>
      {/* Header */}
      <div className="cr-chat-header">
        <div className="cr-chat-header-left">
          <div className="cr-chat-header-icon">{ChatIcons.chat}</div>
          <span className="cr-chat-header-title">LIVE CHAT</span>
        </div>
        <div className="cr-chat-header-right">
          <div className="cr-chat-online-indicator">
            <div className="cr-chat-online-pulse" />
            <span>{onlineCount} online</span>
          </div>
          <button className="cr-chat-minimize-btn" onClick={toggleMinimize}>
            {ChatIcons.minimize}
          </button>
        </div>
      </div>
      
      {/* Channel Tabs */}
      <div className="cr-chat-tabs">
        <button 
          className={`cr-chat-tab ${currentChannel === 'coinrush' ? 'active' : ''}`}
          onClick={() => switchChannel('coinrush')}
        >
          <span className="cr-chat-tab-icon">{ChatIcons.users}</span>
          <span>CoinRush</span>
        </button>
        <button 
          className={`cr-chat-tab ${currentChannel === 'vip' ? 'active' : ''} ${!isVIPUnlocked ? 'locked' : ''}`}
          onClick={() => switchChannel('vip')}
        >
          <span className="cr-chat-tab-icon">{isVIPUnlocked ? ChatIcons.crown : ChatIcons.lock}</span>
          <span>VIP</span>
          {!isVIPUnlocked && <span className="cr-chat-tab-badge">LVL 10</span>}
        </button>
      </div>
      
      {/* Messages Area */}
      <div className="cr-chat-messages" ref={messagesContainerRef}>
        {currentChannel === 'vip' && !isVIPUnlocked ? (
          <div className="cr-chat-locked-panel">
            <div className="cr-chat-locked-icon">{ChatIcons.crown}</div>
            <h3>VIP Lounge</h3>
            <p>Exclusive chat for dedicated players</p>
            <div className="cr-chat-locked-requirement">
              Reach <strong>Level 10</strong> to unlock
              {currentUser && <span className="cr-chat-current-level">Current: LVL {userLevel}</span>}
            </div>
          </div>
        ) : currentMessages.length === 0 ? (
          <div className="cr-chat-empty">
            <div className="cr-chat-empty-icon">{ChatIcons.chat}</div>
            <h3>{currentChannel === 'vip' ? 'VIP Lounge' : 'Welcome to Chat'}</h3>
            <p>{currentChannel === 'vip' ? 'Exclusive room for VIP members' : 'Be the first to say something!'}</p>
          </div>
        ) : (
          <>
            {currentMessages.map((msg) => (
              <ChatMessage 
                key={msg.id || msg.timestamp} 
                message={msg}
                isOwnMessage={msg.username === currentUser?.username}
                currentUser={currentUser}
              />
            ))}
          </>
        )}
      </div>
      
      {/* Input Area */}
      <div className="cr-chat-input-area">
        {banInfo && new Date(banInfo.until) > new Date() ? (
          <div className="cr-chat-banned">
            <span className="cr-chat-banned-icon">{ChatIcons.lock}</span>
            <span>Chat banned until {new Date(banInfo.until).toLocaleTimeString()}</span>
          </div>
        ) : !currentUser ? (
          <div className="cr-chat-login-prompt">
            <span>Login to chat</span>
          </div>
        ) : (
          <div className="cr-chat-input-wrapper">
            <input
              ref={inputRef}
              type="text"
              className="cr-chat-input"
              placeholder={currentChannel === 'vip' ? 'VIP message...' : 'Type a message...'}
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              maxLength={200}
              disabled={currentChannel === 'vip' && !isVIPUnlocked}
            />
            <button 
              className="cr-chat-send-btn"
              onClick={sendMessage}
              disabled={!inputValue.trim() || (currentChannel === 'vip' && !isVIPUnlocked)}
            >
              {ChatIcons.send}
            </button>
          </div>
        )}
        <div className="cr-chat-footer">
          <div className={`cr-chat-connection-status ${isConnected ? 'connected' : ''}`}>
            {isConnected ? ChatIcons.wifi : ChatIcons.wifiOff}
            <span>{isConnected ? 'Connected' : 'Reconnecting...'}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// FLOATING CHAT WRAPPER
// ============================================
function FloatingChat({ currentUser, theme = 'gold' }) {
  const [isOpen, setIsOpen] = useState(false);
  const [hasNewMessage, setHasNewMessage] = useState(false);
  
  return (
    <>
      {/* Floating Button */}
      {!isOpen && (
        <button 
          className={`cr-floating-chat-btn ${theme}`}
          onClick={() => { setIsOpen(true); setHasNewMessage(false); }}
        >
          {ChatIcons.chat}
          {hasNewMessage && <div className="cr-floating-notification" />}
        </button>
      )}
      
      {/* Chat Panel */}
      {isOpen && (
        <div className={`cr-floating-chat-panel ${theme}`}>
          <button 
            className="cr-floating-close-btn"
            onClick={() => setIsOpen(false)}
          >
            {ChatIcons.close}
          </button>
          <CoinRushChatApp currentUser={currentUser} theme={theme} />
        </div>
      )}
    </>
  );
}

// ============================================
// RENDER FUNCTIONS
// ============================================
window.renderCoinRushChat = function(containerId, currentUser, theme = 'gold') {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Chat container #${containerId} not found`);
    return;
  }
  
  const root = ReactDOM.createRoot(container);
  root.render(<CoinRushChatApp currentUser={currentUser} theme={theme} />);
};

window.renderFloatingChat = function(containerId, currentUser, theme = 'gold') {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Floating chat container #${containerId} not found`);
    return;
  }
  
  const root = ReactDOM.createRoot(container);
  root.render(<FloatingChat currentUser={currentUser} theme={theme} />);
};

// Export for use
window.CoinRushChatApp = CoinRushChatApp;
window.FloatingChat = FloatingChat;
