// ============================================
// SOCIAL HUB - Unified Premium React Application
// Friends, Messages, Guild - All in One
// ============================================

const { useState, useEffect, useRef, useCallback } = React;
const CoinRushNavbar = window.CoinRushNavbar;

// ============================================
// SVG ICONS
// ============================================
const Icons = {
  users: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
  message: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>,
  guild: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 21h18M5 21V7l8-4 8 4v14M8 21V11l4-2 4 2v10"/></svg>,
  search: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>,
  plus: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
  check: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"/></svg>,
  x: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  send: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>,
  crown: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m2 4 3 12h14l3-12-6 7-4-7-4 7-6-7zm3 16h14"/></svg>,
  trophy: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>,
  coins: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/></svg>,
  settings: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/></svg>,
  star: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>,
  shield: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>,
  logout: <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>,
  userPlus: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg>,
  clock: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
  bell: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>,
  chevronRight: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="9 18 15 12 9 6"/></svg>,
  externalLink: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>,
};

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

// ============================================
// MAIN SOCIAL HUB COMPONENT
// ============================================
function SocialHub({ user }) {
  const [activeSection, setActiveSection] = useState('overview');
  const [friends, setFriends] = useState([]);
  const [pendingRequests, setPendingRequests] = useState([]);
  const [guild, setGuild] = useState(null);
  const [guildList, setGuildList] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [activeChatFriend, setActiveChatFriend] = useState(null);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    friends: 0,
    unreadMessages: 0,
    guildMembers: 0,
    guildRank: null
  });

  // Load initial data
  useEffect(() => {
    loadAllData();
  }, []);

  const loadAllData = async () => {
    setLoading(true);
    await Promise.all([
      loadFriends(),
      loadGuild(),
      loadGuildList()
    ]);
    setLoading(false);
  };

  const loadFriends = async () => {
    try {
      const res = await fetch('/api/friends/list', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setFriends(data.friends || []);
        setPendingRequests(data.pending_requests || []);
        setStats(prev => ({ ...prev, friends: data.friends?.length || 0 }));
      }
    } catch (err) {
      console.error('Failed to load friends:', err);
    }
  };

  const loadGuild = async () => {
    try {
      const res = await fetch('/api/guilds/my-guild', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        if (data.in_guild) {
          setGuild(data.guild);
          setStats(prev => ({ 
            ...prev, 
            guildMembers: data.guild.total_members || 0 
          }));
        }
      }
    } catch (err) {
      console.error('Failed to load guild:', err);
    }
  };

  const loadGuildList = async () => {
    try {
      const res = await fetch('/api/guilds/list', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setGuildList(data.guilds || []);
      }
    } catch (err) {
      console.error('Failed to load guilds:', err);
    }
  };

  // Search users
  useEffect(() => {
    if (searchQuery.length < 3) {
      setSearchResults([]);
      return;
    }
    
    const timer = setTimeout(async () => {
      try {
        const res = await fetch(`/api/users/search?query=${encodeURIComponent(searchQuery)}`, {
          credentials: 'include'
        });
        if (res.ok) {
          const data = await res.json();
          setSearchResults(data);
        }
      } catch (err) {
        console.error('Search failed:', err);
      }
    }, 400);
    
    return () => clearTimeout(timer);
  }, [searchQuery]);

  const sendFriendRequest = async (username) => {
    try {
      const res = await fetch('/api/friends/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username }),
        credentials: 'include'
      });
      const data = await res.json();
      if (res.ok) {
        setSearchResults(prev => prev.map(u => 
          u.username === username ? { ...u, has_pending_request: true } : u
        ));
      } else {
        alert(data.detail || 'Failed to send request');
      }
    } catch (err) {
      alert('Error sending request');
    }
  };

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

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

  if (loading) {
    return (
      <div className="sh-loading">
        <div className="sh-spinner" />
        <p>Loading Social Hub...</p>
      </div>
    );
  }

  return (
    <div className="social-hub">
      {/* Chat Modal */}
      {activeChatFriend && (
        <ChatModal 
          friend={activeChatFriend} 
          onClose={() => setActiveChatFriend(null)} 
        />
      )}

      {/* Header */}
      <header className="sh-header">
        <div className="sh-header-content">
          <h1 className="sh-title">
            <span className="sh-title-icon">{Icons.users}</span>
            Social Hub
          </h1>
          <p className="sh-subtitle">Connect with friends and join guilds</p>
        </div>
        
        {/* Quick Stats */}
        <div className="sh-quick-stats">
          <div className="sh-stat">
            <span className="sh-stat-value">{stats.friends}</span>
            <span className="sh-stat-label">Friends</span>
          </div>
          <div className="sh-stat">
            <span className="sh-stat-value">{pendingRequests.length}</span>
            <span className="sh-stat-label">Requests</span>
          </div>
          {guild && (
            <div className="sh-stat guild">
              <span className="sh-stat-value">{stats.guildMembers}</span>
              <span className="sh-stat-label">Guild</span>
            </div>
          )}
        </div>
      </header>

      {/* Navigation */}
      <nav className="sh-nav">
        <button 
          className={`sh-nav-btn ${activeSection === 'overview' ? 'active' : ''}`}
          onClick={() => setActiveSection('overview')}
        >
          {Icons.users}
          <span>Overview</span>
        </button>
        <button 
          className={`sh-nav-btn ${activeSection === 'friends' ? 'active' : ''}`}
          onClick={() => setActiveSection('friends')}
        >
          {Icons.message}
          <span>Friends</span>
          {pendingRequests.length > 0 && (
            <span className="sh-nav-badge">{pendingRequests.length}</span>
          )}
        </button>
        <button 
          className={`sh-nav-btn ${activeSection === 'search' ? 'active' : ''}`}
          onClick={() => setActiveSection('search')}
        >
          {Icons.userPlus}
          <span>Add Friends</span>
        </button>
        <button 
          className={`sh-nav-btn ${activeSection === 'guild' ? 'active' : ''}`}
          onClick={() => setActiveSection('guild')}
        >
          {Icons.guild}
          <span>Guild</span>
        </button>
      </nav>

      {/* Main Content */}
      <main className="sh-main">
        {activeSection === 'overview' && (
          <OverviewSection 
            friends={friends}
            pendingRequests={pendingRequests}
            guild={guild}
            onChat={setActiveChatFriend}
            onAccept={acceptRequest}
            onReject={rejectRequest}
            onNavigate={setActiveSection}
          />
        )}
        
        {activeSection === 'friends' && (
          <FriendsSection 
            friends={friends}
            pendingRequests={pendingRequests}
            onChat={setActiveChatFriend}
            onAccept={acceptRequest}
            onReject={rejectRequest}
            onNavigate={setActiveSection}
          />
        )}
        
        {activeSection === 'search' && (
          <SearchSection 
            query={searchQuery}
            setQuery={setSearchQuery}
            results={searchResults}
            onSendRequest={sendFriendRequest}
          />
        )}
        
        {activeSection === 'guild' && (
          <GuildSection 
            guild={guild}
            guildList={guildList}
            user={user}
            onRefresh={loadAllData}
          />
        )}
      </main>
    </div>
  );
}

