/**
 * CoinRush Social Panel - Friends, Guilds, and Private Messages
 * Comprehensive social system with React
 */

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

// ============================================
// ICONS
// ============================================
const SocialIcons = {
  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>
  ),
  guild: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 2L2 7l10 5 10-5-10-5z"></path>
      <path d="M2 17l10 5 10-5"></path>
      <path d="M2 12l10 5 10-5"></path>
    </svg>
  ),
  message: (
    <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>
  ),
  add: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="12" y1="5" x2="12" y2="19"></line>
      <line x1="5" y1="12" x2="19" y2="12"></line>
    </svg>
  ),
  check: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12"></polyline>
    </svg>
  ),
  x: (
    <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>
  ),
  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>
  ),
  crown: (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 2L15 9L22 9.5L17 14L18.5 21L12 17L5.5 21L7 14L2 9.5L9 9L12 2Z"></path>
    </svg>
  ),
  logout: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
      <polyline points="16 17 21 12 16 7"></polyline>
      <line x1="21" y1="12" x2="9" y2="12"></line>
    </svg>
  ),
};

// ============================================
// FRIEND LIST COMPONENT
// ============================================
function FriendsList({ currentUser, onOpenDM }) {
  const [friends, setFriends] = useState([]);
  const [requests, setRequests] = useState({ received: [], sent: [] });
  const [showAddFriend, setShowAddFriend] = useState(false);
  const [addUsername, setAddUsername] = useState('');
  const [loading, setLoading] = useState(false);

  const loadFriends = useCallback(async () => {
    try {
      const res = await fetch('/api/friends/list');
      if (res.ok) {
        const data = await res.json();
        setFriends(data.friends || []);
      }
    } catch (e) {
      console.error('Failed to load friends:', e);
    }
  }, []);

  const loadRequests = useCallback(async () => {
    try {
      const res = await fetch('/api/friends/requests');
      if (res.ok) {
        const data = await res.json();
        setRequests(data);
      }
    } catch (e) {
      console.error('Failed to load requests:', e);
    }
  }, []);

  useEffect(() => {
    loadFriends();
    loadRequests();
    const interval = setInterval(() => {
      loadFriends();
      loadRequests();
    }, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, [loadFriends, loadRequests]);

  const sendRequest = async () => {
    if (!addUsername.trim()) return;
    setLoading(true);
    try {
      const res = await fetch('/api/friends/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: addUsername.trim() })
      });
      const data = await res.json();
      if (res.ok) {
        alert(data.message);
        setAddUsername('');
        setShowAddFriend(false);
        loadFriends();
        loadRequests();
      } else {
        alert(data.detail || 'Failed to send request');
      }
    } catch (e) {
      alert('Network error');
    } finally {
      setLoading(false);
    }
  };

  const acceptRequest = async (requestId) => {
    try {
      const res = await fetch(`/api/friends/accept/${requestId}`, { method: 'POST' });
      if (res.ok) {
        loadFriends();
        loadRequests();
      }
    } catch (e) {
      console.error('Failed to accept:', e);
    }
  };

  const rejectRequest = async (requestId) => {
    try {
      const res = await fetch(`/api/friends/reject/${requestId}`, { method: 'POST' });
      if (res.ok) {
        loadRequests();
      }
    } catch (e) {
      console.error('Failed to reject:', e);
    }
  };

  const removeFriend = async (friendId) => {
    if (!confirm('Remove this friend?')) return;
    try {
      const res = await fetch(`/api/friends/remove/${friendId}`, { method: 'DELETE' });
      if (res.ok) {
        loadFriends();
      }
    } catch (e) {
      console.error('Failed to remove:', e);
    }
  };

  return (
    <div className="social-friends-panel">
      <div className="social-friends-header">
        <h3>{SocialIcons.users} Friends ({friends.length})</h3>
        <button className="btn-icon" onClick={() => setShowAddFriend(!showAddFriend)}>
          {SocialIcons.add}
        </button>
      </div>

      {showAddFriend && (
        <div className="social-add-friend">
          <input
            type="text"
            placeholder="Enter username..."
            value={addUsername}
            onChange={(e) => setAddUsername(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && sendRequest()}
            disabled={loading}
          />
          <button onClick={sendRequest} disabled={loading || !addUsername.trim()}>
            {loading ? 'Sending...' : 'Send Request'}
          </button>
        </div>
      )}

      {requests.received.length > 0 && (
        <div className="social-requests-section">
          <h4>Friend Requests ({requests.received.length})</h4>
          {requests.received.map(req => (
            <div key={req.id} className="social-request-item">
              <div className="social-request-info">
                <span className="username">{req.username}</span>
                <span className="level">LVL {req.level}</span>
              </div>
              <div className="social-request-actions">
                <button className="btn-accept" onClick={() => acceptRequest(req.id)}>
                  {SocialIcons.check}
                </button>
                <button className="btn-reject" onClick={() => rejectRequest(req.id)}>
                  {SocialIcons.x}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="social-friends-list">
        {friends.length === 0 ? (
          <div className="social-empty-state">
            <p>No friends yet. Add some to start chatting!</p>
          </div>
        ) : (
          friends.map(friend => (
            <div key={friend.id} className="social-friend-item">
              <div className="social-friend-avatar">
                <div className={`online-indicator ${friend.is_online ? 'online' : ''}`}></div>
                {friend.username.charAt(0).toUpperCase()}
              </div>
              <div className="social-friend-info">
                <span className="username">{friend.username}</span>
                <span className="level">LVL {friend.level}</span>
              </div>
              <div className="social-friend-actions">
                <button 
                  className="btn-icon" 
                  onClick={() => onOpenDM && onOpenDM(friend)}
                  title="Send message"
                >
                  {SocialIcons.message}
                </button>
                <button 
                  className="btn-icon btn-danger" 
                  onClick={() => removeFriend(friend.id)}
                  title="Remove friend"
                >
                  {SocialIcons.x}
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

// ============================================
// PRIVATE MESSAGE MODAL
// ============================================
function PrivateMessageModal({ friend, onClose, currentUser }) {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef(null);

  const loadMessages = useCallback(async () => {
    if (!friend) return;
    try {
      const res = await fetch(`/api/messages/conversation/${friend.id}`);
      if (res.ok) {
        const data = await res.json();
        setMessages(data.messages || []);
      }
    } catch (e) {
      console.error('Failed to load messages:', e);
    }
  }, [friend]);

  useEffect(() => {
    loadMessages();
    const interval = setInterval(loadMessages, 3000); // Poll every 3 seconds
    return () => clearInterval(interval);
  }, [loadMessages]);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const sendMessage = async () => {
    if (!inputValue.trim() || loading) return;
    setLoading(true);
    try {
      const res = await fetch('/api/messages/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          receiver_username: friend.username,
          message: inputValue.trim()
        })
      });
      if (res.ok) {
        setInputValue('');
        loadMessages();
      } else {
        const data = await res.json();
        alert(data.detail || 'Failed to send message');
      }
    } catch (e) {
      alert('Network error');
    } finally {
      setLoading(false);
    }
  };

  if (!friend) return null;

  return (
    <div className="social-modal-overlay" onClick={onClose}>
      <div className="social-modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="social-modal-header">
          <h3>{SocialIcons.message} {friend.username}</h3>
          <button className="btn-close" onClick={onClose}>{SocialIcons.x}</button>
        </div>
        
        <div className="social-messages-container">
          {messages.length === 0 ? (
            <div className="social-empty-state">
              <p>No messages yet. Start the conversation!</p>
            </div>
          ) : (
            messages.map((msg, idx) => (
              <div key={msg.id || idx} className={`social-message ${msg.is_mine ? 'mine' : 'theirs'}`}>
                <div className="social-message-content">
                  {msg.message}
                </div>
                <div className="social-message-time">
                  {new Date(msg.created_at).toLocaleTimeString()}
                </div>
              </div>
            ))
          )}
          <div ref={messagesEndRef} />
        </div>

        <div className="social-message-input">
          <input
            type="text"
            placeholder="Type a message..."
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
            disabled={loading}
            maxLength={500}
          />
          <button onClick={sendMessage} disabled={loading || !inputValue.trim()}>
            {SocialIcons.send}
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================
// GUILD WARS COMPONENT
// ============================================
function GuildWars({ guild, myRole }) {
  const [activeWar, setActiveWar] = useState(null);
  const [warHistory, setWarHistory] = useState([]);
  const [timeRemaining, setTimeRemaining] = useState('--:--:--');

  useEffect(() => {
    // Mock data - in production, fetch from API
    const mockWar = {
      id: 1,
      enemy_guild: { name: 'Shadow Legion', tag: 'SHDW', score: 4250 },
      our_score: 5120,
      status: 'active',
      ends_at: new Date(Date.now() + 3600000 * 2).toISOString() // 2 hours
    };
    setActiveWar(mockWar);

    // Timer countdown
    const timer = setInterval(() => {
      if (mockWar) {
        const now = new Date();
        const end = new Date(mockWar.ends_at);
        const diff = end - now;
        if (diff > 0) {
          const hours = Math.floor(diff / 3600000);
          const mins = Math.floor((diff % 3600000) / 60000);
          const secs = Math.floor((diff % 60000) / 1000);
          setTimeRemaining(`${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`);
        } else {
          setTimeRemaining('ENDED');
        }
      }
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  if (!activeWar) {
    return (
      <div className="guild-wars-section">
        <div className="guild-wars-header">
          <h3>
            <span className="wars-icon">⚔️</span>
            Guild Wars
          </h3>
          <span className="war-status-badge pending">No Active War</span>
        </div>
        <div className="social-empty-state" style={{padding: '40px 20px'}}>
          <p>No active guild war. Start one to compete against other guilds!</p>
          {myRole === 'leader' && (
            <button className="social-btn-gold" style={{marginTop: '16px'}}>
              🏴 Declare War
            </button>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="guild-wars-section">
      <div className="guild-wars-header">
        <h3>
          <span className="wars-icon">⚔️</span>
          Guild Wars
        </h3>
        <span className="war-status-badge active">🔴 LIVE</span>
      </div>
      
      <div className="war-matchup">
        <div className="war-team">
          <span className="war-team-name">[{guild?.tag || 'YOU'}]</span>
          <span className="war-team-score">{activeWar.our_score.toLocaleString()}</span>
        </div>
        <div className="war-vs">VS</div>
        <div className="war-team enemy">
          <span className="war-team-name">[{activeWar.enemy_guild.tag}]</span>
          <span className="war-team-score">{activeWar.enemy_guild.score.toLocaleString()}</span>
        </div>
      </div>

      <div className="war-timer">
        <div className="war-timer-label">Time Remaining</div>
        <div className="war-timer-value">{timeRemaining}</div>
      </div>
    </div>
  );
}

// ============================================
// WEEKLY CHALLENGES COMPONENT
// ============================================
function WeeklyChallenges({ guild }) {
  const [challenges, setChallenges] = useState([]);
  const [timeUntilReset, setTimeUntilReset] = useState('');

  useEffect(() => {
    // Mock challenges data
    setChallenges([
      {
        id: 1,
        title: 'Wager $50,000 collectively',
        icon: '💰',
        iconType: 'wager',
        current: 32500,
        target: 50000,
        reward: 5000,
        completed: false
      },
      {
        id: 2,
        title: 'Win 100 games as a guild',
        icon: '🏆',
        iconType: 'wins',
        current: 87,
        target: 100,
        reward: 3000,
        completed: false
      },
      {
        id: 3,
        title: 'Have 5 members hit a 10x multiplier',
        icon: '🔥',
        iconType: 'streak',
        current: 5,
        target: 5,
        reward: 2500,
        completed: true
      },
      {
        id: 4,
        title: 'Recruit 3 new members',
        icon: '👥',
        iconType: 'social',
        current: 1,
        target: 3,
        reward: 1500,
        completed: false
      }
    ]);

    // Calculate time until Sunday midnight
    const now = new Date();
    const sunday = new Date(now);
    sunday.setDate(sunday.getDate() + (7 - sunday.getDay()));
    sunday.setHours(23, 59, 59, 999);
    
    const updateTimer = () => {
      const diff = sunday - new Date();
      if (diff > 0) {
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        setTimeUntilReset(`${days}d ${hours}h`);
      }
    };
    
    updateTimer();
    const timer = setInterval(updateTimer, 60000);
    return () => clearInterval(timer);
  }, []);

  return (
    <div className="challenges-section">
      <div className="challenges-header">
        <h3>
          <span style={{fontSize: '1.5rem'}}>🎯</span>
          Weekly Challenges
        </h3>
        <div className="challenges-timer">
          <span>⏱️</span>
          Resets in {timeUntilReset}
        </div>
      </div>

      {challenges.map(challenge => (
        <div key={challenge.id} className={`challenge-card ${challenge.completed ? 'completed' : ''}`}>
          <div className={`challenge-icon ${challenge.iconType}`}>
            {challenge.icon}
          </div>
          <div className="challenge-info">
            <div className="challenge-title">{challenge.title}</div>
            <div className="challenge-progress-bar">
              <div 
                className="challenge-progress-fill" 
                style={{width: `${Math.min(100, (challenge.current / challenge.target) * 100)}%`}}
              ></div>
            </div>
            <div className="challenge-progress-text">
              {challenge.current.toLocaleString()} / {challenge.target.toLocaleString()}
            </div>
          </div>
          <div className="challenge-reward">
            <span className="challenge-reward-value">${(challenge.reward / 100).toFixed(0)}</span>
            <span className="challenge-reward-label">Reward</span>
          </div>
        </div>
      ))}
    </div>
  );
}

// ============================================
// GUILD PERKS COMPONENT
// ============================================
function GuildPerks({ guild, level }) {
  const allPerks = [
    { id: 1, name: 'Lucky Bonus', description: '+1% on all wins', icon: '🍀', requiredLevel: 1, active: level >= 1 },
    { id: 2, name: 'Group Chat', description: 'Private guild chat', icon: '💬', requiredLevel: 2, active: level >= 2 },
    { id: 3, name: 'XP Boost', description: '+10% XP for all members', icon: '⚡', requiredLevel: 3, active: level >= 3 },
    { id: 4, name: 'Daily Bonus', description: 'Extra daily reward', icon: '🎁', requiredLevel: 5, active: level >= 5 },
    { id: 5, name: 'Fee Rebate', description: '-5% platform fees', icon: '💎', requiredLevel: 7, active: level >= 7 },
    { id: 6, name: 'VIP Access', description: 'Exclusive games', icon: '👑', requiredLevel: 10, active: level >= 10 },
  ];

  return (
    <div className="perks-section">
      <h4 style={{color: 'var(--social-text-main)', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px'}}>
        <span style={{fontSize: '1.3rem'}}>✨</span> Guild Perks
      </h4>
      <div className="perks-grid">
        {allPerks.map(perk => (
          <div key={perk.id} className={`perk-card ${perk.active ? 'active' : 'locked'}`}>
            <div className="perk-icon">{perk.icon}</div>
            <div className="perk-name">{perk.name}</div>
            <div className="perk-description">{perk.description}</div>
            {!perk.active && (
              <div className="perk-requirement">Level {perk.requiredLevel}</div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================
// GUILD ACHIEVEMENTS COMPONENT
// ============================================
function GuildAchievements({ guild }) {
  const achievements = [
    { id: 1, name: 'First Steps', icon: '👶', unlocked: true },
    { id: 2, name: 'Growing Strong', icon: '💪', unlocked: true },
    { id: 3, name: 'War Victor', icon: '⚔️', unlocked: false },
    { id: 4, name: 'Millionaire', icon: '💰', unlocked: true },
    { id: 5, name: 'Social Butterfly', icon: '🦋', unlocked: false },
    { id: 6, name: 'Challenge Master', icon: '🎯', unlocked: false },
    { id: 7, name: 'Legendary', icon: '🌟', unlocked: false },
    { id: 8, name: 'Undefeated', icon: '🏆', unlocked: false },
  ];

  return (
    <div className="achievements-section" style={{marginTop: '24px'}}>
      <h4 style={{color: 'var(--social-text-main)', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px'}}>
        <span style={{fontSize: '1.3rem'}}>🏅</span> Achievements
      </h4>
      <div className="achievements-grid">
        {achievements.map(ach => (
          <div key={ach.id} className={`achievement-badge ${ach.unlocked ? 'unlocked' : ''}`}>
            <div className="achievement-icon">{ach.icon}</div>
            <div className="achievement-name">{ach.name}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================
// GUILD ACTIVITY FEED COMPONENT
// ============================================
function GuildActivityFeed({ guildId }) {
  const [activities, setActivities] = useState([]);

  useEffect(() => {
    // Mock activity data
    setActivities([
      { id: 1, user: 'CryptoKing', action: 'won big', amount: '+$2,450', time: '2m ago', positive: true },
      { id: 2, user: 'LuckyAce', action: 'completed challenge', amount: '+$50', time: '5m ago', positive: true },
      { id: 3, user: 'NightRider', action: 'donated to treasury', amount: '+$100', time: '12m ago', positive: true },
      { id: 4, user: 'StarGazer', action: 'joined the guild', amount: null, time: '25m ago', positive: null },
      { id: 5, user: 'WaveRunner', action: 'won war point', amount: '+10 pts', time: '32m ago', positive: true },
    ]);
  }, [guildId]);

  return (
    <div className="activity-feed">
      <div className="activity-header">
        <h4>
          <span className="activity-live-dot"></span>
          Live Activity
        </h4>
      </div>
      <div className="activity-list">
        {activities.map(activity => (
          <div key={activity.id} className="activity-item">
            <div className="activity-avatar">
              {activity.user.charAt(0)}
            </div>
            <div className="activity-content">
              <div className="activity-text">
                <strong>{activity.user}</strong> {activity.action}
              </div>
              <div className="activity-time">{activity.time}</div>
            </div>
            {activity.amount && (
              <div className={`activity-amount ${activity.positive ? 'positive' : 'negative'}`}>
                {activity.amount}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================
// GUILD PANEL
// ============================================
// ============================================
// Donate Modal
// ============================================
function DonateModal({ onClose, onDonate }) {
  const [amount, setAmount] = useState('');

  return (
    <div className="social-modal-overlay" onClick={onClose}>
      <div className="social-modal-content small" onClick={e => e.stopPropagation()}>
        <div className="social-modal-header">
          <h3>Donate to Treasury</h3>
          <button className="btn-close" onClick={onClose}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
        <div className="social-modal-body">
          <p className="modal-description">
            Contribute to your guild's treasury to help unlock perks and events.
          </p>
          <div className="donate-input-group">
            <span className="currency-symbol">$</span>
            <input
              type="number"
              className="donate-input"
              placeholder="Amount"
              value={amount}
              onChange={e => setAmount(e.target.value)}
              autoFocus
            />
          </div>
          <div className="modal-actions">
            <button className="btn-secondary" onClick={onClose}>Cancel</button>
            <button className="btn-donate-confirm" onClick={() => onDonate(parseFloat(amount) * 100)}>Donate</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function GuildPanel({ currentUser }) {
  const [myGuild, setMyGuild] = useState(null);
  const [activeTab, setActiveTab] = useState('overview'); // overview, members, challenges, leaderboard, browse, create
  const [publicGuilds, setPublicGuilds] = useState([]);
  const [leaderboard, setLeaderboard] = useState([]);
  const [createForm, setCreateForm] = useState({ name: '', tag: '', description: '', is_public: true });
  const [loading, setLoading] = useState(false);
  const [showDonate, setShowDonate] = useState(false);

  const loadMyGuild = useCallback(async () => {
    try {
      const res = await fetch('/api/guilds/my-guild');
      if (res.ok) {
        const data = await res.json();
        if (data.in_guild) {
          setMyGuild(data);
          if (activeTab === 'browse' || activeTab === 'create') setActiveTab('overview');

        } else {
          setMyGuild(null);
          if (activeTab === 'overview' || activeTab === 'members') setActiveTab('browse');
        }
      }
    } catch (e) {
      console.error('Failed to load guild:', e);
    }
  }, [activeTab]);

  const loadPublicGuilds = useCallback(async () => {
    try {
      const res = await fetch('/api/guilds/list');
      if (res.ok) {
        const data = await res.json();
        setPublicGuilds(data.guilds || []);
      }
    } catch (e) {
      console.error('Failed to load guilds:', e);
    }
  }, []);

  const loadLeaderboard = useCallback(async () => {
    try {
      const res = await fetch('/api/guilds/leaderboard');
      if (res.ok) {
        const data = await res.json();
        setLeaderboard(data.leaderboard || []);
      }
    } catch (e) {
      console.error('Failed to load leaderboard:', e);
    }
  }, []);

  useEffect(() => {
    loadMyGuild();
    if (activeTab === 'browse') loadPublicGuilds();
    if (activeTab === 'leaderboard') loadLeaderboard();
  }, [loadMyGuild, activeTab, loadPublicGuilds, loadLeaderboard]);

  const createGuild = async () => {
    if (!createForm.name.trim() || !createForm.tag.trim()) {
      alert('Name and tag are required');
      return;
    }
    setLoading(true);
    try {
      const res = await fetch('/api/guilds/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(createForm)
      });
      const data = await res.json();
      if (res.ok) {
        alert(data.message);
        setCreateForm({ name: '', tag: '', description: '', is_public: true });
        loadMyGuild();
      } else {
        alert(data.detail || 'Failed to create guild');
      }
    } catch (e) {
      alert('Network error');
    } finally {
      setLoading(false);
    }
  };

  const joinGuild = async (guildId) => {
    try {
      const res = await fetch(`/api/guilds/join/${guildId}`, { method: 'POST' });
      const data = await res.json();
      if (res.ok) {
        alert(data.message);
        loadMyGuild();
      } else {
        alert(data.detail || 'Failed to join guild');
      }
    } catch (e) {
      alert('Network error');
    }
  };

  const leaveGuild = async () => {
    if (!confirm('Are you sure you want to leave your guild?')) return;
    try {
      const res = await fetch('/api/guilds/leave', { method: 'POST' });
      const data = await res.json();
      if (res.ok) {
        alert(data.message);
        loadMyGuild();
      }
    } catch (e) {
      alert('Network error');
    }
  };

  const handleDonate = async (amount) => {
    if (!amount || amount <= 0) return;
    try {
      const res = await fetch('/api/guilds/donate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount })
      });
      const data = await res.json();
      if (res.ok) {
        alert(data.message);
        setShowDonate(false);
        loadMyGuild();
      } else {
        alert(data.detail || 'Failed to donate');
      }
    } catch (e) {
      alert('Network error');
    }
  };

  const handleKick = async (userId) => {
    if (!confirm('Kick this member?')) return;
    try {
      const res = await fetch(`/api/guilds/kick/${userId}`, { method: 'POST' });
      if (res.ok) {
        loadMyGuild();
      } else {
        const data = await res.json();
        alert(data.detail);
      }
    } catch (e) {
      alert('Network error');
    }
  };

  const handlePromote = async (userId) => {
    try {
      const res = await fetch(`/api/guilds/promote/${userId}`, { method: 'POST' });
      if (res.ok) {
        loadMyGuild();
      } else {
        const data = await res.json();
        alert(data.detail);
      }
    } catch (e) {
      alert('Network error');
    }
  };

  // Render Content based on state
  const renderContent = () => {
    if (activeTab === 'leaderboard') {
      const top3 = leaderboard.slice(0, 3);
      const rest = leaderboard.slice(3);
      
      return (
        <div className="guild-leaderboard-enhanced">
          {/* Podium for top 3 */}
          {top3.length >= 3 && (
            <div className="leaderboard-podium">
              <div className="podium-card silver">
                <div className="podium-crown">🥈</div>
                <div className="podium-tag">[{top3[1].tag}]</div>
                <div className="podium-name">{top3[1].name}</div>
                <div className="podium-stat">${(top3[1].total_wagered / 100).toLocaleString()}</div>
              </div>
              <div className="podium-card gold">
                <div className="podium-crown">👑</div>
                <div className="podium-tag">[{top3[0].tag}]</div>
                <div className="podium-name">{top3[0].name}</div>
                <div className="podium-stat">${(top3[0].total_wagered / 100).toLocaleString()}</div>
              </div>
              <div className="podium-card bronze">
                <div className="podium-crown">🥉</div>
                <div className="podium-tag">[{top3[2].tag}]</div>
                <div className="podium-name">{top3[2].name}</div>
                <div className="podium-stat">${(top3[2].total_wagered / 100).toLocaleString()}</div>
              </div>
            </div>
          )}

          {/* Rest of leaderboard */}
          <div className="guild-leaderboard">
            <div className="leaderboard-header">
              <div className="rank-col">Rank</div>
              <div className="guild-col">Guild</div>
              <div className="members-col">Members</div>
              <div className="wagered-col">Total Wagered</div>
            </div>
            {(top3.length < 3 ? leaderboard : rest).map((g, idx) => (
              <div key={g.id} className={`leaderboard-row ${idx < 3 && top3.length < 3 ? 'top-3' : ''}`}>
                <div className="rank-col">
                  {top3.length < 3 && idx === 0 ? '🥇' : top3.length < 3 && idx === 1 ? '🥈' : top3.length < 3 && idx === 2 ? '🥉' : `#${g.rank || idx + 4}`}
                </div>
                <div className="guild-col">
                  <span className="guild-tag">[{g.tag}]</span>
                  <span className="guild-name">{g.name}</span>
                </div>
                <div className="members-col">{g.total_members}</div>
                <div className="wagered-col">${(g.total_wagered / 100).toLocaleString()}</div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (myGuild && myGuild.in_guild) {
      const { guild, members, my_role } = myGuild;
      
      if (activeTab === 'wars') {
        return (
          <div className="guild-wars-full-view">
            <GuildWars guild={guild} myRole={my_role} />
            <div style={{marginTop: '24px'}}>
              <h4 style={{color: 'var(--social-text-main)', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px'}}>
                <span style={{fontSize: '1.3rem'}}>📜</span> War History
              </h4>
              <div className="war-history-list">
                <div className="war-history-item won">
                  <div className="war-history-teams">
                    <span>[{guild.tag}]</span> vs <span>[SHDW]</span>
                  </div>
                  <div className="war-history-score">5,120 - 4,250</div>
                  <div className="war-history-result">Victory</div>
                </div>
                <div className="war-history-item won">
                  <div className="war-history-teams">
                    <span>[{guild.tag}]</span> vs <span>[APEX]</span>
                  </div>
                  <div className="war-history-score">3,800 - 2,100</div>
                  <div className="war-history-result">Victory</div>
                </div>
                <div className="war-history-item lost">
                  <div className="war-history-teams">
                    <span>[{guild.tag}]</span> vs <span>[ELITE]</span>
                  </div>
                  <div className="war-history-score">2,500 - 4,800</div>
                  <div className="war-history-result">Defeat</div>
                </div>
              </div>
            </div>
          </div>
        );
      }
      
      if (activeTab === 'members') {
        return (
          <div className="social-guild-members">
            <h4>Members ({members.length})</h4>
            {members.map(member => (
              <div key={member.id} className="social-guild-member">
                <div className="member-info">
                  <span className="username">{member.username}</span>
                  {member.role === 'leader' && <span className="role-badge">{SocialIcons.crown} Leader</span>}
                  {member.role === 'officer' && <span className="role-badge">Officer</span>}
                </div>
                <div className="member-actions-group" style={{display: 'flex', alignItems: 'center', gap: '12px'}}>
                  <div className="member-stats">
                    <span>LVL {member.level}</span>
                    <span>${(member.contribution_wagered / 100).toLocaleString()} contributed</span>
                  </div>
                  
                  {/* Management Actions */}
                  {my_role === 'leader' && member.role !== 'leader' && (
                    <div className="admin-actions">
                      <button 
                        className="btn-admin-action promote" 
                        title={member.role === 'officer' ? "Demote" : "Promote"}
                        onClick={() => handlePromote(member.id)}
                      >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                          <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"></path>
                        </svg>
                      </button>
                      <button 
                        className="btn-admin-action danger" 
                        title="Kick"
                        onClick={() => handleKick(member.id)}
                      >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                          <line x1="18" y1="6" x2="6" y2="18"></line>
                          <line x1="6" y1="6" x2="18" y2="18"></line>
                        </svg>
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        );
      }

      // Overview
      const nextLevelWager = guild.level * 1000000; // Mock requirement
      const progress = Math.min(100, (guild.total_wagered / nextLevelWager) * 100);

      return (
        <div className="social-guild-overview">
          <div className="guild-banner">
            <div className="guild-identity">
              <h1>[{guild.tag}] {guild.name}</h1>
              <p>{guild.description || 'No description set.'}</p>
            </div>
            
            {/* Level Progress */}
            <div className="guild-level-progress">
              <div className="progress-labels">
                <span>Level {guild.level}</span>
                <span>Level {guild.level + 1}</span>
              </div>
              <div className="progress-bar">
                <div className="progress-fill" style={{width: `${progress}%`}}></div>
              </div>
              <div style={{textAlign: 'center', marginTop: '8px', fontSize: '0.8rem', color: 'var(--social-text-muted)'}}>
                ${(guild.total_wagered / 100).toLocaleString()} / ${(nextLevelWager / 100).toLocaleString()} wagered
              </div>
            </div>

            <div className="guild-actions">
              <button className="btn-danger" onClick={leaveGuild}>Leave Guild</button>
            </div>
          </div>

          <div className="social-guild-stats">
            <div className="stat">
              <span className="label">Level</span>
              <span className="value">{guild.level}</span>
            </div>
            <div className="stat">
              <span className="label">Members</span>
              <span className="value">{guild.total_members}/{guild.max_members}</span>
            </div>
            <div className="stat">
              <span className="label">Total Wagered</span>
              <span className="value">${(guild.total_wagered / 100).toLocaleString()}</span>
            </div>
            <div className="stat">
              <span className="label">Treasury</span>
              <div className="value-group" style={{display: 'flex', alignItems: 'center', gap: '8px'}}>
                <span className="value">${(guild.treasury / 100).toLocaleString()}</span>
                <button 
                  className="btn-mini-action" 
                  onClick={() => setShowDonate(true)}
                >
                  Donate
                </button>
              </div>
            </div>
          </div>

          {/* Guild Wars */}
          <GuildWars guild={guild} myRole={my_role} />

          {/* Weekly Challenges */}
          <WeeklyChallenges guild={guild} />

          {/* Guild Perks */}
          <GuildPerks guild={guild} level={guild.level} />

          {/* Guild Achievements */}
          <GuildAchievements guild={guild} />

          {/* Activity Feed */}
          <div style={{marginTop: '24px'}}>
            <GuildActivityFeed guildId={guild.id} />
          </div>
        </div>
      );
    }

    // Not in guild
    if (activeTab === 'create') {
      return (
        <div className="social-create-guild-form">
          <h3>Create a New Guild</h3>
          <input
            type="text"
            placeholder="Guild Name"
            value={createForm.name}
            onChange={(e) => setCreateForm({...createForm, name: e.target.value})}
            maxLength={32}
          />
          <input
            type="text"
            placeholder="Tag (e.g., KING)"
            value={createForm.tag}
            onChange={(e) => setCreateForm({...createForm, tag: e.target.value.toUpperCase()})}
            maxLength={6}
          />
          <textarea
            placeholder="Description (optional)"
            value={createForm.description}
            onChange={(e) => setCreateForm({...createForm, description: e.target.value})}
            maxLength={200}
          />
          <label>
            <input
              type="checkbox"
              checked={createForm.is_public}
              onChange={(e) => setCreateForm({...createForm, is_public: e.target.checked})}
            />
            Public Guild (anyone can join)
          </label>
          <button onClick={createGuild} disabled={loading}>
            {loading ? 'Creating...' : 'Create Guild'}
          </button>
        </div>
      );
    }

    // Browse
    return (
      <div className="social-guilds-list">
        <h4>Public Guilds</h4>
        {publicGuilds.length === 0 ? (
          <div className="social-empty-state">
            <p>No public guilds available. Create one!</p>
          </div>
        ) : (
          publicGuilds.map(guild => (
            <div key={guild.id} className="social-guild-item">
              <div className="guild-info">
                <h5>[{guild.tag}] {guild.name}</h5>
                <p>{guild.description || 'No description'}</p>
                <div className="guild-stats-small">
                  <span>{guild.total_members}/{guild.max_members} members</span>
                  <span>LVL {guild.level}</span>
                  <span>${(guild.total_wagered / 100).toLocaleString()} wagered</span>
                </div>
              </div>
              <button className="btn-join" onClick={() => joinGuild(guild.id)}>
                Join
              </button>
            </div>
          ))
        )}
      </div>
    );
  };

  return (
    <div className="social-guild-panel">
      <div className="guild-nav-tabs">
        {myGuild && myGuild.in_guild ? (
          <>
            <button className={activeTab === 'overview' ? 'active' : ''} onClick={() => setActiveTab('overview')}>
              <span style={{marginRight: '6px'}}>🏠</span> Overview
            </button>
            <button className={activeTab === 'members' ? 'active' : ''} onClick={() => setActiveTab('members')}>
              <span style={{marginRight: '6px'}}>👥</span> Members
            </button>
            <button className={activeTab === 'wars' ? 'active' : ''} onClick={() => setActiveTab('wars')}>
              <span style={{marginRight: '6px'}}>⚔️</span> Wars
            </button>
          </>
        ) : (
          <>
            <button className={activeTab === 'browse' ? 'active' : ''} onClick={() => setActiveTab('browse')}>
              <span style={{marginRight: '6px'}}>🔍</span> Browse
            </button>
            <button className={activeTab === 'create' ? 'active' : ''} onClick={() => setActiveTab('create')}>
              <span style={{marginRight: '6px'}}>✨</span> Create
            </button>
          </>
        )}
        <button className={activeTab === 'leaderboard' ? 'active' : ''} onClick={() => setActiveTab('leaderboard')}>
          <span style={{marginRight: '6px'}}>🏆</span> Leaderboard
        </button>
      </div>

      <div className="guild-content-area">
        {renderContent()}
      </div>

      {showDonate && (
        <DonateModal 
          onClose={() => setShowDonate(false)} 
          onDonate={handleDonate} 
        />
      )}
    </div>
  );
}

// Export for global use
window.GuildPanel = GuildPanel;


// ============================================
// MAIN SOCIAL PANEL
// ============================================
function SocialPanel({ currentUser }) {
  const [activeTab, setActiveTab] = useState('friends');
  const [activeDM, setActiveDM] = useState(null);

  const goToGuildHub = () => {
    window.location.href = '/guild';
  };

  return (
    <div className="social-panel-container">
      <div className="social-tabs">
        <button 
          className={activeTab === 'friends' ? 'active' : ''} 
          onClick={() => setActiveTab('friends')}
        >
          {SocialIcons.users} Friends
        </button>
        <button 
          className="guild-hub-btn"
          onClick={goToGuildHub}
          title="Open Guild Hub"
        >
          {SocialIcons.guild} Guild Hub
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{marginLeft: '6px'}}>
            <path d="M7 17L17 7M17 7H7M17 7V17"/>
          </svg>
        </button>
      </div>

      <div className="social-content">
        {activeTab === 'friends' && (
          <FriendsList 
            currentUser={currentUser} 
            onOpenDM={(friend) => setActiveDM(friend)}
          />
        )}
      </div>

      {activeDM && (
        <PrivateMessageModal
          friend={activeDM}
          currentUser={currentUser}
          onClose={() => setActiveDM(null)}
        />
      )}
    </div>
  );
}

// Export for global use
window.SocialPanel = SocialPanel;
window.renderSocialPanel = function(containerId, currentUser) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Social panel container #${containerId} not found`);
    return;
  }
  
  const root = ReactDOM.createRoot(container);
  root.render(<SocialPanel currentUser={currentUser} />);
};