// ============================================
// OVERVIEW SECTION
// ============================================
function OverviewSection({ friends, pendingRequests, guild, onChat, onAccept, onReject, onNavigate }) {
  const onlineFriends = friends.filter(f => f.is_online);
  
  return (
    <div className="sh-overview">
      {/* Pending Requests Alert */}
      {pendingRequests.length > 0 && (
        <div className="sh-alert">
          <div className="sh-alert-icon">{Icons.bell}</div>
          <div className="sh-alert-content">
            <strong>{pendingRequests.length} pending friend request{pendingRequests.length > 1 ? 's' : ''}</strong>
            <p>Someone wants to connect with you!</p>
          </div>
          <button className="sh-alert-btn" onClick={() => onNavigate('friends')}>
            View Requests
          </button>
        </div>
      )}

      <div className="sh-overview-grid">
        {/* Online Friends */}
        <div className="sh-card">
          <div className="sh-card-header">
            <h3>{Icons.users} Online Friends</h3>
            <span className="sh-card-count">{onlineFriends.length}</span>
          </div>
          <div className="sh-card-body">
            {onlineFriends.length === 0 ? (
              <div className="sh-empty-mini">
                <p>No friends online right now</p>
              </div>
            ) : (
              <div className="sh-friend-list-mini">
                {onlineFriends.slice(0, 5).map(friend => (
                  <div key={friend.id} className="sh-friend-mini" onClick={() => onChat(friend)}>
                    <div className="sh-avatar online">
                      {friend.username[0].toUpperCase()}
                    </div>
                    <span className="sh-friend-name">{friend.username}</span>
                  </div>
                ))}
                {onlineFriends.length > 5 && (
                  <button className="sh-see-more" onClick={() => onNavigate('friends')}>
                    +{onlineFriends.length - 5} more
                  </button>
                )}
              </div>
            )}
          </div>
          <button className="sh-card-action" onClick={() => onNavigate('friends')}>
            All Friends {Icons.chevronRight}
          </button>
        </div>

        {/* Guild Card */}
        <div className="sh-card">
          <div className="sh-card-header">
            <h3>{Icons.guild} My Guild</h3>
          </div>
          <div className="sh-card-body">
            {guild ? (
              <div className="sh-guild-preview">
                <div className="sh-guild-banner">
                  <span className="sh-guild-icon">{guild.name[0].toUpperCase()}</span>
                </div>
                <h4 className="sh-guild-name">{guild.name}</h4>
                <div className="sh-guild-stats">
                  <div className="sh-guild-stat">
                    <span>{guild.total_members || 0}</span>
                    <label>Members</label>
                  </div>
                  <div className="sh-guild-stat">
                    <span>{formatCoins(guild.treasury || 0)}</span>
                    <label>Treasury</label>
                  </div>
                  <div className="sh-guild-stat">
                    <span>Lv.{guild.level || 1}</span>
                    <label>Level</label>
                  </div>
                </div>
              </div>
            ) : (
              <div className="sh-empty-mini">
                <p>You're not in a guild yet</p>
                <button className="sh-btn-primary" onClick={() => onNavigate('guild')}>
                  Find a Guild
                </button>
              </div>
            )}
          </div>
          <button className="sh-card-action" onClick={() => onNavigate('guild')}>
            Guild Hub {Icons.chevronRight}
          </button>
        </div>

        {/* Quick Actions */}
        <div className="sh-card">
          <div className="sh-card-header">
            <h3>{Icons.star} Quick Actions</h3>
          </div>
          <div className="sh-card-body">
            <div className="sh-quick-actions">
              <button className="sh-action-btn" onClick={() => onNavigate('search')}>
                {Icons.userPlus}
                <span>Add Friend</span>
              </button>
              <button className="sh-action-btn" onClick={() => onNavigate('guild')}>
                {Icons.guild}
                <span>{guild ? 'Manage Guild' : 'Join Guild'}</span>
              </button>
              <button className="sh-action-btn" onClick={() => window.location.href = '/guild'}>
                {Icons.trophy}
                <span>Guild Wars</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// FRIENDS SECTION
// ============================================
function FriendsSection({ friends, pendingRequests, onChat, onAccept, onReject, onNavigate }) {
  return (
    <div className="sh-friends">
      {/* Pending Requests */}
      {pendingRequests.length > 0 && (
        <div className="sh-section">
          <h3 className="sh-section-title">
            {Icons.bell} Pending Requests
            <span className="sh-count">{pendingRequests.length}</span>
          </h3>
          <div className="sh-requests-list">
            {pendingRequests.map(req => (
              <div key={req.id} className="sh-request-card">
                <div className="sh-avatar">
                  {req.from_username[0].toUpperCase()}
                </div>
                <div className="sh-request-info">
                  <span className="sh-request-name">{req.from_username}</span>
                  <span className="sh-request-time">wants to be your friend</span>
                </div>
                <div className="sh-request-actions">
                  <button className="sh-btn-accept" onClick={() => onAccept(req.id)}>
                    {Icons.check}
                  </button>
                  <button className="sh-btn-reject" onClick={() => onReject(req.id)}>
                    {Icons.x}
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Friends List */}
      <div className="sh-section">
        <div className="sh-section-header">
          <h3 className="sh-section-title">
            {Icons.users} My Friends
            <span className="sh-count">{friends.length}</span>
          </h3>
          <button className="sh-btn-secondary" onClick={() => onNavigate('search')}>
            {Icons.userPlus} Add Friend
          </button>
        </div>
        
        {friends.length === 0 ? (
          <div className="sh-empty">
            <div className="sh-empty-icon">{Icons.users}</div>
            <h4>No friends yet</h4>
            <p>Start adding friends to chat and play together!</p>
            <button className="sh-btn-primary" onClick={() => onNavigate('search')}>
              Find Friends
            </button>
          </div>
        ) : (
          <div className="sh-friends-grid">
            {friends.map(friend => (
              <div key={friend.id} className="sh-friend-card">
                <div className={`sh-avatar ${friend.is_online ? 'online' : ''}`}>
                  {friend.username[0].toUpperCase()}
                </div>
                <div className="sh-friend-info">
                  <span className="sh-friend-name">{friend.username}</span>
                  <span className="sh-friend-status">
                    Level {friend.level || 1} • {friend.is_online ? 'Online' : 'Offline'}
                  </span>
                </div>
                <button className="sh-btn-chat" onClick={() => onChat(friend)}>
                  {Icons.message}
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================
// SEARCH SECTION
// ============================================
function SearchSection({ query, setQuery, results, onSendRequest }) {
  return (
    <div className="sh-search">
      <div className="sh-section">
        <h3 className="sh-section-title">{Icons.search} Find Friends</h3>
        
        <div className="sh-search-box">
          <div className="sh-search-icon">{Icons.search}</div>
          <input
            type="text"
            className="sh-search-input"
            placeholder="Search by username (min 3 characters)..."
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </div>

        {query.length > 0 && query.length < 3 && (
          <p className="sh-search-hint">Type at least 3 characters to search</p>
        )}

        {results.length > 0 && (
          <div className="sh-search-results">
            {results.map(user => (
              <div key={user.id} className="sh-result-card">
                <div className="sh-avatar">
                  {user.username[0].toUpperCase()}
                </div>
                <div className="sh-result-info">
                  <span className="sh-result-name">{user.username}</span>
                  <span className="sh-result-level">Level {user.level || 1}</span>
                </div>
                <div className="sh-result-action">
                  {user.is_friend ? (
                    <span className="sh-badge success">{Icons.check} Friends</span>
                  ) : user.has_pending_request ? (
                    <span className="sh-badge pending">{Icons.clock} Pending</span>
                  ) : (
                    <button 
                      className="sh-btn-primary"
                      onClick={() => onSendRequest(user.username)}
                    >
                      {Icons.userPlus} Add
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}

        {query.length >= 3 && results.length === 0 && (
          <div className="sh-empty">
            <div className="sh-empty-icon">{Icons.search}</div>
            <h4>No users found</h4>
            <p>Try a different search term</p>
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================
// GUILD SECTION
// ============================================
function GuildSection({ guild, guildList, user, onRefresh }) {
  const [showCreateWizard, setShowCreateWizard] = useState(false);
  const [donateAmount, setDonateAmount] = useState('');

  const GuildCreateWizard = window.GuildCreateWizard;

  const joinGuild = async (guildId) => {
    try {
      const res = await fetch(`/api/guilds/join/${guildId}`, {
        method: 'POST',
        credentials: 'include'
      });
      const data = await res.json();
      if (res.ok) {
        onRefresh();
      } else {
        alert(data.detail || 'Failed to join guild');
      }
    } catch (err) {
      alert('Error joining guild');
    }
  };

  const leaveGuild = async () => {
    if (!confirm('Are you sure you want to leave this guild?')) return;
    
    try {
      const res = await fetch('/api/guilds/leave', {
        method: 'POST',
        credentials: 'include'
      });
      if (res.ok) {
        onRefresh();
      }
    } catch (err) {
      alert('Error leaving guild');
    }
  };

  const donateToTreasury = async () => {
    const amount = parseFloat(donateAmount) * 100; // Convert to cents
    if (!amount || amount < 100) {
      alert('Minimum donation is 1.00');
      return;
    }
    
    try {
      const res = await fetch('/api/guilds/donate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ amount })
      });
      const data = await res.json();
      if (res.ok) {
        setDonateAmount('');
        onRefresh();
        alert('Donation successful!');
      } else {
        alert(data.detail || 'Failed to donate');
      }
    } catch (err) {
      alert('Error donating');
    }
  };

  const handleGuildCreated = (newGuild) => {
    setShowCreateWizard(false);
    onRefresh();
  };

  // If user is in a guild, show guild details
  if (guild) {
    return (
      <div className="sh-guild">
        <div className="sh-guild-header">
          <div className="sh-guild-banner-large">
            <span className="sh-guild-icon-large">{guild.name[0].toUpperCase()}</span>
          </div>
          <div className="sh-guild-info">
            <h2 className="sh-guild-title">{guild.name}</h2>
            <p className="sh-guild-desc">{guild.description || 'No description set'}</p>
          </div>
        </div>

        <div className="sh-guild-stats-grid">
          <div className="sh-stat-card">
            <div className="sh-stat-icon">{Icons.users}</div>
            <div className="sh-stat-value">{guild.total_members || 0}</div>
            <div className="sh-stat-label">Members</div>
          </div>
          <div className="sh-stat-card">
            <div className="sh-stat-icon">{Icons.coins}</div>
            <div className="sh-stat-value">{formatCoins(guild.treasury || 0)}</div>
            <div className="sh-stat-label">Treasury</div>
          </div>
          <div className="sh-stat-card">
            <div className="sh-stat-icon">{Icons.star}</div>
            <div className="sh-stat-value">Lv.{guild.level || 1}</div>
            <div className="sh-stat-label">Level</div>
          </div>
          <div className="sh-stat-card">
            <div className="sh-stat-icon">{Icons.trophy}</div>
            <div className="sh-stat-value">{guild.total_xp || 0}</div>
            <div className="sh-stat-label">Total XP</div>
          </div>
        </div>

        {/* Donate Section */}
        <div className="sh-section">
          <h3 className="sh-section-title">{Icons.coins} Donate to Treasury</h3>
          <div className="sh-donate-form">
            <input
              type="number"
              className="sh-input"
              placeholder="Amount (e.g. 10.00)"
              value={donateAmount}
              onChange={(e) => setDonateAmount(e.target.value)}
              min="1"
              step="0.01"
            />
            <button className="sh-btn-primary" onClick={donateToTreasury}>
              Donate
            </button>
          </div>
        </div>

        {/* Actions */}
        <div className="sh-guild-actions">
          <button className="sh-btn-secondary" onClick={() => window.location.href = '/guild'}>
            {Icons.settings} Full Guild Hub
          </button>
          <button className="sh-btn-danger" onClick={leaveGuild}>
            {Icons.logout} Leave Guild
          </button>
        </div>
      </div>
    );
  }

  // If user is not in a guild, show guild creation wizard or list
  return (
    <div className="sh-guild">
      {/* Multi-Step Guild Creation Wizard */}
      {showCreateWizard && GuildCreateWizard && (
        <GuildCreateWizard 
          user={user}
          onClose={() => setShowCreateWizard(false)}
          onSuccess={handleGuildCreated}
        />
      )}

      {/* Create Your Own Guild CTA */}
      <div className="sh-create-guild-cta">
        <div className="cta-content">
          <div className="cta-icon">{Icons.crown}</div>
          <div className="cta-text">
            <h3>Start Your Own Guild</h3>
            <p>Create a community, lead members, compete in wars, and build a treasury together.</p>
          </div>
        </div>
        <button className="sh-btn-create-guild" onClick={() => setShowCreateWizard(true)}>
          {Icons.plus} Create Guild (100 Coins)
        </button>
      </div>

      <div className="sh-section-header">
        <h3 className="sh-section-title">{Icons.guild} Available Guilds</h3>
      </div>

      {guildList.length === 0 ? (
        <div className="sh-empty">
          <div className="sh-empty-icon">{Icons.guild}</div>
          <h4>No guilds available yet</h4>
          <p>Be the first to create a guild and start building your community!</p>
        </div>
      ) : (
        <div className="sh-guild-list">
          {guildList.map(g => (
            <div key={g.id} className="sh-guild-card">
              <div className="sh-guild-card-icon">
                {g.name[0].toUpperCase()}
              </div>
              <div className="sh-guild-card-info">
                <h4>{g.name}</h4>
                <p>{g.total_members || 0} members - Lv.{g.level || 1}</p>
              </div>
              <button className="sh-btn-secondary" onClick={() => joinGuild(g.id)}>
                Join
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ============================================
// CHAT MODAL
// ============================================
function ChatModal({ friend, onClose }) {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const messagesEndRef = useRef(null);

  useEffect(() => {
    loadMessages();
    const interval = setInterval(loadMessages, 3000);
    return () => clearInterval(interval);
  }, [friend]);

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

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

  const sendMessage = async () => {
    if (!input.trim() || sending) return;
    
    setSending(true);
    try {
      const res = await fetch('/api/messages/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          receiver_username: friend.username,
          message: input.trim()
        })
      });
      if (res.ok) {
        setInput('');
        loadMessages();
      }
    } catch (err) {
      console.error('Failed to send:', err);
    }
    setSending(false);
  };

  return (
    <div className="sh-modal-backdrop" onClick={onClose}>
      <div className="sh-chat-modal" onClick={e => e.stopPropagation()}>
        <div className="sh-chat-header">
          <div className="sh-avatar">
            {friend.username[0].toUpperCase()}
          </div>
          <div className="sh-chat-title">
            <h3>{friend.username}</h3>
            <span>{friend.is_online ? 'Online' : 'Offline'}</span>
          </div>
          <button className="sh-modal-close" onClick={onClose}>
            {Icons.x}
          </button>
        </div>
        
        <div className="sh-chat-messages">
          {messages.length === 0 ? (
            <div className="sh-chat-empty">
              <p>No messages yet. Say hi!</p>
            </div>
          ) : (
            messages.map((msg, i) => (
              <div key={msg.id || i} className={`sh-chat-msg ${msg.is_mine ? 'mine' : 'theirs'}`}>
                <div className="sh-chat-msg-content">{msg.message}</div>
                <div className="sh-chat-msg-time">
                  {new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                </div>
              </div>
            ))
          )}
          <div ref={messagesEndRef} />
        </div>
        
        <div className="sh-chat-input">
          <input
            type="text"
            placeholder="Type a message..."
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
            disabled={sending}
          />
          <button onClick={sendMessage} disabled={!input.trim() || sending}>
            {Icons.send}
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================
// MAIN APP WRAPPER
// ============================================
function MainApp() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchUser() {
      try {
        const res = await fetch('/api/user', { credentials: 'include' });
        if (!res.ok) {
          window.location.href = '/';
          return;
        }
        const data = await res.json();
        setUser(data);
      } catch (err) {
        console.error('Failed to load user:', err);
        window.location.href = '/';
      }
      setLoading(false);
    }
    fetchUser();
  }, []);

  if (loading) {
    return (
      <div className="sh-loading">
        <div className="sh-spinner" />
        <p>Loading...</p>
      </div>
    );
  }

  return (
    <div>
      <CoinRushNavbar 
        user={user}
        activePage="social"
        onLogout={() => { window.location.href = '/logout'; }}
      />
      <SocialHub user={user} />
    </div>
  );
}

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