import React, { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useNavigate, useLocation, useParams } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Helmet } from 'react-helmet-async';
import axios from 'axios';
import './App.css';

// Import shadcn components
import { Button } from './components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './components/ui/card';
import { Input } from './components/ui/input';
import { Label } from './components/ui/label';
import { Textarea } from './components/ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from './components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './components/ui/select';
import { Separator } from './components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './components/ui/tabs';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './components/ui/dropdown-menu';
import { Toaster } from './components/ui/toaster';
import { useToast } from './hooks/use-toast';
import { ThemeProvider } from 'next-themes';
import { BookOpen, Users, PenTool, LogOut, Settings, Palette, Save, MessageSquare, Star, Search, Menu, Bookmark, TrendingUp, Clock, Award, Upload, ChevronDown, Edit, Crown, MessageCircle, Send } from 'lucide-react';

// Import payment components
import { 
  PaymentButton, 
  WriterSubscriptionTiers, 
  TipWriter, 
  PremiumMembership, 
  ChapterPurchase, 
  PaymentSuccess 
} from './components/PaymentComponents';

// Import withdrawal components  
import { 
  WriterEarningsDashboard,
  WithdrawalRequestForm,
  WithdrawalHistory,
  WithdrawalSettings
} from './components/WithdrawalComponents';

// Import social components
import { 
  ClickableUsername, 
  FriendRequestButton, 
  NotificationBell, 
  MessageChatBubble, 
  OnlineStatus,
  FriendRequestsManager 
} from './components/SocialComponents';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;

// Create a client
const queryClient = new QueryClient();
const API = `${BACKEND_URL}/api`;

// Panel Opacity Context for user customization
const PanelOpacityContext = React.createContext();

const PanelOpacityProvider = ({ children }) => {
  const [panelSettings, setPanelSettings] = useState({
    leftPanel: 'transparent', // transparent, opaque, solid
    rightPanel: 'transparent',
    mainPanel: 'transparent',
    navigationPanel: 'transparent'
  });

  const updatePanelOpacity = (panel, opacity) => {
    setPanelSettings(prev => ({
      ...prev,
      [panel]: opacity
    }));
  };

  const getPanelClasses = (panel) => {
    const setting = panelSettings[panel];
    switch (setting) {
      case 'transparent':
        return 'backdrop-blur-sm border-white/10 bg-black/[var(--global-panel-opacity)] panel-bg-transparent';
      case 'opaque':
        return 'backdrop-blur-md border-white/20 bg-black/60 panel-bg-opaque';
      case 'solid':
        return 'bg-black border-white/30';
      default:
        return 'backdrop-blur-sm border-white/10 bg-black/[var(--global-panel-opacity)] panel-bg-transparent';
    }
  };

  const getPanelStyle = (panel) => {
    const setting = panelSettings[panel];
    const opacity = parseInt(document.documentElement.style.getPropertyValue('--global-panel-opacity')) || 20;
    
    switch (setting) {
      case 'transparent':
        return { backgroundColor: `rgba(0, 0, 0, ${opacity / 100})` };
      case 'opaque':
        return { backgroundColor: `rgba(0, 0, 0, ${Math.min(0.8, (opacity + 40) / 100)})` };
      case 'solid':
        return { backgroundColor: 'rgba(0, 0, 0, 1)' };
      default:
        return { backgroundColor: `rgba(0, 0, 0, ${opacity / 100})` };
    }
  };

  return (
    <PanelOpacityContext.Provider value={{ panelSettings, updatePanelOpacity, getPanelClasses, getPanelStyle }}>
      {children}
    </PanelOpacityContext.Provider>
  );
};

// Global Background Component
const GlobalBackground = ({ children, className = "" }) => {
  const [globalBg, setGlobalBg] = useState('linear-gradient(45deg, #1a1a2e, #16213e, #0f3460)');
  const [panelOpacity, setPanelOpacity] = useState(20);

  useEffect(() => {
    const fetchGlobalBackground = async () => {
      try {
        const response = await axios.get(`${API}/admin/site-settings`);
        
        if (response.data?.background_image) {
          setGlobalBg(response.data.background_image);
        }
        if (response.data?.panel_opacity !== undefined) {
          setPanelOpacity(response.data.panel_opacity);
          // Set CSS custom property for global opacity
          document.documentElement.style.setProperty('--global-panel-opacity', response.data.panel_opacity);
        }
      } catch (error) {
        console.error('Error fetching global background:', error);
        // Keep the default gradient background and opacity
        console.log('Using default gradient background and opacity due to API error');
        document.documentElement.style.setProperty('--global-panel-opacity', '20');
      }
    };

    fetchGlobalBackground();

    // Listen for storage events to refresh background when settings are updated
    const handleStorageChange = () => {
      fetchGlobalBackground();
    };

    window.addEventListener('storage', handleStorageChange);
    
    // Custom event for same-tab updates
    window.addEventListener('siteSettingsUpdated', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('siteSettingsUpdated', handleStorageChange);
    };
  }, []);

  // Debug: console.log('GlobalBackground render - globalBg:', globalBg);

  return (
    <div className={`relative min-h-screen ${className}`} style={{ '--panel-opacity': panelOpacity }}>

      
      {/* Global Background */}
      {globalBg && (
        <div 
          className="fixed inset-0 bg-cover bg-center bg-no-repeat -z-10"
          style={{ 
            backgroundImage: globalBg.startsWith('linear-gradient') ? globalBg : `url(${globalBg})`,
            background: globalBg.startsWith('linear-gradient') ? globalBg : undefined,
            filter: 'brightness(0.7)'
          }}
        />
      )}
      {children}
    </div>
  );
};

// Auth Context
const AuthContext = React.createContext();

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  // Check for existing session on app load
  useEffect(() => {
    checkAuth();
  }, []);

  // Helper function to check if user has admin permissions
  const isAdmin = () => {
    return user && user.user_type === 'admin';
  };

  // Demo function to switch user types for testing
  const switchUserType = (newType) => {
    if (user) {
      setUser({
        ...user,
        user_type: newType,
        name: newType === 'admin' ? 'Admin User' : 
              newType === 'writer' ? 'Alex Writer' : 'Reader User',
        bio: newType === 'admin' ? 'Site administrator with full access.' :
             newType === 'writer' ? 'Passionate fantasy writer creating immersive worlds.' :
             'Avid reader exploring new fictional worlds.'
      });
    }
  };

  const checkAuth = async () => {
    try {
      const response = await axios.get(`${API}/auth/me`, {
        withCredentials: true
      });
      setUser(response.data); // Backend returns user data directly, not wrapped in user property
    } catch (error) {
      console.error('Auth check failed:', error);
      setUser(null);
    } finally {
      setLoading(false);
    }
  };

  const logout = async () => {
    try {
      await axios.post(`${API}/auth/logout`, {}, {
        withCredentials: true
      });
      setUser(null);
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  return (
    <AuthContext.Provider value={{ user, setUser, logout, loading, checkAuth, isAdmin, switchUserType }}>
      {children}
    </AuthContext.Provider>
  );
};

// Google Auth Handler Component
const AuthHandler = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { checkAuth } = React.useContext(AuthContext);
  const { toast } = useToast();
  const [processing, setProcessing] = useState(false);

  useEffect(() => {
    const processAuth = async () => {
      const urlParams = new URLSearchParams(location.hash.substring(1));
      const sessionId = urlParams.get('session_id');
      
      if (sessionId && !processing) {
        setProcessing(true);
        
        try {
          await axios.post(`${API}/auth/google-session`, {}, {
            headers: {
              'X-Session-ID': sessionId
            },
            withCredentials: true
          });
          
          await checkAuth();
          toast({
            title: "Success!",
            description: "Successfully logged in with Google",
          });
          
          // Clean URL and navigate to dashboard
          window.history.replaceState({}, document.title, window.location.pathname);
          navigate('/dashboard');
          
        } catch (error) {
          console.error('Auth processing failed:', error);
          toast({
            title: "Authentication Failed",
            description: "There was an error processing your login",
            variant: "destructive",
          });
          navigate('/');
        }
      }
    };

    processAuth();
  }, [location, navigate, checkAuth, toast, processing]);

  if (processing) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-black">
        <div className="text-center">
          <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white mx-auto"></div>
          <p className="mt-4 text-white text-lg">Processing your login...</p>
        </div>
      </div>
    );
  }

  return null;
};

// Landing Page Component - Redesigned Layout
const LandingPage = () => {
  const { user, setUser, logout, checkAuth, loading } = React.useContext(AuthContext);
  const navigate = useNavigate();
  const { isAdmin } = React.useContext(AuthContext);
  const [showAuth, setShowAuth] = useState(false);
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: '',
    user_type: 'reader'
  });
  const [landingContent, setLandingContent] = useState(null);
  const [siteSettings, setSiteSettings] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchType, setSearchType] = useState('story');
  const [showRightPanel, setShowRightPanel] = useState(true);
  const [backgroundImage, setBackgroundImage] = useState('');
  const { getPanelClasses, updatePanelOpacity } = React.useContext(PanelOpacityContext);
  const [popularStories, setPopularStories] = useState([]);
  const { toast } = useToast();
  const [siteStats, setSiteStats] = useState(null);
  const { toast } = useToast();

  useEffect(() => {
    // Removed automatic dashboard redirect - let users stay on landing page
    fetchLandingContent();
    fetchSiteSettings();
    fetchPopularStories();
    fetchSiteStats(); // Add real stats instead of mock data
  }, [navigate]); // Removed 'user' dependency to prevent flicker on auth changes

  const fetchPopularStories = async () => {
    try {
      const response = await axios.get(`${API}/stories?limit=5`);
      if (response.data && response.data.stories) {
        // Transform API stories to match popular stories format
        const transformed = response.data.stories.map((story, index) => ({
          id: story.id,
          title: story.title,
          author: story.author,
          cover: `https://picsum.photos/120/180?random=${story.id || index + 1}`,
          rating: story.rating
        }));
        setPopularStories(transformed);
      }
    } catch (error) {
      console.error('Error fetching popular stories:', error);
      // Set empty array for production - no fallback mock data
      setPopularStories([]);
    }
  };

  const fetchSiteStats = async () => {
    try {
      const response = await axios.get(`${API}/stats`);
      console.log('🔍 Site stats API response:', response.data);
      setSiteStats(response.data);
    } catch (error) {
      console.error('Error fetching site stats:', error);
      // Set default stats if API fails
      setSiteStats({
        totalUsers: 0,
        activeUsers: 0,
        totalStories: 0,
        totalPosts: 0
      });
    }
  };

  const fetchSiteSettings = async () => {
    try {
      const response = await axios.get(`${API}/admin/site-settings`);
      setSiteSettings(response.data);
    } catch (error) {
      console.error('Error fetching site settings:', error);
      setSiteSettings({
        site_name: "Queens Mountain",
        site_logo_url: "",
        background_color: "#000000", 
        primary_color: "#ffffff",
        secondary_color: "#666666"
      });
    }
  };

  const fetchLandingContent = async () => {
    try {
      const response = await axios.get(`${API}/content/landing-page`);
      console.log('🔍 LandingContent API response:', response.data);
      setLandingContent(response.data);
      console.log('🔍 setLandingContent called with:', response.data);
      setBackgroundImage(response.data.hero_background_image || '');
    } catch (error) {
      console.error('Error fetching landing content:', error);
      toast.error('Failed to load landing content. Please try refreshing the page.');
      setLandingContent({
        hero_title: "Welcome to Queens Mountain",
        hero_subtitle: "A premium platform where writers share their stories and readers discover amazing content. Join our community of storytellers and book lovers.",
        hero_cta_text: "Get Started",
        feature1_title: "For Readers",
        feature1_description: "Discover incredible stories, follow your favorite writers, and share reviews with the community.",
        feature2_title: "For Writers", 
        feature2_description: "Share your stories, build an audience, and earn from your passion with our subscription system.",
        feature3_title: "Community",
        feature3_description: "Join a vibrant community where stories come alive and friendships are formed through literature."
      });
    }
  };

  const handleAuth = async (e) => {
    e.preventDefault();
    
    try {
      const endpoint = isLogin ? '/auth/login' : '/auth/register';
      const response = await axios.post(`${API}${endpoint}`, formData, {
        withCredentials: true
      });
      
      if (isLogin) {
        setUser(response.data.user); // Backend returns user data wrapped in user property
        toast({
          title: "Welcome!",
          description: "Successfully logged in",
        });
        setShowAuth(false);
        // Redirect to appropriate dashboard based on user type
        if (response.data.user.user_type === 'admin') {
          navigate('/admin/dashboard');
        } else {
          navigate('/profile'); // Redirect writers and readers to their profiles
        }
      } else {
        toast({
          title: "Account Created!",
          description: "Please log in with your new account",
        });
        setIsLogin(true);
        setFormData({ name: '', email: '', password: '', user_type: 'reader' });
      }
    } catch (error) {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Authentication failed",
        variant: "destructive",
      });
    }
  };

  const handleGoogleAuth = () => {
    const redirectUrl = encodeURIComponent(`${window.location.origin}/dashboard`);
    window.location.href = `https://auth.emergentagent.com/?redirect=${redirectUrl}`;
  };

  const handleSearch = () => {
    if (searchQuery.trim()) {
      toast({
        title: "Search",
        description: `Searching for ${searchType}: "${searchQuery}"`,
      });
      // TODO: Implement actual search functionality
    }
  };

  const handleStoryClick = (story) => {
    toast({
      title: "Story Selected",
      description: `Opening "${story.title}" by ${story.author}`,
    });
    // TODO: Navigate to story page
  };

  const handleImageUpload = (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        setBackgroundImage(e.target.result);
        toast({
          title: "Background Updated",
          description: "Background image has been updated",
        });
      };
      reader.readAsDataURL(file);
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  return (
    <GlobalBackground className="bg-black text-white relative overflow-hidden">
      <Helmet>
        <title>Queens Mountain - Premium Platform for Writers and Readers</title>
        <meta name="description" content="Discover incredible stories, follow your favorite writers, and share reviews with the community. Join our vibrant community of storytellers and book lovers." />
        <meta name="keywords" content="stories, writers, readers, community, literature, fiction, novels" />
        <meta property="og:title" content="Queens Mountain - Premium Platform for Writers and Readers" />
        <meta property="og:description" content="A premium platform where writers share their stories and readers discover amazing content." />
        <meta property="og:type" content="website" />
        <meta name="twitter:card" content="summary_large_image" />
        {/* Google Analytics */}
        <script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
        <script>
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'GA_MEASUREMENT_ID');
          `}
        </script>
      </Helmet>
      {/* Landing Page Specific Background */}
      {backgroundImage && (
        <div 
          className="absolute inset-0 bg-cover bg-center bg-no-repeat"
          style={{ 
            backgroundImage: `url(${backgroundImage})`,
            filter: 'brightness(0.3)'
          }}
        />
      )}
      
      {/* Top Panel - Transparent Header */}
      <nav className="relative z-50 bg-black/70 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            {/* Site Title */}
            <div className="flex items-center cursor-pointer" onClick={() => navigate('/')}>
              {siteSettings?.header_logo ? (
                <div className="flex items-center space-x-3">
                  <img
                    src={siteSettings.header_logo}
                    alt={siteSettings.site_name || "Queens Mountain"}
                    className="h-8 w-auto object-contain"
                    loading="lazy"
                  />
                  <h1 className="text-2xl font-bold text-white">{siteSettings.site_name || "Queens Mountain"}</h1>
                </div>
              ) : (
                <h1 className="text-2xl font-bold text-white">{siteSettings?.site_name || "Queens Mountain"}</h1>
              )}
            </div>

            {/* Navigation Tabs - Desktop */}
            <div className="hidden lg:flex items-center space-x-1">
              {/* Search Tab */}
              <div className="flex items-center bg-white/10 rounded-lg px-3 py-1 mr-4">
                <Select value={searchType} onValueChange={setSearchType}>
                  <SelectTrigger className="w-24 h-8 bg-transparent border-none text-white text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-black border-white/20">
                    <SelectItem value="writer" className="text-white">Writer</SelectItem>
                    <SelectItem value="story" className="text-white">Story Title</SelectItem>
                    <SelectItem value="tags" className="text-white">Story Tags</SelectItem>
                    <SelectItem value="reader" className="text-white">Reader</SelectItem>
                  </SelectContent>
                </Select>
                <Input
                  type="text"
                  placeholder={`Search ${searchType}...`}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                  className="w-48 h-8 bg-transparent border-none text-white placeholder-gray-400 text-sm"
                />
                <Button 
                  size="sm" 
                  variant="ghost" 
                  onClick={handleSearch}
                  className="h-8 px-2 text-white hover:bg-white/20"
                >
                  <Search className="w-4 h-4" />
                </Button>
              </div>

              <Button
                variant="ghost"
                onClick={() => navigate('/reviews')}
                className="text-gray-300 hover:text-white hover:bg-white/20 px-4 py-2"
              >
                Reviews
              </Button>
              
              <Button
                variant="ghost"
                onClick={() => toast({ title: "News", description: "News section coming soon" })}
                className="text-gray-300 hover:text-white hover:bg-white/20 px-4 py-2"
              >
                News
              </Button>
              
              <Button
                variant="ghost"
                onClick={() => navigate('/genres')}
                className="text-gray-300 hover:text-white hover:bg-white/20 px-4 py-2"
              >
                Genres
              </Button>
              
              <Button
                variant="ghost"
                onClick={() => navigate('/forum')}
                className="text-gray-300 hover:text-white hover:bg-white/20 px-4 py-2"
              >
                Community
              </Button>
            </div>

            {/* Login Button */}
            <div className="flex items-center space-x-6">
              {loading ? (
                <div className="w-16 h-8 animate-pulse bg-white/20 rounded"></div>
              ) : user ? (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  
                  {/* Social Features - Notification Bell and Message Chat Bubble */}
                  <NotificationBell />
                  <MessageChatBubble />
                  
                  <Button 
                    variant="ghost" 
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-red-900/20"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              ) : (
                <Button 
                  variant="outline" 
                  onClick={() => setShowAuth(true)}
                  className="border-white/30 text-white hover:bg-white/20"
                >
                  Log In
                </Button>
              )}
              

            </div>
          </div>
        </div>
      </nav>

      {/* Right Panel Toggle Button - Fixed position */}
      <Button
        variant="ghost"
        size="sm"
        onClick={() => setShowRightPanel(!showRightPanel)}
        className={`fixed right-6 top-24 z-50 text-gray-400 hover:text-white hover:bg-black/40 backdrop-blur-sm p-3 rounded-full border border-white/20 transition-all duration-300 ${showRightPanel ? 'translate-x-0' : 'translate-x-0'}`}
      >
        <Menu className="w-5 h-5" />
      </Button>

      {/* Main Layout Container */}
      <div className="relative z-10 flex min-h-screen">
        {/* Left Panel - Popular Stories */}
        <div className={`hidden lg:block w-64 rounded-xl m-4 p-4 ${getPanelClasses('leftPanel')}`}>
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
            <TrendingUp className="w-5 h-5 mr-2" />
            Popular Stories
          </h3>
          <div className="space-y-4">
            {popularStories.length > 0 ? (
              popularStories.map((story) => (
                <div 
                  key={story.id}
                  onClick={() => handleStoryClick(story)}
                  className="cursor-pointer group bg-black/60 hover:bg-black/80 rounded-lg p-3 transition-all backdrop-blur-md border border-white/20"
                >
                  <div className="flex space-x-3">
                    <img
                      src={story.cover}
                      alt={story.title}
                      className="w-12 h-18 object-cover rounded"
                      loading="lazy"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-white group-hover:text-blue-300 truncate">
                        {story.title}
                      </p>
                      <p className="text-xs text-gray-400 truncate">
                        by {story.author}
                      </p>
                      <div className="flex items-center mt-1">
                        <Star className="w-3 h-3 text-yellow-400 fill-current" />
                        <span className="text-xs text-gray-300 ml-1">{story.rating}</span>
                      </div>
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="text-center py-8 px-4">
                <BookOpen className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                <p className="text-gray-400 text-sm mb-2">No stories yet</p>
                <p className="text-gray-500 text-xs">Be the first to publish a story!</p>
              </div>
            )}
          </div>
        </div>

        {/* Middle Panel - Main Content */}
        <div className="flex-1 relative">
          {/* Background upload moved to Admin Dashboard only */}

          {/* Main Content */}
          <div className="flex items-center justify-center min-h-screen p-8">
            <div className="text-center max-w-4xl">
              <h1 className="text-4xl md:text-6xl lg:text-8xl font-bold text-white mb-6 drop-shadow-2xl">
                {landingContent ? landingContent.hero_title : "Welcome to Queens Mountain"}
              </h1>
              <p className="text-lg md:text-xl lg:text-2xl text-gray-200 mb-8 max-w-3xl mx-auto drop-shadow-lg">
                {landingContent ? landingContent.hero_subtitle : "A premium platform where writers share their stories and readers discover amazing content. Join our community of storytellers and book lovers."}
              </p>
              
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <Button 
                  size="lg" 
                  className="bg-white text-black hover:bg-gray-200 px-8 py-4 text-lg font-semibold rounded-lg shadow-2xl"
                  onClick={() => setShowAuth(true)}
                >
                  {landingContent ? landingContent.hero_cta_text : "Get Started"}
                </Button>
                <Button 
                  size="lg" 
                  variant="outline" 
                  className="border-white/30 text-white hover:bg-white/20 px-8 py-4 text-lg rounded-lg"
                  onClick={() => navigate('/reviews')}
                >
                  Explore Stories
                </Button>
              </div>
            </div>
          </div>
        </div>

        {/* Right Panel - Menu */}
        <div className={`hidden xl:block transition-all duration-300 ${showRightPanel ? 'w-64' : 'w-0'} overflow-hidden`}>
          <div className={`w-64 rounded-xl m-4 p-4 transition-transform duration-300 ${getPanelClasses('rightPanel')} ${showRightPanel ? 'translate-x-0' : 'translate-x-full'}`}>
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-white">
                Menu
              </h3>
            </div>
          
          <div className="space-y-2">
            <Button
              variant="ghost"
              onClick={() => navigate('/forum')}
              className="w-full justify-start text-gray-300 hover:text-white hover:bg-white/10 rounded-lg"
            >
              <MessageSquare className="w-4 h-4 mr-3" />
              Community Forum
            </Button>
            
            <Button
              variant="ghost"
              onClick={() => navigate('/reviews')}
              className="w-full justify-start text-gray-300 hover:text-white hover:bg-white/10 rounded-lg"
            >
              <Award className="w-4 h-4 mr-3" />
              Top Reviews
            </Button>
            
            <Button
              variant="ghost"
              onClick={() => toast({ title: "Writers", description: "Browse writers directory" })}
              className="w-full justify-start text-gray-300 hover:text-white hover:bg-white/10 rounded-lg"
            >
              <PenTool className="w-4 h-4 mr-3" />
              Featured Writers
            </Button>
            
            <Button
              variant="ghost"
              onClick={() => toast({ title: "Genres", description: "Browse by genre" })}
              className="w-full justify-start text-gray-300 hover:text-white hover:bg-white/10 rounded-lg"
            >
              <BookOpen className="w-4 h-4 mr-3" />
              Browse Genres
            </Button>
            
            <Button
              variant="ghost"
              onClick={() => toast({ title: "Latest", description: "Latest updates" })}
              className="w-full justify-start text-gray-300 hover:text-white hover:bg-white/10 rounded-lg"
            >
              <Clock className="w-4 h-4 mr-3" />
              Latest Updates
            </Button>
            
            {/* Site Settings - Only visible to admins */}
            {isAdmin() && (
              <Button
                variant="ghost"
                onClick={() => navigate('/admin')}
                className="w-full justify-start text-gray-300 hover:text-white hover:bg-white/10 rounded-lg"
              >
                <Settings className="w-4 h-4 mr-3" />
                Site Settings
              </Button>
            )}

            {/* Panel Opacity Controls moved to Edit Profile */}
          </div>
          
          {showRightPanel && (
            <>
              <Separator className="my-6 bg-white/20" />
              
              <div>
                <h4 className="text-sm font-semibold text-gray-400 mb-3">Quick Stats</h4>
                <div className="space-y-2 text-sm text-gray-300">
                  <div className="flex justify-between">
                    <span>Active Writers:</span>
                    <span>{siteStats ? siteStats.totalUsers : '...'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Total Stories:</span>
                    <span>{siteStats ? siteStats.totalStories : '...'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Chapters:</span>
                    <span>{siteStats ? siteStats.totalPosts : '...'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Online Now:</span>
                    <span>{siteStats ? siteStats.activeUsers : '...'}</span>
                  </div>
                </div>
              </div>
            </>
          )}
          </div>
        </div>
      </div>

      {/* Footer */}
      <footer className="relative z-20 bg-black/80 backdrop-blur-md border-t border-white/10 mt-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="grid md:grid-cols-3 gap-8">
            {/* Company Info */}
            <div>
              <h3 className="text-xl font-bold text-white mb-4">Queens Mountain</h3>
              <p className="text-gray-400 mb-4">
                The premier platform for writers and readers to connect, share, and explore amazing stories.
              </p>
              <p className="text-gray-500 text-sm">
                © 2024 Queens Mountain. All rights reserved.
              </p>
            </div>

            {/* Quick Links */}
            <div>
              <h4 className="text-lg font-semibold text-white mb-4">Quick Links</h4>
              <div className="space-y-2">
                <button 
                  onClick={() => navigate('/about')}
                  className="block text-gray-400 hover:text-white transition-colors"
                >
                  About Us
                </button>
                <button 
                  onClick={() => navigate('/contact')}
                  className="block text-gray-400 hover:text-white transition-colors"
                >
                  Contact Us
                </button>
                <button className="block text-gray-400 hover:text-white transition-colors">
                  Community Guidelines
                </button>
                <button className="block text-gray-400 hover:text-white transition-colors">
                  Privacy Policy
                </button>
              </div>
            </div>

            {/* Contact Info */}
            <div>
              <h4 className="text-lg font-semibold text-white mb-4">Get in Touch</h4>
              <div className="space-y-2 text-gray-400">
                <p>Email us for support or inquiries</p>
                <a 
                  href="mailto:info@queensmountain.com"
                  className="text-blue-400 hover:text-blue-300 transition-colors"
                >
                  info@queensmountain.com
                </a>
                <p className="text-sm mt-4">
                  Response time: Within 24 hours
                </p>
              </div>
            </div>
          </div>
        </div>
      </footer>

      {/* Auth Dialog */}
      <Dialog open={showAuth} onOpenChange={setShowAuth}>
        <DialogContent className="sm:max-w-md bg-black border-white/20 text-white">
          <DialogHeader>
            <DialogTitle className="text-white">
              {isLogin ? 'Sign In' : 'Create Account'}
            </DialogTitle>
            <DialogDescription className="text-gray-400">
              {isLogin ? 'Welcome back to Queens Mountain' : 'Join the Queens Mountain community'}
            </DialogDescription>
          </DialogHeader>
          
          <form onSubmit={handleAuth} className="space-y-4">
            {!isLogin && (
              <div>
                <Label htmlFor="name" className="text-white">Name</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => setFormData({...formData, name: e.target.value})}
                  required={!isLogin}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
            )}
            
            <div>
              <Label htmlFor="email" className="text-white">Email</Label>
              <Input
                id="email"
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({...formData, email: e.target.value})}
                required
                className="bg-white/10 border-white/20 text-white"
              />
            </div>
            
            <div>
              <Label htmlFor="password" className="text-white">Password</Label>
              <Input
                id="password"
                type="password"
                value={formData.password}
                onChange={(e) => setFormData({...formData, password: e.target.value})}
                required
                className="bg-white/10 border-white/20 text-white"
              />
            </div>
            
            {!isLogin && (
              <div>
                <Label htmlFor="user_type" className="text-white">I am a...</Label>
                <Select value={formData.user_type} onValueChange={(value) => setFormData({...formData, user_type: value})}>
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-black border-white/20">
                    <SelectItem value="reader" className="text-white">Reader</SelectItem>
                    <SelectItem value="writer" className="text-white">Writer</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            )}
            
            <Button type="submit" className="w-full bg-white text-black hover:bg-gray-200">
              {isLogin ? 'Sign In' : 'Create Account'}
            </Button>
          </form>
          
          <div className="relative">
            <Separator className="bg-white/20" />
            <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-black px-2 text-sm text-gray-400">
              or
            </span>
          </div>
          
          <Button
            variant="outline"
            onClick={handleGoogleAuth}
            className="w-full border-white/20 text-gray-300 hover:bg-white/10"
          >
            Continue with Google
          </Button>
          
          <DialogFooter className="flex-col space-y-2">
            <Button
              variant="ghost"
              onClick={() => setIsLogin(!isLogin)}
              className="text-gray-300 hover:text-white"
            >
              {isLogin ? "Don't have an account? Sign up" : "Already have an account? Sign in"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </GlobalBackground>
  );
};

// Writer Profile Component - Patreon-style with Reader/Writer toggle
const WriterProfile = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses, updatePanelOpacity } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { writerId } = useParams();
  
  // View toggle state - only visible to profile owner
  const [viewMode, setViewMode] = useState('writer'); // 'reader' or 'writer'
  
  const [writerData, setWriterData] = useState({
    id: 'writer-123',
    name: 'Alex Writer',
    user_type: 'writer',
    bio: 'Creating epic fantasy adventures',
    profile_image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face',
    banner_image: 'https://images.unsplash.com/photo-1519681393784-d120d68551aa?w=1200&h=300&fit=crop',
    background_image: null, // New field for profile background
    subscriber_count: 1247,
    total_earnings: 5420.50,
    monthly_earnings: 890.25,
    monthly_goal: 2000.00,
    total_chapters: 156,
    total_stories: 8,
    avg_rating: 4.7,
    joined_date: '2023-03-15',
    about: 'Welcome to my creative world! I\'ve been writing fantasy novels for over 5 years, and I love creating stories that transport readers to magical realms filled with adventure, mystery, and heart. My writing focuses on character-driven narratives with rich world-building and emotional depth.\n\nI publish new chapters weekly, and I always love hearing from my readers. Your support means everything to me and helps me continue creating the stories you love!',
    social_links: {
      twitter: '@alexwriter',
      discord: 'AlexWriter#1234',
      website: 'https://alexwriter.com'
    },
    goals: [
      {
        id: 1,
        title: 'Monthly Writing Goal',
        description: 'Reach $2,000/month to write full-time',
        current: 890.25,
        target: 2000.00,
        active: true
      }
    ]
  });

  const [subscriptionTiers, setSubscriptionTiers] = useState([
    {
      id: 1,
      name: 'Supporter',
      price: 3,
      description: 'Support my writing journey',
      benefits: ['Early access to chapters', 'Monthly progress updates', 'Behind-the-scenes content'],
      subscriber_count: 234
    },
    {
      id: 2,
      name: 'Fan',
      price: 8,
      description: 'Get exclusive content and perks',
      benefits: ['All Supporter benefits', 'Exclusive bonus chapters', 'Character art and sketches', 'Monthly Q&A sessions'],
      subscriber_count: 156
    },
    {
      id: 3,
      name: 'Champion',
      price: 15,
      description: 'Maximum support with premium access',
      benefits: ['All Fan benefits', 'Your name in story credits', 'Input on story direction', 'Private Discord access', 'Monthly video calls'],
      subscriber_count: 45
    }
  ]);

  const [recentChapters, setRecentChapters] = useState([
    {
      id: 1,
      title: 'Chapter 23: The Dragon\'s Awakening',
      story: 'Chronicles of Aethermoor',
      published: '2 days ago',
      is_free: true,
      price: 0,
      excerpt: 'The ancient dragon stirred from its millennium slumber as the prophecy began to unfold...',
      likes: 89,
      comments: 23
    },
    {
      id: 2,
      title: 'Chapter 22: Shadows in the Night',
      story: 'Chronicles of Aethermoor',
      published: '1 week ago',
      is_free: false,
      price: 2.50,
      required_tier: 'Supporter',
      excerpt: 'Locked content - Subscribe to read this chapter',
      likes: 156,
      comments: 45
    },
    {
      id: 3,
      title: 'Character Spotlight: Lyra the Mage',
      story: 'Bonus Content',
      published: '2 weeks ago',
      is_free: false,
      price: 0,
      required_tier: 'Fan',
      excerpt: 'Exclusive behind-the-scenes look at one of my favorite characters...',
      likes: 67,
      comments: 18
    }
  ]);

  const [isOwner, setIsOwner] = useState(true); // Temporarily set to true for testing
  const [isSubscribed, setIsSubscribed] = useState(false);
  const [currentSubscription, setCurrentSubscription] = useState(null);
  const [isEditing, setIsEditing] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [uploadingHeader, setUploadingHeader] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    // Check if current user is the profile owner
    if (user && (user.id === writerData.id || !writerId)) {
      setIsOwner(true);
    }
    
    // Mock subscription status
    if (user && user.user_type === 'reader') {
      setIsSubscribed(false); // TODO: Check actual subscription status
    }
  }, [user, writerId, writerData.id]);

  const handleSubscribe = (tier) => {
    // Navigate to subscription page with tier pre-selected
    navigate(`/writer/${writerId || writerData.id}/subscribe`, { state: { selectedTier: tier } });
  };

  const handleOneTimeSupport = () => {
    // Open tip dialog or navigate to tip page
    // For now, show toast - will implement tip modal later
    toast({
      title: "Tip Feature",
      description: "One-time tip feature will be implemented in the next update.",
    });
  };

  const handleEditProfile = () => {
    setIsEditing(true);
  };

  const handleSaveProfile = async () => {
    try {
      // TODO: Implement actual API call to update writer profile
      toast({
        title: "Profile Updated!",
        description: "Your writer profile has been updated successfully.",
      });
      setIsEditing(false);
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to update profile. Please try again.",
        variant: "destructive",
      });
    }
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    // TODO: Reset form data to original values
  };

  const handleProfileImageUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    setUploadingImage(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await axios.post(`${API}/upload/image`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        withCredentials: true
      });
      
      setWriterData(prev => ({
        ...prev,
        profile_image: response.data.url
      }));
      
      toast({
        title: "Profile Image Updated!",
        description: "Your profile image has been updated.",
      });
    } catch (error) {
      toast({
        title: "Upload Failed",
        description: "Failed to upload image. Please try again.",
        variant: "destructive",
      });
    } finally {
      setUploadingImage(false);
    }
  };

  const handleHeaderImageUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    setUploadingHeader(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await axios.post(`${API}/upload/image`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        withCredentials: true
      });
      
      setWriterData(prev => ({
        ...prev,
        banner_image: response.data.url
      }));
      
      toast({
        title: "Header Image Updated!",
        description: "Your header image has been updated.",
      });
    } catch (error) {
      toast({
        title: "Upload Failed",
        description: "Failed to upload header image. Please try again.",
        variant: "destructive",
      });
    } finally {
      setUploadingHeader(false);
    }
  };

  if (!user && !writerId) {
    return <Navigate to="/" replace />;
  }

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              
              {/* View Toggle - Only visible to profile owner */}
              {isOwner && (
                <div className="flex items-center space-x-1 bg-white/10 rounded-lg p-1">
                  <Button
                    variant={viewMode === 'reader' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => setViewMode('reader')}
                    className={viewMode === 'reader' ? 'bg-white text-black' : 'text-white hover:bg-white/20'}
                  >
                    Reader View
                  </Button>
                  <Button
                    variant={viewMode === 'writer' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => setViewMode('writer')}
                    className={viewMode === 'writer' ? 'bg-white text-black' : 'text-white hover:bg-white/20'}
                  >
                    Manage
                  </Button>
                </div>
              )}
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Render appropriate view based on viewMode */}
      {viewMode === 'reader' ? (
        <ReaderFacingView />
      ) : (
        <WriterManagementView />
      )}
    </GlobalBackground>
  );

  // Reader-Facing View (Patreon-style)
  function ReaderFacingView() {
    return (
      <div 
        className="min-h-screen"
        style={{
          backgroundImage: writerData.background_image 
            ? `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.8)), url(${writerData.background_image})`
            : 'none',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundAttachment: 'fixed'
        }}
      >
        {/* Hero Banner Section */}
        <div className="relative">
          {writerData.banner_image ? (
            <div 
              className="h-80 bg-cover bg-center"
              style={{ backgroundImage: `url(${writerData.banner_image})` }}
            >
              <div className="absolute inset-0 bg-black/40"></div>
            </div>
          ) : (
            <div className="h-80 bg-gradient-to-r from-purple-900 to-blue-900">
              <div className="absolute inset-0 bg-black/30"></div>
            </div>
          )}
          
          {/* Profile Content Overlay */}
          <div className="absolute inset-0 flex items-end">
            <div className="w-full max-w-7xl mx-auto px-6 pb-8">
              <div className="flex items-end space-x-6">
                {/* Profile Image */}
                <img
                  src={writerData.profile_image}
                  alt={writerData.name}
                  className="w-32 h-32 rounded-full border-4 border-white shadow-lg object-cover"
                  loading="lazy"
                />
                
                {/* Creator Info */}
                <div className="flex-1 min-w-0 pb-4">
                  <h1 className="text-4xl font-bold text-white drop-shadow-lg mb-2">
                    {writerData.name}
                  </h1>
                  <p className="text-xl text-gray-200 drop-shadow-md mb-3">
                    {writerData.bio}
                  </p>
                  <div className="flex items-center space-x-4 text-white">
                    <div className="flex items-center space-x-2">
                      <Users className="w-5 h-5" />
                      <span className="font-semibold">{writerData.subscriber_count.toLocaleString()} members</span>
                    </div>
                    <div className="flex items-center space-x-2">
                      <span>•</span>
                      <span>{writerData.total_chapters} posts</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content Area with enhanced background support */}
        <div className="max-w-7xl mx-auto px-6 py-8">
          <div className="grid lg:grid-cols-3 gap-8">
            
            {/* Left Sidebar - Join/Support */}
            <div className="lg:order-2 space-y-6">
              {/* Join Card - Patreon Style with background blur support */}
              <Card className={`${getPanelClasses('rightPanel')} sticky top-8 overflow-hidden backdrop-blur-sm ${
                writerData.background_image ? 'bg-black/80 border-white/20' : ''
              }`}>
                <CardContent className="p-0">
                  {/* Profile Summary */}
                  <div className="p-6 text-center border-b border-white/10">
                    <img
                      src={writerData.profile_image}
                      alt={writerData.name}
                      className="w-20 h-20 rounded-full mx-auto mb-3 object-cover"
                      loading="lazy"
                    />
                    <h3 className="text-white font-bold text-lg mb-1">{writerData.name}</h3>
                    <p className="text-gray-400 text-sm mb-3">{writerData.bio}</p>
                    
                    {/* Stats */}
                    <div className="text-center">
                      <div className="text-2xl font-bold text-white">
                        {writerData.total_chapters.toLocaleString()} posts
                      </div>
                      <div className="text-sm text-gray-400">
                        Unlock {writerData.total_chapters} exclusive posts
                      </div>
                    </div>
                  </div>

                  {/* Join Section */}
                  <div className="p-6">
                    <div className="text-center mb-4">
                      <h4 className="text-white font-bold text-lg mb-2">
                        Join a community of {writerData.subscriber_count.toLocaleString()} paid members
                      </h4>
                    </div>
                    
                    {/* Pricing */}
                    <div className="bg-orange-500/10 border border-orange-500/20 rounded-lg p-4 mb-4">
                      <div className="text-center">
                        <div className="text-white text-sm mb-1">Starting at</div>
                        <div className="text-3xl font-bold text-orange-400">$3</div>
                        <div className="text-gray-300 text-sm">/month</div>
                      </div>
                    </div>

                    {/* Join Buttons */}
                    <div className="space-y-3">
                      <Button 
                        className="w-full bg-orange-500 hover:bg-orange-600 text-white font-semibold py-3 text-lg"
                        onClick={() => navigate(`/writer/${writerId || writerData.id}/subscribe`)}
                      >
                        Join now
                      </Button>
                      
                      {/* One-time support */}
                      <div className="text-center">
                        <span className="text-gray-400 text-sm">or </span>
                        <button 
                          className="text-blue-400 hover:text-blue-300 text-sm underline"
                          onClick={handleOneTimeSupport}
                        >
                          send a one-time tip
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* Recent Supporters */}
                  <div className="px-6 pb-6">
                    <h5 className="text-white font-semibold mb-3">Recent supporters</h5>
                    <div className="space-y-3">
                      {[
                        { name: 'Sarah M.', amount: 15, time: '2 hours ago', avatar: 'SM' },
                        { name: 'Jake D.', amount: 8, time: '1 day ago', avatar: 'JD' },
                        { name: 'Emma L.', amount: 3, time: '3 days ago', avatar: 'EL' }
                      ].map((supporter, index) => (
                        <div key={index} className="flex items-center space-x-3">
                          <div className="w-8 h-8 bg-gray-600 rounded-full flex items-center justify-center">
                            <span className="text-white text-xs font-semibold">
                              {supporter.avatar}
                            </span>
                          </div>
                          <div className="flex-1">
                            <div className="text-white text-sm font-medium">{supporter.name}</div>
                            <div className="text-gray-400 text-xs">{supporter.time}</div>
                          </div>
                          <div className="text-orange-400 font-semibold text-sm">
                            ${supporter.amount}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
            
            {/* Main Content Feed */}
            <div className="lg:col-span-2 lg:order-1">
              {/* Page Title */}
              <div className="mb-8">
                <h2 className="text-3xl font-bold text-white mb-2">
                  Recent posts by {writerData.name}
                </h2>
                
                {/* Filters - Patreon Style */}
                <div className="flex items-center space-x-4 mb-6">
                  <Select defaultValue="all">
                    <SelectTrigger className="w-40 bg-gray-800/80 border-gray-600 text-white backdrop-blur-sm">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="bg-gray-800/90 border-gray-600 backdrop-blur-sm">
                      <SelectItem value="all" className="text-white">All posts</SelectItem>
                      <SelectItem value="free" className="text-white">Free posts</SelectItem>
                      <SelectItem value="members" className="text-white">Members only</SelectItem>
                    </SelectContent>
                  </Select>
                  
                  <Select defaultValue="recent">
                    <SelectTrigger className="w-40 bg-gray-800/80 border-gray-600 text-white backdrop-blur-sm">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="bg-gray-800/90 border-gray-600 backdrop-blur-sm">
                      <SelectItem value="recent" className="text-white">Most recent</SelectItem>
                      <SelectItem value="popular" className="text-white">Most popular</SelectItem>
                      <SelectItem value="oldest" className="text-white">Oldest first</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* Posts Feed with background support */}
              <div className="space-y-6">
                {recentChapters.map((chapter) => (
                  <Card key={chapter.id} className={`${getPanelClasses('mainPanel')} overflow-hidden hover:ring-1 hover:ring-white/10 transition-all backdrop-blur-sm ${
                    writerData.background_image ? 'bg-black/80 border-white/20' : ''
                  }`}>
                    <CardContent className="p-0">
                      {/* Post Header */}
                      <div className="p-6 border-b border-white/10">
                        <div className="flex items-center justify-between mb-3">
                          <div className="flex items-center space-x-3">
                            <img
                              src={writerData.profile_image}
                              alt={writerData.name}
                              className="w-10 h-10 rounded-full object-cover"
                              loading="lazy"
                            />
                            <div>
                              <h3 className="text-white font-semibold">{writerData.name}</h3>
                              <div className="flex items-center space-x-2 text-sm text-gray-400">
                                <span>{chapter.published}</span>
                                <span>•</span>
                                <span className={`px-2 py-1 rounded text-xs ${
                                  chapter.is_free ? 'bg-green-600' : 'bg-yellow-600'
                                }`}>
                                  {chapter.is_free ? 'Public' : 'Members only'}
                                </span>
                              </div>
                            </div>
                          </div>
                          
                          {/* Post actions */}
                          <div className="flex items-center space-x-2">
                            <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                              <MessageSquare className="w-4 h-4" />
                            </Button>
                            <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                              <Star className="w-4 h-4" />
                            </Button>
                          </div>
                        </div>

                        <h4 className="text-xl font-bold text-white mb-2">{chapter.title}</h4>
                      </div>

                      {/* Post Content */}
                      <div className="p-6">
                        {!chapter.is_free && !isSubscribed ? (
                          <div className="space-y-4">
                            {/* Preview text */}
                            <p className="text-gray-300">
                              {chapter.excerpt ? chapter.excerpt.substring(0, 150) + '...' : 'This post contains exclusive content for members.'}
                            </p>
                            
                            {/* Locked content indicator */}
                            <div className="bg-gray-800/50 border border-gray-600 rounded-lg p-6 text-center">
                              <div className="w-16 h-16 bg-orange-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                                <BookOpen className="w-8 h-8 text-orange-400" />
                              </div>
                              <h5 className="text-white font-semibold mb-2">This post is for members only</h5>
                              <p className="text-gray-400 text-sm mb-4">
                                Join now to read this story and get access to all exclusive content.
                              </p>
                              <Button 
                                className="bg-orange-500 hover:bg-orange-600 text-white"
                                onClick={() => navigate(`/writer/${writerId || writerData.id}/subscribe`)}
                              >
                                Become a member
                              </Button>
                            </div>
                          </div>
                        ) : (
                          <div className="prose prose-invert max-w-none">
                            <p className="text-gray-300 leading-relaxed">
                              {chapter.excerpt}
                            </p>
                            
                            {/* Continue reading for longer posts */}
                            <div className="mt-4">
                              <Button variant="outline" className="border-white/20 text-white hover:bg-white/10">
                                Continue reading →
                              </Button>
                            </div>
                          </div>
                        )}
                      </div>

                      {/* Post Footer */}
                      <div className="px-6 pb-6 flex items-center justify-between border-t border-white/10 pt-4">
                        <div className="flex items-center space-x-6">
                          <div className="flex items-center space-x-2">
                            <button className="text-gray-400 hover:text-red-400 transition-colors">
                              <span className="text-lg">♥</span>
                            </button>
                            <span className="text-white text-sm">{chapter.likes}</span>
                          </div>
                          <div className="flex items-center space-x-2">
                            <MessageSquare className="w-4 h-4 text-gray-400" />
                            <span className="text-white text-sm">{chapter.comments}</span>
                          </div>
                        </div>
                        <div className="text-gray-400 text-sm">
                          Share
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>

              {/* About Section with background support */}
              <Card className={`${getPanelClasses('mainPanel')} mt-8 backdrop-blur-sm ${
                writerData.background_image ? 'bg-black/80 border-white/20' : ''
              }`}>
                <CardContent className="p-6">
                  <h3 className="text-2xl font-bold text-white mb-4">About {writerData.name}</h3>
                  <div className="prose prose-invert max-w-none">
                    <p className="text-gray-300 leading-relaxed mb-4">
                      {writerData.about}
                    </p>
                  </div>
                  
                  {/* Social Links */}
                  {Object.keys(writerData.social_links).length > 0 && (
                    <div className="mt-6 pt-4 border-t border-white/10">
                      <h4 className="text-white font-semibold mb-3">Find me elsewhere</h4>
                      <div className="flex flex-wrap gap-3">
                        {Object.entries(writerData.social_links).map(([platform, handle]) => (
                          handle && (
                            <a
                              key={platform}
                              href={platform === 'website' ? handle : `#`}
                              className="inline-flex items-center space-x-2 text-blue-400 hover:text-blue-300 text-sm"
                            >
                              <span className="capitalize">{platform}</span>
                              <span>→</span>
                            </a>
                          )
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* Load more */}
              <div className="text-center mt-8">
                <Button 
                  variant="outline" 
                  className="border-white/20 text-white hover:bg-white/10 backdrop-blur-sm"
                >
                  Load more posts
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Writer Management View
  function WriterManagementView() {
    const [activeTab, setActiveTab] = useState('overview');
    
    // Check if this is initial setup (no tiers created yet)
    const isInitialSetup = subscriptionTiers.length === 0;

    if (isInitialSetup) {
      return <CreatorOnboardingFlow />;
    }

    // Main Writer Dashboard
    return (
      <div className="max-w-7xl mx-auto px-6 py-8">
        {/* Dashboard Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">Creator Dashboard</h1>
          <p className="text-gray-400">Manage your content, track your progress, and engage with your community</p>
        </div>

        {/* Quick Stats Cards */}
        <div className="grid md:grid-cols-4 gap-6 mb-8">
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Total Members</p>
                  <p className="text-3xl font-bold text-white">{writerData.subscriber_count}</p>
                  <p className="text-green-400 text-xs mt-1">+12 this month</p>
                </div>
                <Users className="w-8 h-8 text-blue-400" />
              </div>
            </CardContent>
          </Card>

          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Monthly Earnings</p>
                  <p className="text-3xl font-bold text-green-400">${writerData.monthly_earnings}</p>
                  <p className="text-green-400 text-xs mt-1">+8.2% from last month</p>
                </div>
                <div className="text-green-400">💰</div>
              </div>
            </CardContent>
          </Card>

          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Total Posts</p>
                  <p className="text-3xl font-bold text-white">{writerData.total_chapters}</p>
                  <p className="text-blue-400 text-xs mt-1">3 drafts</p>
                </div>
                <BookOpen className="w-8 h-8 text-purple-400" />
              </div>
            </CardContent>
          </Card>

          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Engagement</p>
                  <p className="text-3xl font-bold text-white">4.8</p>
                  <p className="text-yellow-400 text-xs mt-1">Avg rating</p>
                </div>
                <Star className="w-8 h-8 text-yellow-400" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Main Dashboard Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList className="bg-gray-800/50 border border-gray-700">
            <TabsTrigger value="overview" className="text-gray-300 data-[state=active]:bg-blue-600 data-[state=active]:text-white">
              Overview
            </TabsTrigger>
            <TabsTrigger value="content" className="text-gray-300 data-[state=active]:bg-blue-600 data-[state=active]:text-white">
              Content
            </TabsTrigger>
            <TabsTrigger value="members" className="text-gray-300 data-[state=active]:bg-blue-600 data-[state=active]:text-white">
              Members
            </TabsTrigger>
            <TabsTrigger value="earnings" className="text-gray-300 data-[state=active]:bg-blue-600 data-[state=active]:text-white">
              Earnings
            </TabsTrigger>
            <TabsTrigger value="settings" className="text-gray-300 data-[state=active]:bg-blue-600 data-[state=active]:text-white">
              Settings
            </TabsTrigger>
          </TabsList>

          {/* Overview Tab */}
          <TabsContent value="overview" className="space-y-6">
            <OverviewTab />
          </TabsContent>

          {/* Content Tab */}
          <TabsContent value="content" className="space-y-6">
            <ContentTab />
          </TabsContent>

          {/* Members Tab */}
          <TabsContent value="members" className="space-y-6">
            <MembersTab />
          </TabsContent>

          {/* Earnings Tab */}
          <TabsContent value="earnings" className="space-y-6">
            <EarningsTab />
          </TabsContent>

          {/* Settings Tab */}
          <TabsContent value="settings" className="space-y-6">
            <SettingsTab />
          </TabsContent>
        </Tabs>
      </div>
    );

    // Overview Tab Component
    function OverviewTab() {
      return (
        <div className="grid lg:grid-cols-2 gap-6">
          {/* Recent Activity */}
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">Recent Activity</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {[
                { type: 'member', text: 'Sarah M. became a Supporter', time: '2 hours ago', icon: Users },
                { type: 'post', text: 'Chapter 23 published successfully', time: '1 day ago', icon: BookOpen },
                { type: 'earnings', text: 'Monthly payout of $890 processed', time: '3 days ago', icon: '💰' },
                { type: 'member', text: '3 new members joined this week', time: '1 week ago', icon: Users }
              ].map((activity, index) => (
                <div key={index} className="flex items-center space-x-3 p-3 bg-gray-800/30 rounded-lg">
                  {typeof activity.icon === 'string' ? (
                    <span className="text-lg">{activity.icon}</span>
                  ) : (
                    <activity.icon className="w-5 h-5 text-blue-400" />
                  )}
                  <div className="flex-1">
                    <p className="text-white text-sm">{activity.text}</p>
                    <p className="text-gray-400 text-xs">{activity.time}</p>
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>

          {/* Quick Actions */}
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">Quick Actions</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <Button 
                className="w-full bg-blue-600 hover:bg-blue-700 text-white justify-start h-12"
                onClick={() => navigate('/create-chapter')}
              >
                <PenTool className="w-5 h-5 mr-3" />
                Create New Post
              </Button>
              
              <Button 
                variant="outline"
                className="w-full border-white/20 text-white hover:bg-white/10 justify-start h-12"
                onClick={() => setActiveTab('members')}
              >
                <Users className="w-5 h-5 mr-3" />
                View Members
              </Button>
              
              <Button 
                variant="outline"
                className="w-full border-white/20 text-white hover:bg-white/10 justify-start h-12"
                onClick={() => setActiveTab('earnings')}
              >
                <TrendingUp className="w-5 h-5 mr-3" />
                Check Earnings
              </Button>
              
              <Button 
                variant="outline"
                className="w-full border-white/20 text-white hover:bg-white/10 justify-start h-12"
                onClick={() => setActiveTab('settings')}
              >
                <Settings className="w-5 h-5 mr-3" />
                Manage Tiers
              </Button>
            </CardContent>
          </Card>

          {/* Goals Progress */}
          <Card className={`${getPanelClasses('mainPanel')} lg:col-span-2`}>
            <CardHeader>
              <CardTitle className="text-white">Monthly Goals</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <div className="flex justify-between items-center mb-2">
                  <span className="text-white">Monthly Earnings Goal</span>
                  <span className="text-gray-400">${writerData.monthly_earnings} / $2,000</span>
                </div>
                <div className="w-full bg-gray-700 rounded-full h-3">
                  <div 
                    className="bg-green-500 h-3 rounded-full transition-all duration-300"
                    style={{ width: `${(writerData.monthly_earnings / 2000) * 100}%` }}
                  ></div>
                </div>
              </div>
              
              <div>
                <div className="flex justify-between items-center mb-2">
                  <span className="text-white">New Members Goal</span>
                  <span className="text-gray-400">12 / 20 this month</span>
                </div>
                <div className="w-full bg-gray-700 rounded-full h-3">
                  <div 
                    className="bg-blue-500 h-3 rounded-full transition-all duration-300"
                    style={{ width: '60%' }}
                  ></div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      );
    }

    // Content Tab Component
    function ContentTab() {
      const [postType, setPostType] = useState('all');
      const [showCreateForm, setShowCreateForm] = useState(false);

      return (
        <div className="space-y-6">
          {/* Content Header */}
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold text-white">Content Management</h2>
              <p className="text-gray-400">Create, edit, and manage your posts</p>
            </div>
            <Button 
              className="bg-blue-600 hover:bg-blue-700 text-white"
              onClick={() => setShowCreateForm(true)}
            >
              <PenTool className="w-4 h-4 mr-2" />
              New Post
            </Button>
          </div>

          {/* Content Filters */}
          <div className="flex space-x-4">
            <Select value={postType} onValueChange={setPostType}>
              <SelectTrigger className="w-48 bg-gray-800 border-gray-600 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-gray-800 border-gray-600">
                <SelectItem value="all" className="text-white">All Posts</SelectItem>
                <SelectItem value="published" className="text-white">Published</SelectItem>
                <SelectItem value="draft" className="text-white">Drafts</SelectItem>
                <SelectItem value="scheduled" className="text-white">Scheduled</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Posts List */}
          <div className="space-y-4">
            {recentChapters.map((post) => (
              <Card key={post.id} className={`${getPanelClasses('mainPanel')}`}>
                <CardContent className="p-6">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-2">
                        <h3 className="text-white font-semibold text-lg">{post.title}</h3>
                        <span className={`px-2 py-1 rounded text-xs ${
                          post.is_free ? 'bg-green-600' : 'bg-yellow-600'
                        }`}>
                          {post.is_free ? 'Public' : 'Members Only'}
                        </span>
                      </div>
                      <p className="text-gray-400 text-sm mb-2">{post.excerpt}</p>
                      <div className="flex items-center space-x-4 text-sm text-gray-400">
                        <span>{post.published}</span>
                        <span>•</span>
                        <span>{post.likes} likes</span>
                        <span>•</span>
                        <span>{post.comments} comments</span>
                      </div>
                    </div>
                    
                    <div className="flex items-center space-x-2">
                      <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                        <TrendingUp className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      );
    }

    // Members Tab Component
    function MembersTab() {
      return (
        <div className="space-y-6">
          <div>
            <h2 className="text-2xl font-bold text-white mb-2">Member Management</h2>
            <p className="text-gray-400">View and manage your subscribers across different tiers</p>
          </div>

          {/* Member Stats by Tier */}
          <div className="grid md:grid-cols-3 gap-6">
            {subscriptionTiers.map((tier) => (
              <Card key={tier.id} className={`${getPanelClasses('mainPanel')}`}>
                <CardContent className="p-6">
                  <h3 className="text-white font-bold text-lg mb-2">{tier.name}</h3>
                  <div className="text-3xl font-bold text-blue-400 mb-1">
                    {tier.subscriber_count || 0}
                  </div>
                  <p className="text-gray-400 text-sm mb-4">members</p>
                  <div className="text-green-400 font-semibold">
                    ${((tier.subscriber_count || 0) * tier.price).toFixed(0)}/month
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Recent Members */}
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">Recent Members</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {[
                  { name: 'Sarah Mitchell', tier: 'Champion', joined: '2 days ago', avatar: 'SM' },
                  { name: 'Jake Davis', tier: 'Fan', joined: '5 days ago', avatar: 'JD' },
                  { name: 'Emma Lopez', tier: 'Supporter', joined: '1 week ago', avatar: 'EL' },
                  { name: 'Mike Johnson', tier: 'Fan', joined: '1 week ago', avatar: 'MJ' }
                ].map((member, index) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-gray-800/30 rounded-lg">
                    <div className="flex items-center space-x-3">
                      <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center">
                        <span className="text-white font-semibold text-sm">{member.avatar}</span>
                      </div>
                      <div>
                        <p className="text-white font-medium">{member.name}</p>
                        <p className="text-gray-400 text-sm">{member.tier} • {member.joined}</p>
                      </div>
                    </div>
                    <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                      <MessageSquare className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>
      );
    }

    // Earnings Tab Component
    function EarningsTab() {
      return (
        <div className="space-y-6">
          <div>
            <h2 className="text-2xl font-bold text-white mb-2">Earnings & Payouts</h2>
            <p className="text-gray-400">Track your income and manage withdrawal settings</p>
          </div>

          {/* Integrate WriterEarningsDashboard from WithdrawalComponents */}
          <WriterEarningsDashboard writerId={writerId || writerData.id} />
        </div>
      );
    }

    // Settings Tab Component
    function SettingsTab() {
      const [activeSettingsTab, setActiveSettingsTab] = useState('profile');
      
      return (
        <div className="space-y-6">
          <div>
            <h2 className="text-2xl font-bold text-white mb-2">Profile & Settings</h2>
            <p className="text-gray-400">Customize your profile appearance and manage your subscription tiers</p>
          </div>

          {/* Settings Sub-tabs */}
          <Tabs value={activeSettingsTab} onValueChange={setActiveSettingsTab} className="space-y-6">
            <TabsList className="bg-gray-800/50 border border-gray-700">
              <TabsTrigger value="profile" className="text-gray-300 data-[state=active]:bg-purple-600 data-[state=active]:text-white">
                Profile Info
              </TabsTrigger>
              <TabsTrigger value="appearance" className="text-gray-300 data-[state=active]:bg-purple-600 data-[state=active]:text-white">
                Appearance
              </TabsTrigger>
              <TabsTrigger value="tiers" className="text-gray-300 data-[state=active]:bg-purple-600 data-[state=active]:text-white">
                Subscription Tiers
              </TabsTrigger>
              <TabsTrigger value="notifications" className="text-gray-300 data-[state=active]:bg-purple-600 data-[state=active]:text-white">
                Notifications
              </TabsTrigger>
            </TabsList>

            {/* Profile Information Tab */}
            <TabsContent value="profile" className="space-y-6">
              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white">Basic Information</CardTitle>
                  <CardDescription className="text-gray-400">
                    Update your display name, bio, and category
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid md:grid-cols-2 gap-4">
                    <div>
                      <Label className="text-white">Display Name</Label>
                      <Input
                        value={writerData.name}
                        onChange={(e) => setWriterData(prev => ({ ...prev, name: e.target.value }))}
                        className="bg-gray-800 border-gray-600 text-white mt-1"
                      />
                    </div>
                    <div>
                      <Label className="text-white">Category</Label>
                      <Select defaultValue="fantasy">
                        <SelectTrigger className="bg-gray-800 border-gray-600 text-white mt-1">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent className="bg-gray-800 border-gray-600">
                          <SelectItem value="fantasy" className="text-white">Fantasy & Sci-Fi</SelectItem>
                          <SelectItem value="romance" className="text-white">Romance</SelectItem>
                          <SelectItem value="fiction" className="text-white">Fiction</SelectItem>
                          <SelectItem value="horror" className="text-white">Horror</SelectItem>
                          <SelectItem value="mystery" className="text-white">Mystery & Thriller</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div>
                    <Label className="text-white">Bio / Tagline</Label>
                    <Textarea
                      value={writerData.bio}
                      onChange={(e) => setWriterData(prev => ({ ...prev, bio: e.target.value }))}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                      rows="2"
                      placeholder="Creating epic fantasy adventures that transport you to magical realms"
                    />
                  </div>
                  <div>
                    <Label className="text-white">About (Detailed Description)</Label>
                    <Textarea
                      value={writerData.about}
                      onChange={(e) => setWriterData(prev => ({ ...prev, about: e.target.value }))}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                      rows="4"
                      placeholder="Tell readers about your work, writing style, and what they can expect..."
                    />
                  </div>
                  
                  {/* Social Links */}
                  <div>
                    <Label className="text-white mb-3 block">Social Media Links</Label>
                    <div className="grid md:grid-cols-2 gap-4">
                      <div>
                        <Label className="text-gray-400 text-sm">Website</Label>
                        <Input
                          value={writerData.social_links?.website || ''}
                          onChange={(e) => setWriterData(prev => ({ 
                            ...prev, 
                            social_links: { ...prev.social_links, website: e.target.value }
                          }))}
                          placeholder="https://yourwebsite.com"
                          className="bg-gray-800 border-gray-600 text-white mt-1"
                        />
                      </div>
                      <div>
                        <Label className="text-gray-400 text-sm">Twitter</Label>
                        <Input
                          value={writerData.social_links?.twitter || ''}
                          onChange={(e) => setWriterData(prev => ({ 
                            ...prev, 
                            social_links: { ...prev.social_links, twitter: e.target.value }
                          }))}
                          placeholder="@yourusername"
                          className="bg-gray-800 border-gray-600 text-white mt-1"
                        />
                      </div>
                      <div>
                        <Label className="text-gray-400 text-sm">Discord</Label>
                        <Input
                          value={writerData.social_links?.discord || ''}
                          onChange={(e) => setWriterData(prev => ({ 
                            ...prev, 
                            social_links: { ...prev.social_links, discord: e.target.value }
                          }))}
                          placeholder="Username#1234"
                          className="bg-gray-800 border-gray-600 text-white mt-1"
                        />
                      </div>
                      <div>
                        <Label className="text-gray-400 text-sm">Instagram</Label>
                        <Input
                          value={writerData.social_links?.instagram || ''}
                          onChange={(e) => setWriterData(prev => ({ 
                            ...prev, 
                            social_links: { ...prev.social_links, instagram: e.target.value }
                          }))}
                          placeholder="@yourusername"
                          className="bg-gray-800 border-gray-600 text-white mt-1"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="flex justify-end pt-4">
                    <Button className="bg-blue-600 hover:bg-blue-700 text-white">
                      Save Profile Changes
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            {/* Profile Appearance Tab */}
            <TabsContent value="appearance" className="space-y-6">
              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white">Profile Appearance</CardTitle>
                  <CardDescription className="text-gray-400">
                    Customize how your profile looks to readers
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  
                  {/* Profile Image */}
                  <div>
                    <Label className="text-white mb-3 block">Profile Picture</Label>
                    <div className="flex items-center space-x-6">
                      <div className="w-24 h-24 rounded-full overflow-hidden border-2 border-gray-600">
                        <img
                          src={writerData.profile_image}
                          alt="Profile"
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div>
                        <input
                          type="file"
                          id="profile-image-settings"
                          accept="image/*"
                          onChange={handleProfileImageUpload}
                          className="hidden"
                        />
                        <Button
                          variant="outline"
                          onClick={() => document.getElementById('profile-image-settings').click()}
                          className="border-white/20 text-white hover:bg-white/10 mb-2"
                          disabled={uploadingImage}
                        >
                          {uploadingImage ? (
                            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                          ) : (
                            <Upload className="w-4 h-4 mr-2" />
                          )}
                          Change Profile Picture
                        </Button>
                        <p className="text-xs text-gray-400">
                          Recommended: 400x400px, JPG or PNG
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Header/Banner Image */}
                  <div>
                    <Label className="text-white mb-3 block">Header Banner Image</Label>
                    <div className="space-y-4">
                      <div 
                        className="h-48 rounded-lg bg-cover bg-center border-2 border-gray-600 relative overflow-hidden"
                        style={{ 
                          backgroundImage: writerData.banner_image 
                            ? `url(${writerData.banner_image})` 
                            : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' 
                        }}
                      >
                        <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                          {!writerData.banner_image && (
                            <div className="text-center">
                              <Upload className="w-12 h-12 text-white/70 mx-auto mb-2" />
                              <p className="text-white/70 text-sm">Click below to add banner image</p>
                            </div>
                          )}
                        </div>
                      </div>
                      
                      <div className="flex items-center space-x-3">
                        <input
                          type="file"
                          id="banner-image-settings"
                          accept="image/*"
                          onChange={handleHeaderImageUpload}
                          className="hidden"
                        />
                        <Button
                          variant="outline"
                          onClick={() => document.getElementById('banner-image-settings').click()}
                          className="border-white/20 text-white hover:bg-white/10"
                          disabled={uploadingHeader}
                        >
                          {uploadingHeader ? (
                            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                          ) : (
                            <Upload className="w-4 h-4 mr-2" />
                          )}
                          {writerData.banner_image ? 'Change Banner' : 'Add Banner Image'}
                        </Button>
                        
                        {writerData.banner_image && (
                          <Button
                            variant="ghost"
                            onClick={() => setWriterData(prev => ({ ...prev, banner_image: null }))}
                            className="text-red-400 hover:text-red-300 hover:bg-red-400/10"
                          >
                            Remove Banner
                          </Button>
                        )}
                      </div>
                      
                      <p className="text-xs text-gray-400">
                        Recommended: 1200x400px, JPG or PNG. This appears at the top of your reader-facing profile.
                      </p>
                    </div>
                  </div>

                  {/* Background Image */}
                  <div>
                    <Label className="text-white mb-3 block">Profile Background Image (Optional)</Label>
                    <div className="space-y-4">
                      <div 
                        className="h-32 rounded-lg bg-cover bg-center border-2 border-dashed border-gray-600 relative overflow-hidden"
                        style={{ 
                          backgroundImage: writerData.background_image 
                            ? `url(${writerData.background_image})` 
                            : 'none',
                          backgroundColor: writerData.background_image ? 'transparent' : '#1f2937'
                        }}
                      >
                        <div className="absolute inset-0 bg-black/40 flex items-center justify-center">
                          {!writerData.background_image ? (
                            <div className="text-center">
                              <Palette className="w-8 h-8 text-gray-400 mx-auto mb-1" />
                              <p className="text-gray-400 text-xs">Optional background image</p>
                            </div>
                          ) : (
                            <div className="text-center">
                              <p className="text-white text-xs bg-black/50 px-2 py-1 rounded">
                                Background Preview
                              </p>
                            </div>
                          )}
                        </div>
                      </div>
                      
                      <div className="flex items-center space-x-3">
                        <input
                          type="file"
                          id="background-image-settings"
                          accept="image/*"
                          onChange={(e) => {
                            const file = e.target.files[0];
                            if (file) {
                              const url = URL.createObjectURL(file);
                              setWriterData(prev => ({ ...prev, background_image: url }));
                              toast({
                                title: "Background Updated!",
                                description: "Your profile background has been updated.",
                              });
                            }
                          }}
                          className="hidden"
                        />
                        <Button
                          variant="outline"
                          onClick={() => document.getElementById('background-image-settings').click()}
                          className="border-white/20 text-white hover:bg-white/10"
                        >
                          <Palette className="w-4 h-4 mr-2" />
                          {writerData.background_image ? 'Change Background' : 'Add Background'}
                        </Button>
                        
                        {writerData.background_image && (
                          <Button
                            variant="ghost"
                            onClick={() => setWriterData(prev => ({ ...prev, background_image: null }))}
                            className="text-red-400 hover:text-red-300 hover:bg-red-400/10"
                          >
                            Remove Background
                          </Button>
                        )}
                      </div>
                      
                      <p className="text-xs text-gray-400">
                        Optional: Subtle background image that appears behind your profile content. Recommended: 1920x1080px, low opacity images work best.
                      </p>
                    </div>
                  </div>

                  {/* Preview Button */}
                  <div className="bg-blue-600/10 border border-blue-600/20 rounded-lg p-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-white font-semibold mb-1">Preview Your Changes</h4>
                        <p className="text-gray-400 text-sm">See how your profile will look to readers</p>
                      </div>
                      <Button 
                        variant="outline"
                        onClick={() => setViewMode('reader')}
                        className="border-blue-400 text-blue-400 hover:bg-blue-400/10"
                      >
                        Preview Profile
                      </Button>
                    </div>
                  </div>

                  <div className="flex justify-end pt-4">
                    <Button className="bg-purple-600 hover:bg-purple-700 text-white">
                      Save Appearance Changes
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            {/* Subscription Tiers Tab */}
            <TabsContent value="tiers" className="space-y-6">
              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardHeader>
                  <div className="flex justify-between items-start">
                    <div>
                      <CardTitle className="text-white">Subscription Tiers</CardTitle>
                      <CardDescription className="text-gray-400">
                        Manage your membership levels and pricing
                      </CardDescription>
                    </div>
                    <Button className="bg-green-600 hover:bg-green-700 text-white">
                      <PenTool className="w-4 h-4 mr-2" />
                      Add New Tier
                    </Button>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  {subscriptionTiers.map((tier, index) => (
                    <div key={tier.id} className="p-4 bg-gray-800/30 rounded-lg">
                      <div className="flex justify-between items-start mb-2">
                        <div className="flex-1">
                          <h4 className="text-white font-semibold text-lg">{tier.name}</h4>
                          <p className="text-gray-400 text-sm mb-2">{tier.description}</p>
                          <div className="flex items-center space-x-4 text-sm">
                            <span className="text-green-400 font-semibold text-lg">${tier.price}/month</span>
                            <span className="text-gray-400">{tier.subscriber_count || 0} members</span>
                            <span className="text-blue-400">
                              ${((tier.subscriber_count || 0) * tier.price).toFixed(0)}/month revenue
                            </span>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          <Button variant="ghost" size="sm" className="text-gray-400 hover:text-white">
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button variant="ghost" size="sm" className="text-red-400 hover:text-red-300">
                            <span className="text-lg">×</span>
                          </Button>
                        </div>
                      </div>
                      
                      {/* Benefits */}
                      <div>
                        <h5 className="text-gray-300 text-sm font-medium mb-1">Benefits:</h5>
                        <ul className="text-gray-400 text-sm space-y-1">
                          {tier.benefits.map((benefit, i) => (
                            <li key={i} className="flex items-center">
                              <span className="text-green-400 mr-2">•</span>
                              {benefit}
                            </li>
                          ))}
                        </ul>
                      </div>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </TabsContent>

            {/* Notifications Tab */}
            <TabsContent value="notifications" className="space-y-6">
              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white">Notification Settings</CardTitle>
                  <CardDescription className="text-gray-400">
                    Control how and when you receive notifications
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Email Notifications */}
                  <div className="space-y-4">
                    <h4 className="text-white font-semibold">Email Notifications</h4>
                    
                    {[
                      { label: 'New members', description: 'When someone subscribes to your content' },
                      { label: 'Payment received', description: 'When you receive a payment or tip' },
                      { label: 'Comments on posts', description: 'When readers comment on your posts' },
                      { label: 'Monthly earnings report', description: 'Monthly summary of your earnings' },
                      { label: 'Platform updates', description: 'Important updates from Queens Mountain' }
                    ].map((notification, index) => (
                      <div key={index} className="flex items-center justify-between py-2">
                        <div>
                          <p className="text-white text-sm font-medium">{notification.label}</p>
                          <p className="text-gray-400 text-xs">{notification.description}</p>
                        </div>
                        <input
                          type="checkbox"
                          defaultChecked
                          className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                        />
                      </div>
                    ))}
                  </div>

                  <div className="flex justify-end pt-4">
                    <Button className="bg-blue-600 hover:bg-blue-700 text-white">
                      Save Notification Settings
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      );
    }
  }

  // Creator Onboarding Flow - Patreon Style
  function CreatorOnboardingFlow() {
    const [currentStep, setCurrentStep] = useState(1);
    const [onboardingData, setOnboardingData] = useState({
      // Step 1: Basic Profile
      display_name: '',
      tagline: '',
      category: '',
      profile_image: null,
      banner_image: null,
      
      // Step 2: About & Links
      about: '',
      creation_process: '',
      social_links: {
        website: '',
        twitter: '',
        instagram: '',
        discord: '',
        youtube: ''
      },
      
      // Step 3: Membership Tiers
      tiers: [
        {
          id: 1,
          name: '',
          price: '',
          description: '',
          benefits: ['']
        }
      ],
      
      // Step 4: Content & Goals
      content_examples: [],
      monthly_goal: '',
      goal_description: ''
    });

    const totalSteps = 4;

    const handleNext = () => {
      if (currentStep < totalSteps) {
        setCurrentStep(currentStep + 1);
      }
    };

    const handlePrevious = () => {
      if (currentStep > 1) {
        setCurrentStep(currentStep - 1);
      }
    };

    const handleInputChange = (field, value) => {
      setOnboardingData(prev => ({
        ...prev,
        [field]: value
      }));
    };

    const handleSocialLinkChange = (platform, value) => {
      setOnboardingData(prev => ({
        ...prev,
        social_links: {
          ...prev.social_links,
          [platform]: value
        }
      }));
    };

    const addTier = () => {
      setOnboardingData(prev => ({
        ...prev,
        tiers: [...prev.tiers, {
          id: prev.tiers.length + 1,
          name: '',
          price: '',
          description: '',
          benefits: ['']
        }]
      }));
    };

    const updateTier = (index, field, value) => {
      setOnboardingData(prev => ({
        ...prev,
        tiers: prev.tiers.map((tier, i) => 
          i === index ? { ...tier, [field]: value } : tier
        )
      }));
    };

    const addBenefit = (tierIndex) => {
      setOnboardingData(prev => ({
        ...prev,
        tiers: prev.tiers.map((tier, i) => 
          i === tierIndex 
            ? { ...tier, benefits: [...tier.benefits, ''] }
            : tier
        )
      }));
    };

    const updateBenefit = (tierIndex, benefitIndex, value) => {
      setOnboardingData(prev => ({
        ...prev,
        tiers: prev.tiers.map((tier, i) => 
          i === tierIndex 
            ? { 
                ...tier, 
                benefits: tier.benefits.map((benefit, j) => 
                  j === benefitIndex ? value : benefit
                )
              }
            : tier
        )
      }));
    };

    return (
      <div className="max-w-4xl mx-auto px-6 py-8">
        {/* Progress Header */}
        <div className="mb-12">
          <div className="flex items-center justify-between mb-6">
            <h1 className="text-3xl font-bold text-white">Set up your Queens Mountain page</h1>
            <div className="text-sm text-gray-400">
              Step {currentStep} of {totalSteps}
            </div>
          </div>
          
          {/* Progress Bar */}
          <div className="w-full bg-gray-700 rounded-full h-2 mb-2">
            <div 
              className="bg-orange-500 h-2 rounded-full transition-all duration-300"
              style={{ width: `${(currentStep / totalSteps) * 100}%` }}
            ></div>
          </div>
          <div className="text-xs text-gray-400 mb-8">
            Complete your profile to start receiving support from readers
          </div>
        </div>

        {/* Step Content */}
        <div className="bg-gray-900/50 rounded-2xl p-8 mb-8">
          {currentStep === 1 && <Step1BasicProfile />}
          {currentStep === 2 && <Step2AboutAndLinks />}
          {currentStep === 3 && <Step3MembershipTiers />}
          {currentStep === 4 && <Step4Preview />}
        </div>

        {/* Navigation */}
        <div className="flex justify-between">
          <Button
            variant="outline"
            onClick={handlePrevious}
            disabled={currentStep === 1}
            className="border-white/20 text-white hover:bg-white/10 disabled:opacity-50"
          >
            Previous
          </Button>
          
          <Button
            onClick={currentStep === totalSteps ? handleLaunchPage : handleNext}
            className="bg-orange-500 hover:bg-orange-600 text-white px-8"
          >
            {currentStep === totalSteps ? 'Launch my page' : 'Continue'}
          </Button>
        </div>
      </div>
    );

    // Step 1: Basic Profile Setup
    function Step1BasicProfile() {
      return (
        <div className="space-y-8">
          <div className="text-center mb-8">
            <h2 className="text-2xl font-bold text-white mb-2">Let's start with the basics</h2>
            <p className="text-gray-400">Your profile represents your creative work and helps readers discover you</p>
          </div>

          <div className="grid md:grid-cols-2 gap-8">
            {/* Left Column */}
            <div className="space-y-6">
              {/* Profile Image */}
              <div>
                <label className="text-white font-medium block mb-3">Profile photo</label>
                <div className="flex items-center space-x-4">
                  <div className="w-20 h-20 bg-gray-700 rounded-full flex items-center justify-center overflow-hidden">
                    {onboardingData.profile_image ? (
                      <img src={onboardingData.profile_image} alt="Profile" className="w-full h-full object-cover" />
                    ) : (
                      <Upload className="w-8 h-8 text-gray-400" />
                    )}
                  </div>
                  <div>
                    <input
                      type="file"
                      id="profile-image"
                      accept="image/*"
                      className="hidden"
                      onChange={(e) => {
                        const file = e.target.files[0];
                        if (file) {
                          const url = URL.createObjectURL(file);
                          handleInputChange('profile_image', url);
                        }
                      }}
                    />
                    <Button
                      variant="outline"
                      onClick={() => document.getElementById('profile-image').click()}
                      className="border-white/20 text-white hover:bg-white/10"
                    >
                      Choose image
                    </Button>
                    <p className="text-xs text-gray-400 mt-1">JPG, GIF or PNG. 400x400px recommended.</p>
                  </div>
                </div>
              </div>

              {/* Display Name */}
              <div>
                <label className="text-white font-medium block mb-3">
                  Page name <span className="text-red-400">*</span>
                </label>
                <Input
                  value={onboardingData.display_name}
                  onChange={(e) => handleInputChange('display_name', e.target.value)}
                  placeholder="e.g. Alex Writer"
                  className="bg-gray-800 border-gray-600 text-white"
                />
                <p className="text-xs text-gray-400 mt-1">This will be visible to everyone</p>
              </div>

              {/* Category */}
              <div>
                <label className="text-white font-medium block mb-3">
                  What do you create? <span className="text-red-400">*</span>
                </label>
                <Select 
                  value={onboardingData.category} 
                  onValueChange={(value) => handleInputChange('category', value)}
                >
                  <SelectTrigger className="bg-gray-800 border-gray-600 text-white">
                    <SelectValue placeholder="Choose a category" />
                  </SelectTrigger>
                  <SelectContent className="bg-gray-800 border-gray-600">
                    <SelectItem value="fiction" className="text-white">Fiction & Literature</SelectItem>
                    <SelectItem value="fantasy" className="text-white">Fantasy & Sci-Fi</SelectItem>
                    <SelectItem value="romance" className="text-white">Romance</SelectItem>
                    <SelectItem value="mystery" className="text-white">Mystery & Thriller</SelectItem>
                    <SelectItem value="horror" className="text-white">Horror</SelectItem>
                    <SelectItem value="poetry" className="text-white">Poetry</SelectItem>
                    <SelectItem value="nonfiction" className="text-white">Non-fiction</SelectItem>
                    <SelectItem value="other" className="text-white">Other</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Right Column */}
            <div className="space-y-6">
              {/* Banner Image */}
              <div>
                <label className="text-white font-medium block mb-3">Cover photo (optional)</label>
                <div className="border-2 border-dashed border-gray-600 rounded-lg p-8 text-center">
                  {onboardingData.banner_image ? (
                    <img src={onboardingData.banner_image} alt="Banner" className="w-full h-32 object-cover rounded-lg" />
                  ) : (
                    <div>
                      <Upload className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                      <p className="text-gray-400 mb-2">Add a cover photo</p>
                      <p className="text-xs text-gray-500">1600x400px recommended</p>
                    </div>
                  )}
                  <input
                    type="file"
                    id="banner-image"
                    accept="image/*"
                    className="hidden"
                    onChange={(e) => {
                      const file = e.target.files[0];
                      if (file) {
                        const url = URL.createObjectURL(file);
                        handleInputChange('banner_image', url);
                      }
                    }}
                  />
                  <Button
                    variant="outline"
                    onClick={() => document.getElementById('banner-image').click()}
                    className="border-white/20 text-white hover:bg-white/10 mt-3"
                  >
                    {onboardingData.banner_image ? 'Change image' : 'Choose image'}
                  </Button>
                </div>
              </div>

              {/* Tagline */}
              <div>
                <label className="text-white font-medium block mb-3">
                  Tagline <span className="text-red-400">*</span>
                </label>
                <Textarea
                  value={onboardingData.tagline}
                  onChange={(e) => handleInputChange('tagline', e.target.value)}
                  placeholder="e.g. Creating epic fantasy adventures that transport you to magical realms"
                  className="bg-gray-800 border-gray-600 text-white resize-none h-24"
                  maxLength={180}
                />
                <p className="text-xs text-gray-400 mt-1">
                  {onboardingData.tagline.length}/180 characters
                </p>
              </div>
            </div>
          </div>
        </div>
      );
    }

    // Step 2: About and Social Links
    function Step2AboutAndLinks() {
      return (
        <div className="space-y-8">
          <div className="text-center mb-8">
            <h2 className="text-2xl font-bold text-white mb-2">Tell your story</h2>
            <p className="text-gray-400">Help readers understand what you create and why they should support you</p>
          </div>

          <div className="space-y-6">
            {/* About Section */}
            <div>
              <label className="text-white font-medium block mb-3">
                About your work <span className="text-red-400">*</span>
              </label>
              <Textarea
                value={onboardingData.about}
                onChange={(e) => handleInputChange('about', e.target.value)}
                placeholder="Welcome to my creative world! I've been writing fantasy novels for over 5 years, and I love creating stories that transport readers to magical realms filled with adventure, mystery, and heart..."
                className="bg-gray-800 border-gray-600 text-white resize-none h-32"
                maxLength={2000}
              />
              <p className="text-xs text-gray-400 mt-1">
                Describe what you create, your style, and what supporters can expect. {onboardingData.about.length}/2000 characters
              </p>
            </div>

            {/* Creation Process */}
            <div>
              <label className="text-white font-medium block mb-3">
                Your creation process (optional)
              </label>
              <Textarea
                value={onboardingData.creation_process}
                onChange={(e) => handleInputChange('creation_process', e.target.value)}
                placeholder="I publish new chapters weekly, and I always love hearing from my readers. Your support means everything to me and helps me continue creating the stories you love!"
                className="bg-gray-800 border-gray-600 text-white resize-none h-24"
                maxLength={1000}
              />
              <p className="text-xs text-gray-400 mt-1">
                How often do you create? What's your workflow? {onboardingData.creation_process.length}/1000 characters
              </p>
            </div>

            {/* Social Links */}
            <div>
              <label className="text-white font-medium block mb-4">Connect your social media (optional)</label>
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-gray-400 block mb-1">Website</label>
                  <Input
                    value={onboardingData.social_links.website}
                    onChange={(e) => handleSocialLinkChange('website', e.target.value)}
                    placeholder="https://yourwebsite.com"
                    className="bg-gray-800 border-gray-600 text-white"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-400 block mb-1">Twitter</label>
                  <Input
                    value={onboardingData.social_links.twitter}
                    onChange={(e) => handleSocialLinkChange('twitter', e.target.value)}
                    placeholder="@yourusername"
                    className="bg-gray-800 border-gray-600 text-white"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-400 block mb-1">Instagram</label>
                  <Input
                    value={onboardingData.social_links.instagram}
                    onChange={(e) => handleSocialLinkChange('instagram', e.target.value)}
                    placeholder="@yourusername"
                    className="bg-gray-800 border-gray-600 text-white"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-400 block mb-1">Discord</label>
                  <Input
                    value={onboardingData.social_links.discord}
                    onChange={(e) => handleSocialLinkChange('discord', e.target.value)}
                    placeholder="Username#1234"
                    className="bg-gray-800 border-gray-600 text-white"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      );
    }

    // Step 3: Membership Tiers
    function Step3MembershipTiers() {
      return (
        <div className="space-y-8">
          <div className="text-center mb-8">
            <h2 className="text-2xl font-bold text-white mb-2">Create your membership tiers</h2>
            <p className="text-gray-400">Set up different support levels with unique benefits for your readers</p>
          </div>

          <div className="space-y-6">
            {onboardingData.tiers.map((tier, index) => (
              <Card key={tier.id} className="bg-gray-800/50 border-gray-600">
                <CardContent className="p-6">
                  <div className="flex justify-between items-start mb-4">
                    <h3 className="text-white font-bold">Tier {index + 1}</h3>
                    {index > 0 && (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setOnboardingData(prev => ({
                            ...prev,
                            tiers: prev.tiers.filter((_, i) => i !== index)
                          }));
                        }}
                        className="text-red-400 hover:text-red-300"
                      >
                        Remove
                      </Button>
                    )}
                  </div>

                  <div className="grid md:grid-cols-3 gap-4 mb-4">
                    <div>
                      <label className="text-sm text-gray-400 block mb-1">Tier name <span className="text-red-400">*</span></label>
                      <Input
                        value={tier.name}
                        onChange={(e) => updateTier(index, 'name', e.target.value)}
                        placeholder="e.g. Supporter"
                        className="bg-gray-700 border-gray-600 text-white"
                      />
                    </div>
                    <div>
                      <label className="text-sm text-gray-400 block mb-1">Price (USD) <span className="text-red-400">*</span></label>
                      <Input
                        type="number"
                        value={tier.price}
                        onChange={(e) => updateTier(index, 'price', e.target.value)}
                        placeholder="3"
                        className="bg-gray-700 border-gray-600 text-white"
                      />
                    </div>
                    <div>
                      <label className="text-sm text-gray-400 block mb-1">Description</label>
                      <Input
                        value={tier.description}
                        onChange={(e) => updateTier(index, 'description', e.target.value)}
                        placeholder="Support my writing journey"
                        className="bg-gray-700 border-gray-600 text-white"
                      />
                    </div>
                  </div>

                  {/* Benefits */}
                  <div>
                    <label className="text-sm text-gray-400 block mb-2">Benefits <span className="text-red-400">*</span></label>
                    <div className="space-y-2">
                      {tier.benefits.map((benefit, benefitIndex) => (
                        <div key={benefitIndex} className="flex items-center space-x-2">
                          <Input
                            value={benefit}
                            onChange={(e) => updateBenefit(index, benefitIndex, e.target.value)}
                            placeholder="e.g. Early access to chapters"
                            className="bg-gray-700 border-gray-600 text-white flex-1"
                          />
                          {tier.benefits.length > 1 && (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setOnboardingData(prev => ({
                                  ...prev,
                                  tiers: prev.tiers.map((t, i) => 
                                    i === index 
                                      ? { ...t, benefits: t.benefits.filter((_, j) => j !== benefitIndex) }
                                      : t
                                  )
                                }));
                              }}
                              className="text-gray-400 hover:text-red-400"
                            >
                              ✕
                            </Button>
                          )}
                        </div>
                      ))}
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => addBenefit(index)}
                        className="border-gray-600 text-gray-400 hover:text-white hover:bg-gray-700"
                      >
                        + Add benefit
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}

            <div className="text-center">
              <Button
                variant="outline"
                onClick={addTier}
                className="border-orange-500 text-orange-500 hover:bg-orange-500 hover:text-white"
              >
                + Add another tier
              </Button>
            </div>
          </div>
        </div>
      );
    }

    // Step 4: Preview and Launch
    function Step4Preview() {
      return (
        <div className="space-y-8">
          <div className="text-center mb-8">
            <h2 className="text-2xl font-bold text-white mb-2">Preview your page</h2>
            <p className="text-gray-400">Here's how your Queens Mountain page will look to readers</p>
          </div>

          {/* Preview Card */}
          <Card className="bg-gray-800 border-gray-600 overflow-hidden">
            {/* Banner Preview */}
            {onboardingData.banner_image && (
              <div 
                className="h-48 bg-cover bg-center"
                style={{ backgroundImage: `url(${onboardingData.banner_image})` }}
              >
                <div className="absolute inset-0 bg-black/30"></div>
              </div>
            )}
            
            <CardContent className="p-6">
              <div className="flex items-start space-x-4 mb-6">
                {/* Profile Image Preview */}
                <div className="w-20 h-20 bg-gray-700 rounded-full overflow-hidden flex-shrink-0">
                  {onboardingData.profile_image ? (
                    <img src={onboardingData.profile_image} alt="Profile" className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full bg-gray-600 flex items-center justify-center">
                      <Upload className="w-6 h-6 text-gray-400" />
                    </div>
                  )}
                </div>
                
                <div className="flex-1">
                  <h3 className="text-2xl font-bold text-white mb-1">
                    {onboardingData.display_name || 'Your Name'}
                  </h3>
                  <p className="text-gray-300 mb-2">
                    {onboardingData.tagline || 'Your tagline will appear here'}
                  </p>
                  <span className="inline-block bg-blue-600 text-white text-xs px-2 py-1 rounded">
                    {onboardingData.category || 'Category'}
                  </span>
                </div>

                {/* Mock Subscribe Button */}
                <Button className="bg-orange-500 hover:bg-orange-600 text-white">
                  Subscribe
                </Button>
              </div>

              {/* About Preview */}
              <div className="mb-6">
                <h4 className="text-white font-semibold mb-2">About</h4>
                <p className="text-gray-300 text-sm">
                  {onboardingData.about || 'Your about section will appear here...'}
                </p>
              </div>

              {/* Tiers Preview */}
              {onboardingData.tiers.length > 0 && (
                <div>
                  <h4 className="text-white font-semibold mb-4">Membership Tiers</h4>
                  <div className="grid gap-4">
                    {onboardingData.tiers.map((tier, index) => (
                      <div key={index} className="bg-gray-700/50 rounded-lg p-4">
                        <div className="flex justify-between items-start mb-2">
                          <h5 className="text-white font-medium">{tier.name || `Tier ${index + 1}`}</h5>
                          <span className="text-white font-bold">${tier.price || '0'}/month</span>
                        </div>
                        {tier.description && (
                          <p className="text-gray-300 text-sm mb-2">{tier.description}</p>
                        )}
                        <ul className="text-gray-300 text-sm space-y-1">
                          {tier.benefits.filter(b => b.trim()).map((benefit, i) => (
                            <li key={i} className="flex items-center">
                              <span className="text-green-400 mr-2">•</span>
                              {benefit}
                            </li>
                          ))}
                        </ul>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          <div className="text-center">
            <p className="text-gray-400 mb-4">
              Ready to launch? You can always edit your page later.
            </p>
          </div>
        </div>
      );
    }

    function handleLaunchPage() {
      // TODO: Save all onboarding data to backend
      toast({
        title: "Page launched successfully!",
        description: "Your Queens Mountain page is now live and ready to accept supporters.",
      });
      
      // Redirect or update view to show completed profile
      setViewMode('reader');
    }
  }
};




// Reader Profile Component (Original)
const ReaderProfile = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses, updatePanelOpacity } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { toast } = useToast();
  const [profileData, setProfileData] = useState({
    name: '',
    email: '',
    bio: '',
    user_type: 'reader',
    interests: [],
    genre_preferences: [],
    favorite_books: [],
    social_links: {
      discord: '',
      twitter: '',
      instagram: '',
      facebook: '',
      website: ''
    },
    profile_image: '',
    header_image: '', // Add header image
    header_position: 'center', // Add header positioning
    background_image: '', // Add background image
    background_position: 'center', // Add background positioning
    location: '',
    age: ''
  });
  const [isEditing, setIsEditing] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [hiddenStories, setHiddenStories] = useState(new Set());
  
  // Social features state
  const [showFriendRequests, setShowFriendRequests] = useState(false);
  const [showMessaging, setShowMessaging] = useState(false);

  const handleImageUpload = async (file, imageType) => {
    if (!file) return;
    
    setUploadingImage(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await axios.post(`${API}/upload/image`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data && response.data.url) {
        const imageUrl = `${API}${response.data.url}`;
        setProfileData(prev => ({ ...prev, [imageType]: imageUrl }));
        
        toast({
          title: "Image Uploaded",
          description: `${imageType.replace('_', ' ')} has been updated successfully.`,
        });
      }
    } catch (error) {
      console.error('Image upload error:', error);
      toast({
        title: "Upload Failed", 
        description: "Failed to upload image. Please try again.",
        variant: "destructive",
      });
    } finally {
      setUploadingImage(false);
    }
  };

  return (
    <div 
      className="min-h-screen"
      style={{
        backgroundImage: profileData.background_image 
          ? `url(${profileData.background_image})` 
          : 'linear-gradient(45deg, #1a1a2e, #16213e, #0f3460)',
        backgroundSize: 'cover',
        backgroundPosition: profileData.background_position || 'center',
        backgroundAttachment: 'fixed'
      }}
    >
      {/* Background Overlay for readability */}
      <div className="absolute inset-0 bg-black/20"></div>
      
      <div className="relative z-10">
        {/* Navigation Header */}
        <nav className="bg-black/90 backdrop-blur-md border-b border-white/10 sticky top-0 z-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between h-16">
              <div className="flex items-center space-x-8">
                <h1 
                  className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" 
                  onClick={() => navigate('/')}
                >
                  Queens Mountain
                </h1>
              </div>
              <div className="flex items-center space-x-4">
                {user && (
                  <div className="flex items-center space-x-4">
                    <span 
                      onClick={() => navigate('/profile')}
                      className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                    >
                      {user.name}
                    </span>
                    <Button
                      variant="ghost"
                      onClick={logout}
                      className="text-gray-300 hover:text-white hover:bg-white/10"
                    >
                      <LogOut className="w-4 h-4" />
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </nav>

        <main className="min-h-screen">
        {/* Header with Custom Background */}
        <div 
          className="bg-gradient-to-r from-gray-900 to-black border-b border-white/10 relative overflow-hidden"
          style={{
            backgroundImage: profileData.header_image ? `url(${profileData.header_image})` : 'none',
            backgroundSize: 'cover',
            backgroundPosition: profileData.header_position || 'center'
          }}
        >
          {/* Header Image Overlay */}
          {profileData.header_image && (
            <div className="absolute inset-0 bg-black/40"></div>
          )}
          
          <div className="max-w-7xl mx-auto px-6 py-8 relative z-10">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center space-x-4">
                <img
                  src={profileData.profile_image || user?.profile_image || 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face'}
                  alt={user?.name || 'Reader'}
                  className="w-16 h-16 rounded-full object-cover border-4 border-white/20 shadow-lg"
                />
                <div>
                  <h1 className="text-3xl font-bold text-white drop-shadow-lg">
                    {profileData.name || user?.name || 'Reader Profile'}
                  </h1>
                  <p className="text-gray-200 drop-shadow">
                    {profileData.bio || 'Explore amazing stories and connect with writers'}
                  </p>
                </div>
              </div>
              
              <div className="flex items-center space-x-3">
                <NotificationBell />
                <Button
                  variant="outline"
                  onClick={() => setShowFriendRequests(true)}
                  className="border-white/20 text-white hover:bg-white/10"
                >
                  <Users className="w-4 h-4 mr-2" />
                  Friends
                </Button>
                <Button
                  variant="outline" 
                  onClick={() => setShowMessaging(true)}
                  className="border-white/20 text-white hover:bg-white/10"
                >
                  <MessageSquare className="w-4 h-4 mr-2" />
                  Messages
                </Button>
                <Button 
                  variant="outline"
                  onClick={() => setIsEditing(!isEditing)}
                  className="border-blue-600 text-blue-400 hover:bg-blue-600/20"
                >
                  <Edit className="w-4 h-4 mr-2" />
                  {isEditing ? 'Cancel Edit' : 'Edit Profile'}
                </Button>
                <Button variant="outline" onClick={logout} className="border-red-600 text-red-400 hover:bg-red-600/20">
                  <LogOut className="w-4 h-4 mr-2" />
                  Logout
                </Button>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="max-w-7xl mx-auto px-6 py-8">
          <div className="grid lg:grid-cols-3 gap-8">
            
            {/* Left Sidebar - Bookshelf */}
            <div className="space-y-6">
              <Card className={`${getPanelClasses('leftPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white flex items-center">
                    <BookOpen className="w-5 h-5 mr-2" />
                    My Bookshelf
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-3">
                    {[1, 2, 3, 4].map((book) => (
                      <div key={book} className="bg-gray-700/50 rounded-lg p-3 text-center">
                        <div className="w-full h-24 bg-gray-600 rounded mb-2"></div>
                        <p className="text-white text-xs">Book {book}</p>
                        <p className="text-gray-400 text-xs">Progress: {book * 25}%</p>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* Online Friends */}
              <Card className={`${getPanelClasses('leftPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white flex items-center">
                    <Users className="w-5 h-5 mr-2" />
                    Online Friends
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    {['Sarah M.', 'Jake D.', 'Emma L.'].map((friend, index) => (
                      <div key={index} className="flex items-center space-x-2">
                        <OnlineStatus isOnline={index < 2} />
                        <ClickableUsername 
                          userId={`friend-${index}`}
                          username={friend}
                          className="text-white text-sm"
                        />
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Center Content - Thoughts & Activity */}
            <div className="lg:col-span-2 space-y-6">
              {/* Thoughts Section */}
              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white flex items-center">
                    <MessageSquare className="w-5 h-5 mr-2" />
                    Thoughts
                  </CardTitle>
                  <CardDescription className="text-gray-400">
                    Share your thoughts about stories and connect with the community
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Post New Thought */}
                  <div className="bg-gray-800/30 rounded-lg p-4">
                    <Textarea
                      placeholder="What's on your mind about the stories you're reading?"
                      className="bg-gray-700/50 border-gray-600 text-white mb-3 min-h-[100px]"
                    />
                    <div className="flex justify-between items-center">
                      <div className="flex items-center space-x-2 text-sm text-gray-400">
                        <span>📖 Currently reading: "The Dragon's Quest"</span>
                      </div>
                      <Button size="sm" className="bg-blue-600 hover:bg-blue-700 text-white">
                        <Send className="w-4 h-4 mr-2" />
                        Share Thought
                      </Button>
                    </div>
                  </div>

                  {/* Recent Thoughts Feed */}
                  <div className="space-y-4">
                    <h4 className="text-white font-semibold">Your Recent Thoughts</h4>
                    
                    {[
                      {
                        id: 1,
                        content: "Just finished Chapter 15 of 'Chronicles of Aethermoor' and WOW! The dragon awakening scene gave me chills. Alex Writer really knows how to build suspense! 🐉✨",
                        story: "Chronicles of Aethermoor",
                        time: "2 hours ago",
                        likes: 12,
                        comments: 3
                      },
                      {
                        id: 2,
                        content: "Been thinking about the character development in 'Magic Academy'. The way Lyra's powers evolve throughout the story is so well written. Can't wait for the next chapter!",
                        story: "Magic Academy", 
                        time: "1 day ago",
                        likes: 8,
                        comments: 2
                      },
                      {
                        id: 3,
                        content: "Does anyone else think the plot twist in 'Shadow Chronicles' was absolutely mind-blowing? I did NOT see that coming! 🤯",
                        story: "Shadow Chronicles",
                        time: "3 days ago", 
                        likes: 15,
                        comments: 7
                      }
                    ].map((thought) => (
                      <div key={thought.id} className="bg-gray-800/30 rounded-lg p-4">
                        <div className="flex items-start space-x-3">
                          <img
                            src={user?.profile_image || 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=40&h=40&fit=crop&crop=face'}
                            alt={user?.name}
                            className="w-10 h-10 rounded-full object-cover"
                          />
                          <div className="flex-1">
                            <div className="flex items-center space-x-2 mb-2">
                              <span className="text-white font-medium">{user?.name || 'Jane Reader'}</span>
                              <span className="text-gray-400 text-sm">•</span>
                              <span className="text-gray-400 text-sm">{thought.time}</span>
                              <span className="text-gray-400 text-sm">•</span>
                              <span className="text-blue-400 text-sm">#{thought.story}</span>
                            </div>
                            
                            <p className="text-gray-300 mb-3">{thought.content}</p>
                            
                            <div className="flex items-center space-x-4">
                              <button className="flex items-center space-x-1 text-gray-400 hover:text-red-400 transition-colors">
                                <Star className="w-4 h-4" />
                                <span className="text-sm">{thought.likes}</span>
                              </button>
                              <button className="flex items-center space-x-1 text-gray-400 hover:text-blue-400 transition-colors">
                                <MessageSquare className="w-4 h-4" />
                                <span className="text-sm">{thought.comments}</span>
                              </button>
                              <button className="text-gray-400 hover:text-white transition-colors text-sm">
                                Reply
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* Recent Activity */}
              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white">Recent Activity</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="bg-gray-800/30 rounded-lg p-4">
                    <p className="text-white text-sm">Started reading "The Dragon's Quest" by Alex Writer</p>
                    <p className="text-gray-400 text-xs mt-1">2 hours ago</p>
                  </div>
                  <div className="bg-gray-800/30 rounded-lg p-4">
                    <p className="text-white text-sm">Completed "Magic Academy" - left a 5-star review</p>
                    <p className="text-gray-400 text-xs mt-1">1 day ago</p>
                  </div>
                  <div className="bg-gray-800/30 rounded-lg p-4">
                    <p className="text-white text-sm">Became friends with Sarah M.</p>
                    <p className="text-gray-400 text-xs mt-1">3 days ago</p>
                  </div>
                </CardContent>
              </Card>

              {/* Quick Actions */}
              <div className="grid md:grid-cols-2 gap-6">
                <Card className={`${getPanelClasses('mainPanel')}`}>
                  <CardHeader>
                    <CardTitle className="text-white">Discover</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <Button 
                      className="w-full bg-blue-600 hover:bg-blue-700 text-white justify-start"
                      onClick={() => navigate('/genres')}
                    >
                      <Search className="w-4 h-4 mr-2" />
                      Browse Stories
                    </Button>
                    <Button 
                      variant="outline" 
                      className="w-full border-white/20 text-white hover:bg-white/10 justify-start"
                      onClick={() => navigate('/forum')}
                    >
                      <MessageCircle className="w-4 h-4 mr-2" />
                      Community Forum
                    </Button>
                    <Button 
                      variant="outline" 
                      className="w-full border-white/20 text-white hover:bg-white/10 justify-start"
                      onClick={() => navigate('/reviews')}
                    >
                      <Star className="w-4 h-4 mr-2" />
                      Top Reviews
                    </Button>
                  </CardContent>
                </Card>

                <Card className={`${getPanelClasses('mainPanel')}`}>
                  <CardHeader>
                    <CardTitle className="text-white">Reading Stats</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-gray-400">Books Read:</span>
                      <span className="text-white font-semibold">47</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-400">Reviews Given:</span>
                      <span className="text-white font-semibold">23</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-400">Authors Supported:</span>
                      <span className="text-white font-semibold">12</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-400">Reading Streak:</span>
                      <span className="text-green-400 font-semibold">15 days</span>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </div>
        </div>

        {/* Edit Profile Modal */}
        <Dialog open={isEditing} onOpenChange={setIsEditing}>
          <DialogContent className="sm:max-w-md bg-black border-white/20 text-white max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="text-white">Edit Profile</DialogTitle>
              <DialogDescription className="text-gray-400">
                Update your profile information and preferences
              </DialogDescription>
            </DialogHeader>
            
            <div className="space-y-4">
              {/* Background Image Upload */}
              <div>
                <Label className="text-white mb-3 block">Background Image</Label>
                <div className="flex items-center space-x-4">
                  <div className="w-32 h-20 bg-gray-700 rounded-lg flex items-center justify-center overflow-hidden">
                    {profileData.background_image ? (
                      <img 
                        src={profileData.background_image} 
                        alt="Background Preview" 
                        className="w-full h-full object-cover"
                        style={{ objectPosition: profileData.background_position || 'center' }}
                      />
                    ) : (
                      <Upload className="w-6 h-6 text-gray-400" />
                    )}
                  </div>
                  <div className="flex-1">
                    <Button
                      variant="outline"
                      onClick={() => document.getElementById('background-upload').click()}
                      className="border-white/20 text-white hover:bg-white/10 mb-2 w-full"
                      disabled={uploadingImage}
                    >
                      {uploadingImage ? 'Uploading...' : 'Upload Background'}
                    </Button>
                    
                    {/* Background Position Controls */}
                    {profileData.background_image && (
                      <div className="mt-2">
                        <Label className="text-white text-xs">Position</Label>
                        <select
                          value={profileData.background_position || 'center'}
                          onChange={(e) => setProfileData({...profileData, background_position: e.target.value})}
                          className="bg-gray-800 border-gray-600 text-white text-xs rounded w-full mt-1"
                        >
                          <option value="center">Center</option>
                          <option value="top">Top</option>
                          <option value="bottom">Bottom</option>
                          <option value="left">Left</option>
                          <option value="right">Right</option>
                          <option value="top left">Top Left</option>
                          <option value="top right">Top Right</option>
                          <option value="bottom left">Bottom Left</option>
                          <option value="bottom right">Bottom Right</option>
                        </select>
                      </div>
                    )}
                    
                    <p className="text-gray-400 text-xs mt-1">Upload an image for your profile background</p>
                    <input
                      id="background-upload"
                      type="file"
                      accept="image/*"
                      onChange={(e) => {
                        const file = e.target.files[0];
                        if (file) {
                          handleImageUpload(file, 'background_image');
                        }
                      }}
                      className="hidden"
                    />
                  </div>
                </div>
              </div>

              {/* Header Image Upload */}
              <div>
                <Label className="text-white mb-3 block">Header Image</Label>
                <div className="flex items-center space-x-4">
                  <div className="w-32 h-20 bg-gray-700 rounded-lg flex items-center justify-center overflow-hidden">
                    {profileData.header_image ? (
                      <img 
                        src={profileData.header_image} 
                        alt="Header Preview" 
                        className="w-full h-full object-cover"
                        style={{ objectPosition: profileData.header_position || 'center' }}
                      />
                    ) : (
                      <Upload className="w-6 h-6 text-gray-400" />
                    )}
                  </div>
                  <div className="flex-1">
                    <Button
                      variant="outline"
                      onClick={() => document.getElementById('header-upload').click()}
                      className="border-white/20 text-white hover:bg-white/10 mb-2 w-full"
                      disabled={uploadingImage}
                    >
                      {uploadingImage ? 'Uploading...' : 'Upload Header'}
                    </Button>
                    
                    {/* Header Position Controls */}
                    {profileData.header_image && (
                      <div className="mt-2">
                        <Label className="text-white text-xs">Position</Label>
                        <select
                          value={profileData.header_position || 'center'}
                          onChange={(e) => setProfileData({...profileData, header_position: e.target.value})}
                          className="bg-gray-800 border-gray-600 text-white text-xs rounded w-full mt-1"
                        >
                          <option value="center">Center</option>
                          <option value="top">Top</option>
                          <option value="bottom">Bottom</option>
                          <option value="left">Left</option>
                          <option value="right">Right</option>
                          <option value="top left">Top Left</option>
                          <option value="top right">Top Right</option>
                          <option value="bottom left">Bottom Left</option>
                          <option value="bottom right">Bottom Right</option>
                        </select>
                      </div>
                    )}
                    
                    <p className="text-gray-400 text-xs mt-1">Upload an image for your profile header</p>
                    <input
                      id="header-upload"
                      type="file"
                      accept="image/*"
                      onChange={(e) => {
                        const file = e.target.files[0];
                        if (file) {
                          handleImageUpload(file, 'header_image');
                        }
                      }}
                      className="hidden"
                    />
                  </div>
                </div>
              </div>

              {/* Profile Image Upload */}
              <div className="text-center">
                <div className="relative w-20 h-20 mx-auto mb-4">
                  <img
                    src={user?.profile_image || 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face'}
                    alt="Profile"
                    className="w-20 h-20 rounded-full object-cover"
                  />
                  <Button
                    size="sm"
                    className="absolute -bottom-2 -right-2 w-8 h-8 p-0 bg-blue-600 hover:bg-blue-700 rounded-full"
                    onClick={() => document.getElementById('profile-image-upload').click()}
                    disabled={uploadingImage}
                  >
                    {uploadingImage ? (
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    ) : (
                      <Upload className="w-4 h-4" />
                    )}
                  </Button>
                  <input
                    id="profile-image-upload"
                    type="file"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files[0];
                      if (file) {
                        handleImageUpload(file, 'profile_image');
                      }
                    }}
                    className="hidden"
                  />
                </div>
              </div>

              {/* Basic Info */}
              <div>
                <Label className="text-white">Display Name</Label>
                <Input
                  value={profileData.name || user?.name || ''}
                  onChange={(e) => setProfileData({...profileData, name: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                />
              </div>

              <div>
                <Label className="text-white">Bio</Label>
                <Textarea
                  value={profileData.bio}
                  onChange={(e) => setProfileData({...profileData, bio: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Tell us about yourself..."
                  rows={3}
                />
              </div>

              <div>
                <Label className="text-white">Location</Label>
                <Input
                  value={profileData.location}
                  onChange={(e) => setProfileData({...profileData, location: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Your location"
                />
              </div>

              {/* Reading Preferences */}
              <div>
                <Label className="text-white">Favorite Genres</Label>
                <Input
                  value={profileData.genre_preferences?.join(', ') || ''}
                  onChange={(e) => setProfileData({...profileData, genre_preferences: e.target.value.split(', ').filter(g => g.trim())})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Fantasy, Sci-Fi, Romance..."
                />
              </div>

              {/* Social Links */}
              <div className="space-y-2">
                <Label className="text-white">Social Links</Label>
                <Input
                  value={profileData.social_links?.twitter || ''}
                  onChange={(e) => setProfileData({
                    ...profileData, 
                    social_links: {...profileData.social_links, twitter: e.target.value}
                  })}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Twitter username (without @)"
                />
                <Input
                  value={profileData.social_links?.website || ''}
                  onChange={(e) => setProfileData({
                    ...profileData, 
                    social_links: {...profileData.social_links, website: e.target.value}
                  })}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Website URL"
                />
              </div>
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => setIsEditing(false)}>
                Cancel
              </Button>
              <Button 
                onClick={async () => {
                  setUpdating(true);
                  try {
                    const response = await axios.put(`${API}/users/profile`, {
                      name: profileData.name,
                      profile_image: profileData.profile_image,
                      header_image: profileData.header_image,
                      background_image: profileData.background_image,
                      header_position: profileData.header_position,
                      background_position: profileData.background_position,
                      bio: profileData.bio,
                      location: profileData.location,
                      genre_preferences: profileData.genre_preferences,
                      social_links: profileData.social_links
                    });
                    
                    setIsEditing(false);
                    toast({
                      title: "Profile Updated",
                      description: "Your profile has been successfully updated.",
                    });
                  } catch (error) {
                    console.error('Profile update error:', error);
                    toast({
                      title: "Update Failed",
                      description: "Failed to update profile. Please try again.",
                      variant: "destructive",
                    });
                  } finally {
                    setUpdating(false);
                  }
                }}
                disabled={updating}
                className="bg-blue-600 hover:bg-blue-700 text-white"
              >
                {updating ? 'Saving...' : 'Save Changes'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        </main>
      </div>
    </div>
  );
};


// Profile Router - Directs to Writer or Reader profile based on user type
const ProfileRouter = () => {
  const { user } = React.useContext(AuthContext);
  
  if (!user) {
    return <Navigate to="/" replace />;
  }
  
  // Redirect admin users to admin dashboard
  if (user.user_type === 'admin') {
    return <Navigate to="/admin/dashboard" replace />;
  }
  
  if (user.user_type === 'writer') {
    return <WriterProfile />;
  } else {
    return <ReaderProfile />;
  }
};

// User Profile Component - For viewing other users' profiles
const UserProfile = () => {
  const { user, logout } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { userId } = useParams();
  const [profileUser, setProfileUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    const fetchUserProfile = async () => {
      try {
        // TODO: Replace with actual API call
        // const response = await axios.get(`${API}/users/${userId}`);
        // setProfileUser(response.data);
        
        // Mock data for now
        setProfileUser({
          id: userId,
          name: 'Demo User',
          user_type: 'reader',
          bio: 'This is a demo user profile. In a real application, this would show the actual user data.',
          profile_image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face',
          location: 'Demo City',
          joined_date: '2023-01-01',
          social_links: {
            twitter: '@demouser',
            website: 'https://demo.com'
          }
        });
      } catch (error) {
        console.error('Error fetching user profile:', error);
        toast({
          title: "Error",
          description: "Failed to load user profile",
          variant: "destructive",
        });
      } finally {
        setLoading(false);
      }
    };

    if (userId) {
      fetchUserProfile();
    }
  }, [userId, toast]);

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  if (loading) {
    return (
      <GlobalBackground className="bg-black text-white">
        <div className="min-h-screen flex items-center justify-center">
          <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
        </div>
      </GlobalBackground>
    );
  }

  if (!profileUser) {
    return (
      <GlobalBackground className="bg-black text-white">
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <h1 className="text-2xl font-bold text-white mb-4">User Not Found</h1>
            <Button onClick={() => navigate('/')} variant="outline" className="border-white/30 text-white hover:bg-white/10">
              Go Home
            </Button>
          </div>
        </div>
      </GlobalBackground>
    );
  }

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Card className={`rounded-xl ${getPanelClasses('mainPanel')}`}>
          <CardContent className="p-8">
            {/* Profile Header */}
            <div className="flex items-center space-x-6 mb-8">
              <img
                src={profileUser.profile_image}
                alt={profileUser.name}
                className="w-24 h-24 rounded-full object-cover border-4 border-white/20"
              />
              <div className="flex-1">
                <h1 className="text-3xl font-bold text-white mb-2">{profileUser.name}</h1>
                <p className="text-gray-300 mb-2">{profileUser.bio}</p>
                <div className="flex items-center space-x-4 text-sm text-gray-400">
                  {profileUser.location && (
                    <span>📍 {profileUser.location}</span>
                  )}
                  <span>📅 Joined {new Date(profileUser.joined_date).toLocaleDateString()}</span>
                  <span className="capitalize">👤 {profileUser.user_type}</span>
                </div>
              </div>
            </div>

            {/* Social Links */}
            {profileUser.social_links && Object.keys(profileUser.social_links).some(key => profileUser.social_links[key]) && (
              <div className="mb-8">
                <h3 className="text-lg font-semibold text-white mb-4">Connect</h3>
                <div className="flex space-x-4">
                  {profileUser.social_links.twitter && (
                    <Button variant="outline" size="sm" className="border-white/30 text-white hover:bg-white/10">
                      Twitter
                    </Button>
                  )}
                  {profileUser.social_links.website && (
                    <Button variant="outline" size="sm" className="border-white/30 text-white hover:bg-white/10">
                      Website
                    </Button>
                  )}
                </div>
              </div>
            )}

            {/* Actions */}
            <div className="flex space-x-4">
              {user && user.id !== profileUser.id && (
                <>
                  <FriendRequestButton userId={profileUser.id} />
                  <Button variant="outline" className="border-white/30 text-white hover:bg-white/10">
                    <MessageSquare className="w-4 h-4 mr-2" />
                    Message
                  </Button>
                </>
              )}
              {profileUser.user_type === 'writer' && (
                <Button 
                  onClick={() => navigate(`/writer/${profileUser.id}`)}
                  className="bg-blue-600 hover:bg-blue-700 text-white"
                >
                  <BookOpen className="w-4 h-4 mr-2" />
                  View Writer Profile
                </Button>
              )}
            </div>

            {/* Additional Content Based on User Type */}
            {profileUser.user_type === 'writer' && (
              <div className="mt-8 pt-8 border-t border-white/10">
                <h3 className="text-lg font-semibold text-white mb-4">Recent Stories</h3>
                <p className="text-gray-400">This writer's recent stories would appear here.</p>
              </div>
            )}

            {profileUser.user_type === 'reader' && (
              <div className="mt-8 pt-8 border-t border-white/10">
                <h3 className="text-lg font-semibold text-white mb-4">Reading Activity</h3>
                <p className="text-gray-400">This reader's recent activity would appear here.</p>
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </GlobalBackground>
  );
};

// Admin Panel Component
const AdminPanel = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();

  // Redirect non-admin users
  if (!isAdmin()) {
    return <Navigate to="/dashboard" replace />;
  }
  const [siteSettings, setSiteSettings] = useState(null);
  const [landingContent, setLandingContent] = useState(null);
  const [updating, setUpdating] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const { toast } = useToast();
  
  // Mock user for demo
  const mockUser = user || { name: 'Demo Admin', id: 'demo123' };

  useEffect(() => {
    // Fetch real data instead of using mock data
    fetchSiteSettings();
    fetchLandingContent();
  }, []);

  const fetchSiteSettings = async () => {
    try {
      const response = await axios.get(`${API}/admin/site-settings`);
      setSiteSettings(response.data);
    } catch (error) {
      console.error('Error fetching site settings:', error);
      // Set default values if API fails
      setSiteSettings({
        site_name: "Queens Mountain",
        header_logo: "",
        background_color: "#000000", 
        primary_color: "#ffffff",
        secondary_color: "#666666",
        background_image: ""
      });
    }
  };

  const fetchLandingContent = async () => {
    try {
      const response = await axios.get(`${API}/content/landing-page`);
      setLandingContent(response.data);
    } catch (error) {
      console.error('Error fetching landing content:', error);
      // Set default values if API fails
      setLandingContent({
        hero_title: "Welcome to Queens Mountain",
        hero_subtitle: "A premium platform where writers share their stories and readers discover amazing content. Join our community of storytellers and book lovers.",
        hero_cta_text: "Get Started",
        hero_background_image: "",
        feature1_title: "For Readers",
        feature1_description: "Discover incredible stories, follow your favorite writers, and share reviews with the community.",
        feature2_title: "For Writers", 
        feature2_description: "Share your stories, build an audience, and earn from your passion with our subscription system.",
        feature3_title: "Community",
        feature3_description: "Join a vibrant community where stories come alive and friendships are formed through literature."
      });
    }
  };

  const updateSiteSettings = async () => {
    if (!siteSettings) return;
    
    setUpdating(true);
    try {
      await axios.put(`${API}/admin/site-settings`, siteSettings, {
        withCredentials: true
      });
      
      // Trigger event to refresh global background on other components
      window.dispatchEvent(new Event('siteSettingsUpdated'));
      
      toast({
        title: "Settings Updated!",
        description: "Site settings have been successfully updated.",
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to update site settings.",
        variant: "destructive",
      });
    }
    setUpdating(false);
  };

  const updateLandingContent = async () => {
    if (!landingContent) return;
    
    setUpdating(true);
    try {
      await axios.put(`${API}/admin/landing-page`, landingContent, {
        withCredentials: true
      });
      toast({
        title: "Content Updated!",
        description: "Landing page content has been successfully updated.",
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to update landing page content.",
        variant: "destructive",
      });
    }
    setUpdating(false);
  };

  const handleImageUpload = (event, fieldName) => {
    const file = event.target.files[0];
    if (file) {
      setUploadingImage(true);
      const reader = new FileReader();
      reader.onload = (e) => {
        if (fieldName === 'background') {
          setLandingContent({
            ...landingContent,
            hero_background_image: e.target.result
          });
        } else if (fieldName === 'logo') {
          setSiteSettings({
            ...siteSettings,
            header_logo: e.target.result
          });
        } else if (fieldName === 'global_background') {
          setSiteSettings({
            ...siteSettings,
            background_image: e.target.result
          });
        }
        setUploadingImage(false);
        toast({
          title: "Image Uploaded!",
          description: `${
            fieldName === 'background' ? 'Hero background' : 
            fieldName === 'logo' ? 'Logo' : 
            'Global background'
          } image has been uploaded successfully.`,
        });
      };
      reader.readAsDataURL(file);
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  if (!user) {
    return <Navigate to="/" replace />;
  }

  if (!siteSettings || !landingContent) {
    return (
      <div className="min-h-screen bg-black text-white flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    );
  }

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>Queens Mountain Admin</h1>
            </div>
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                onClick={() => navigate('/dashboard')}
                className="text-gray-300 hover:text-white hover:bg-white/10"
              >
                Dashboard
              </Button>
              <span className="text-white">Admin: {mockUser.name}</span>
              <Button
                variant="ghost"
                onClick={handleLogout}
                className="text-gray-300 hover:text-white hover:bg-red-900/20"
                data-testid="logout-button"
              >
                <LogOut className="w-4 h-4" />
              </Button>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center space-x-2 mb-8">
          <Settings className="w-6 h-6 text-gray-400" />
          <h2 className="text-3xl font-bold text-white">Site Administration</h2>
        </div>

        <Tabs defaultValue="branding" className="w-full">
          <TabsList className="grid w-full grid-cols-3 bg-white/10">
            <TabsTrigger value="branding" className="text-white data-[state=active]:bg-white data-[state=active]:text-black">
              <Palette className="w-4 h-4 mr-2" />
              Branding
            </TabsTrigger>
            <TabsTrigger value="content" className="text-white data-[state=active]:bg-white data-[state=active]:text-black">
              <BookOpen className="w-4 h-4 mr-2" />
              Landing Page
            </TabsTrigger>
            <TabsTrigger value="appearance" className="text-white data-[state=active]:bg-white data-[state=active]:text-black">
              <Settings className="w-4 h-4 mr-2" />
              Site Settings
            </TabsTrigger>
          </TabsList>

          <TabsContent value="branding" className="space-y-6 mt-6">
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Site Branding & Header</CardTitle>
                <CardDescription className="text-gray-400">
                  Customize your site's header, logo, and visual identity
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div>
                  <Label htmlFor="site_name" className="text-white">Site Name/Title</Label>
                  <Input
                    id="site_name"
                    value={siteSettings.site_name}
                    onChange={(e) => setSiteSettings({...siteSettings, site_name: e.target.value})}
                    className="bg-white/10 border-white/20 text-white"
                    placeholder="Queens Mountain"
                    data-testid="site-name-input"
                  />
                  <p className="text-xs text-gray-400 mt-1">This will appear in the header of your site</p>
                </div>

                <div>
                  <Label className="text-white">Site Logo</Label>
                  <div className="mt-2 space-y-4">
                    {siteSettings.header_logo && (
                      <div className="flex items-center space-x-4 p-4 bg-white/5 rounded-lg">
                        <img 
                          src={siteSettings.header_logo} 
                          alt="Site Logo Preview" 
                          className="w-16 h-16 object-cover rounded border border-white/20"
                        />
                        <div>
                          <p className="text-white text-sm font-medium">Current Logo</p>
                          <p className="text-gray-400 text-xs">This logo will be clickable and link to the homepage</p>
                        </div>
                      </div>
                    )}
                    <div>
                      <label htmlFor="logo-upload">
                        <Button
                          variant="outline"
                          disabled={uploadingImage}
                          className="border-white/30 text-white hover:bg-white/10 cursor-pointer"
                          asChild
                        >
                          <span>
                            <Upload className="w-4 h-4 mr-2" />
                            {uploadingImage ? 'Uploading...' : 'Upload Logo'}
                          </span>
                        </Button>
                      </label>
                      <input
                        id="logo-upload"
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleImageUpload(e, 'logo')}
                        className="hidden"
                      />
                      <p className="text-xs text-gray-400 mt-2">Upload a logo image (PNG, JPG, SVG recommended)</p>
                    </div>
                  </div>
                </div>

                <div>
                  <Label className="text-white">Global Site Background</Label>
                  <div className="mt-2 space-y-4">
                    {siteSettings.background_image && (
                      <div className="relative">
                        <img 
                          src={siteSettings.background_image} 
                          alt="Global Background Preview" 
                          className="w-full h-32 object-cover rounded border border-white/20"
                        />
                        <div className="absolute inset-0 bg-black/30 flex items-center justify-center rounded">
                          <p className="text-white text-sm font-medium">Global Site Background</p>
                        </div>
                      </div>
                    )}
                    <div>
                      <label htmlFor="global-background-upload">
                        <Button
                          variant="outline"
                          disabled={uploadingImage}
                          className="border-white/30 text-white hover:bg-white/10 cursor-pointer"
                          asChild
                        >
                          <span>
                            <Upload className="w-4 h-4 mr-2" />
                            {uploadingImage ? 'Uploading...' : 'Upload Global Background'}
                          </span>
                        </Button>
                      </label>
                      <input
                        id="global-background-upload"
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleImageUpload(e, 'global_background')}
                        className="hidden"
                      />
                      <p className="text-xs text-gray-400 mt-2">This background will apply to all site pages (landing, forum, reviews, admin, etc.)</p>
                    </div>
                    <div className="mt-2">
                      <Button
                        variant="outline"
                        onClick={() => {
                          setSiteSettings({
                            ...siteSettings,
                            background_image: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80"
                          });
                          toast({
                            title: "Test Background Set",
                            description: "Test mountain background applied. Click Save Branding to apply.",
                          });
                        }}
                        className="border-white/30 text-white hover:bg-white/10"
                      >
                        Set Test Background
                      </Button>
                      <p className="text-xs text-gray-400 mt-1">Click this to test with a sample mountain background</p>
                    </div>
                  </div>
                </div>

                <div>
                  <Label className="text-white">Landing Page Hero Background</Label>
                  <div className="mt-2 space-y-4">
                    {landingContent.hero_background_image && (
                      <div className="relative">
                        <img 
                          src={landingContent.hero_background_image} 
                          alt="Hero Background Preview" 
                          className="w-full h-32 object-cover rounded border border-white/20"
                        />
                        <div className="absolute inset-0 bg-black/30 flex items-center justify-center rounded">
                          <p className="text-white text-sm font-medium">Landing Page Hero Background</p>
                        </div>
                      </div>
                    )}
                    <div>
                      <label htmlFor="background-upload">
                        <Button
                          variant="outline"
                          disabled={uploadingImage}
                          className="border-white/30 text-white hover:bg-white/10 cursor-pointer"
                          asChild
                        >
                          <span>
                            <Upload className="w-4 h-4 mr-2" />
                            {uploadingImage ? 'Uploading...' : 'Upload Hero Background'}
                          </span>
                        </Button>
                      </label>
                      <input
                        id="background-upload"
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleImageUpload(e, 'background')}
                        className="hidden"
                      />
                      <p className="text-xs text-gray-400 mt-2">Specific background for the landing page hero section (overlays global background)</p>
                    </div>
                  </div>
                </div>

                <Button
                  onClick={() => {
                    updateSiteSettings();
                    updateLandingContent();
                  }}
                  disabled={updating || uploadingImage}
                  className="bg-white text-black hover:bg-gray-200"
                >
                  <Save className="w-4 h-4 mr-2" />
                  {updating ? 'Saving...' : 'Save Branding'}
                </Button>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="content" className="space-y-6 mt-6">
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Hero Section</CardTitle>
                <CardDescription className="text-gray-400">
                  Customize the main hero section of your landing page
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="hero_title" className="text-white">Hero Title</Label>
                  <Input
                    id="hero_title"
                    value={landingContent.hero_title}
                    onChange={(e) => setLandingContent({...landingContent, hero_title: e.target.value})}
                    className="bg-white/10 border-white/20 text-white"
                    placeholder="Welcome to Queens Mountain"
                  />
                </div>

                <div>
                  <Label htmlFor="hero_subtitle" className="text-white">Hero Subtitle</Label>
                  <Textarea
                    id="hero_subtitle"
                    value={landingContent.hero_subtitle}
                    onChange={(e) => setLandingContent({...landingContent, hero_subtitle: e.target.value})}
                    className="bg-white/10 border-white/20 text-white"
                    rows={3}
                  />
                </div>

                <div>
                  <Label htmlFor="hero_cta_text" className="text-white">Call-to-Action Button Text</Label>
                  <Input
                    id="hero_cta_text"
                    value={landingContent.hero_cta_text}
                    onChange={(e) => setLandingContent({...landingContent, hero_cta_text: e.target.value})}
                    className="bg-white/10 border-white/20 text-white"
                    placeholder="Get Started"
                  />
                </div>
              </CardContent>
            </Card>

            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Feature Cards</CardTitle>
                <CardDescription className="text-gray-400">
                  Customize the three feature cards below the hero section
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Feature 1 */}
                <div className="border border-white/10 rounded-lg p-4">
                  <h4 className="text-white font-semibold mb-3">Feature 1 - Readers</h4>
                  <div className="space-y-3">
                    <Input
                      value={landingContent.feature1_title}
                      onChange={(e) => setLandingContent({...landingContent, feature1_title: e.target.value})}
                      placeholder="Feature title"
                      className="bg-white/10 border-white/20 text-white"
                    />
                    <Textarea
                      value={landingContent.feature1_description}
                      onChange={(e) => setLandingContent({...landingContent, feature1_description: e.target.value})}
                      placeholder="Feature description"
                      className="bg-white/10 border-white/20 text-white"
                      rows={2}
                    />
                  </div>
                </div>

                {/* Feature 2 */}
                <div className="border border-white/10 rounded-lg p-4">
                  <h4 className="text-white font-semibold mb-3">Feature 2 - Writers</h4>
                  <div className="space-y-3">
                    <Input
                      value={landingContent.feature2_title}
                      onChange={(e) => setLandingContent({...landingContent, feature2_title: e.target.value})}
                      placeholder="Feature title"
                      className="bg-white/10 border-white/20 text-white"
                    />
                    <Textarea
                      value={landingContent.feature2_description}
                      onChange={(e) => setLandingContent({...landingContent, feature2_description: e.target.value})}
                      placeholder="Feature description"
                      className="bg-white/10 border-white/20 text-white"
                      rows={2}
                    />
                  </div>
                </div>

                {/* Feature 3 */}
                <div className="border border-white/10 rounded-lg p-4">
                  <h4 className="text-white font-semibold mb-3">Feature 3 - Community</h4>
                  <div className="space-y-3">
                    <Input
                      value={landingContent.feature3_title}
                      onChange={(e) => setLandingContent({...landingContent, feature3_title: e.target.value})}
                      placeholder="Feature title"
                      className="bg-white/10 border-white/20 text-white"
                    />
                    <Textarea
                      value={landingContent.feature3_description}
                      onChange={(e) => setLandingContent({...landingContent, feature3_description: e.target.value})}
                      placeholder="Feature description"
                      className="bg-white/10 border-white/20 text-white"
                      rows={2}
                    />
                  </div>
                </div>

                <Button
                  onClick={updateLandingContent}
                  disabled={updating}
                  className="bg-white text-black hover:bg-gray-200"
                >
                  <Save className="w-4 h-4 mr-2" />
                  {updating ? 'Saving...' : 'Save Content'}
                </Button>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="appearance" className="space-y-6 mt-6">
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Site Colors & Styling</CardTitle>
                <CardDescription className="text-gray-400">
                  Customize your site's color scheme and styling
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="background_color" className="text-white">Background Color</Label>
                    <Input
                      id="background_color"
                      type="color"
                      value={siteSettings.background_color}
                      onChange={(e) => setSiteSettings({...siteSettings, background_color: e.target.value})}
                      className="bg-white/10 border-white/20 text-white h-10"
                    />
                  </div>
                  <div>
                    <Label htmlFor="primary_color" className="text-white">Primary Color</Label>
                    <Input
                      id="primary_color"
                      type="color"
                      value={siteSettings.primary_color || '#ffffff'}
                      onChange={(e) => setSiteSettings({...siteSettings, primary_color: e.target.value})}
                      className="bg-white/10 border-white/20 text-white h-10"
                    />
                  </div>
                </div>

                <Button
                  onClick={updateSiteSettings}
                  disabled={updating}
                  className="bg-white text-black hover:bg-gray-200"
                >
                  <Save className="w-4 h-4 mr-2" />
                  {updating ? 'Saving...' : 'Save Settings'}
                </Button>
              </CardContent>
            </Card>
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Hero Section</CardTitle>
                <CardDescription className="text-gray-400">
                  Customize the main hero section of your landing page
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="hero_title" className="text-white">Hero Title</Label>
                  <Input
                    id="hero_title"
                    value={landingContent.hero_title}
                    onChange={(e) => setLandingContent({...landingContent, hero_title: e.target.value})}
                    className="bg-white/10 border-white/20 text-white"
                    placeholder="Welcome to Queens Mountain"
                  />
                </div>

                <div>
                  <Label htmlFor="hero_subtitle" className="text-white">Hero Subtitle</Label>
                  <Textarea
                    id="hero_subtitle"
                    value={landingContent.hero_subtitle}
                    onChange={(e) => setLandingContent({...landingContent, hero_subtitle: e.target.value})}
                    className="bg-white/10 border-white/20 text-white"
                    rows={3}
                  />
                </div>

                <div>
                  <Label htmlFor="hero_cta_text" className="text-white">Call-to-Action Button Text</Label>
                  <Input
                    id="hero_cta_text"
                    value={landingContent.hero_cta_text}
                    onChange={(e) => setLandingContent({...landingContent, hero_cta_text: e.target.value})}
                    className="bg-white/10 border-white/20 text-white"
                    placeholder="Get Started"
                  />
                </div>
              </CardContent>
            </Card>

            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Feature Cards</CardTitle>
                <CardDescription className="text-gray-400">
                  Customize the three feature cards below the hero section
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Feature 1 */}
                <div className="border border-white/10 rounded-lg p-4">
                  <h4 className="text-white font-semibold mb-3">Feature 1 - Readers</h4>
                  <div className="space-y-3">
                    <Input
                      value={landingContent.feature1_title}
                      onChange={(e) => setLandingContent({...landingContent, feature1_title: e.target.value})}
                      placeholder="Feature title"
                      className="bg-white/10 border-white/20 text-white"
                    />
                    <Textarea
                      value={landingContent.feature1_description}
                      onChange={(e) => setLandingContent({...landingContent, feature1_description: e.target.value})}
                      placeholder="Feature description"
                      className="bg-white/10 border-white/20 text-white"
                      rows={2}
                    />
                  </div>
                </div>

                {/* Feature 2 */}
                <div className="border border-white/10 rounded-lg p-4">
                  <h4 className="text-white font-semibold mb-3">Feature 2 - Writers</h4>
                  <div className="space-y-3">
                    <Input
                      value={landingContent.feature2_title}
                      onChange={(e) => setLandingContent({...landingContent, feature2_title: e.target.value})}
                      placeholder="Feature title"
                      className="bg-white/10 border-white/20 text-white"
                    />
                    <Textarea
                      value={landingContent.feature2_description}
                      onChange={(e) => setLandingContent({...landingContent, feature2_description: e.target.value})}
                      placeholder="Feature description"
                      className="bg-white/10 border-white/20 text-white"
                      rows={2}
                    />
                  </div>
                </div>

                {/* Feature 3 */}
                <div className="border border-white/10 rounded-lg p-4">
                  <h4 className="text-white font-semibold mb-3">Feature 3 - Community</h4>
                  <div className="space-y-3">
                    <Input
                      value={landingContent.feature3_title}
                      onChange={(e) => setLandingContent({...landingContent, feature3_title: e.target.value})}
                      placeholder="Feature title"
                      className="bg-white/10 border-white/20 text-white"
                    />
                    <Textarea
                      value={landingContent.feature3_description}
                      onChange={(e) => setLandingContent({...landingContent, feature3_description: e.target.value})}
                      placeholder="Feature description"
                      className="bg-white/10 border-white/20 text-white"
                      rows={2}
                    />
                  </div>
                </div>

                <Button
                  onClick={updateLandingContent}
                  disabled={updating}
                  className="bg-white text-black hover:bg-gray-200"
                >
                  <Save className="w-4 h-4 mr-2" />
                  {updating ? 'Saving...' : 'Save Content'}
                </Button>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </main>
    </GlobalBackground>
  );
};
const Dashboard = () => {
  const { user, logout, isAdmin, switchUserType } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  if (!user) {
    return <Navigate to="/" replace />;
  }

  // Redirect non-admin users to landing page
  if (!isAdmin()) {
    return <Navigate to="/" replace />;
  }

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>Queens Mountain</h1>
              <div className="hidden md:flex space-x-4">
                <Button
                  variant="ghost"
                  onClick={() => navigate('/forum')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  <MessageSquare className="w-4 h-4 mr-2" />
                  Community
                </Button>
                <Button
                  variant="ghost"
                  onClick={() => navigate('/genres')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  <BookOpen className="w-4 h-4 mr-2" />
                  Genres
                </Button>
                <Button
                  variant="ghost"
                  onClick={() => navigate('/reviews')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  <Star className="w-4 h-4 mr-2" />
                  Reviews
                </Button>
                {/* Show admin link for any authenticated user (for MVP) */}
                <Button
                  variant="ghost"
                  onClick={() => navigate('/admin')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  <Settings className="w-4 h-4 mr-2" />
                  Admin
                </Button>
              </div>
            </div>
            <div className="flex items-center space-x-4">
              <span 
                onClick={() => navigate('/profile')}
                className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
              >
                {user.name}
              </span>
              <Button
                variant="ghost"
                onClick={handleLogout}
                className="text-gray-300 hover:text-white hover:bg-red-900/20"
                data-testid="logout-button"
              >
                <LogOut className="w-4 h-4" />
              </Button>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="text-center">
          <h2 className="text-3xl font-bold text-white mb-4">Dashboard</h2>
          <p className="text-gray-300 mb-4">Welcome to your Queens Mountain dashboard, {user?.name}!</p>
          <p className="text-sm text-blue-400 mb-8">Current role: {user?.user_type}</p>

          {/* Demo User Type Switcher for Testing Permissions */}
          <div className="mb-6 p-4 bg-yellow-900/20 border border-yellow-600/30 rounded-lg max-w-md mx-auto">
            <p className="text-yellow-400 text-sm mb-3">🔧 Demo Mode: Test different user permissions</p>
            <div className="flex justify-center space-x-2">
              <Button
                variant="outline" 
                size="sm"
                onClick={() => switchUserType('writer')}
                className={`${user?.user_type === 'writer' ? 'bg-blue-600 text-white border-blue-600' : 'text-gray-300 border-gray-600 hover:bg-gray-700'}`}
              >
                Writer
              </Button>
              <Button
                variant="outline"
                size="sm" 
                onClick={() => switchUserType('reader')}
                className={`${user?.user_type === 'reader' ? 'bg-blue-600 text-white border-blue-600' : 'text-gray-300 border-gray-600 hover:bg-gray-700'}`}
              >
                Reader
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => switchUserType('admin')}
                className={`${user?.user_type === 'admin' ? 'bg-blue-600 text-white border-blue-600' : 'text-gray-300 border-gray-600 hover:bg-gray-700'}`}
              >
                Admin
              </Button>
            </div>
          </div>
          
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            {/* Quick Navigation Cards */}
            <Card className={`rounded-xl ${getPanelClasses('mainPanel')} cursor-pointer hover:bg-white/10 transition-colors`} onClick={() => navigate('/forum')}>
              <CardHeader className="text-center">
                <MessageSquare className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                <CardTitle className="text-white">Community</CardTitle>
                <CardDescription className="text-gray-400">
                  Join community discussions
                </CardDescription>
              </CardHeader>
            </Card>

            <Card className={`rounded-xl ${getPanelClasses('mainPanel')} cursor-pointer hover:bg-white/10 transition-colors`} onClick={() => navigate('/reviews')}>
              <CardHeader className="text-center">
                <Star className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                <CardTitle className="text-white">Reviews</CardTitle>
                <CardDescription className="text-gray-400">
                  Top-rated content
                </CardDescription>
              </CardHeader>
            </Card>

            {/* Premium Membership Card */}
            <Card className={`rounded-xl ${getPanelClasses('mainPanel')} border-gold-500/30`}>
              <CardHeader className="text-center">
                <div className="w-12 h-12 bg-gradient-to-r from-gold-500 to-yellow-600 rounded-full flex items-center justify-center mx-auto mb-2">
                  <Award className="w-6 h-6 text-white" />
                </div>
                <CardTitle className="text-white">Premium</CardTitle>
                <CardDescription className="text-gray-400">
                  Unlock exclusive content
                </CardDescription>
                <div className="mt-3">
                  <PaymentButton
                    packageId="site_premium_monthly"
                    buttonText="Go Premium"
                    className="bg-gold-600 hover:bg-gold-700 text-white text-sm px-4 py-2"
                    icon={Award}
                  />
                </div>
              </CardHeader>
            </Card>

            {/* Admin Panel - Only visible to admins */}
            {isAdmin() && (
              <Card className={`rounded-xl ${getPanelClasses('mainPanel')} cursor-pointer hover:bg-white/10 transition-colors`} onClick={() => navigate('/admin')}>
                <CardHeader className="text-center">
                  <Settings className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                  <CardTitle className="text-white">Admin Panel</CardTitle>
                  <CardDescription className="text-gray-400">
                    Manage site settings
                  </CardDescription>
                </CardHeader>
              </Card>
            )}

            <Card className={`rounded-xl ${getPanelClasses('mainPanel')} cursor-pointer hover:bg-white/10 transition-colors`} onClick={() => navigate('/profile')} data-testid="profile-card">
              <CardHeader className="text-center">
                <Users className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                <CardTitle className="text-white">Profile</CardTitle>
                <CardDescription className="text-gray-400">
                  Manage your profile
                </CardDescription>
              </CardHeader>
            </Card>
          </div>
          
          {user.user_type === 'writer' && (
            <Card className={`rounded-xl ${getPanelClasses('mainPanel')} max-w-md mx-auto`}>
              <CardHeader>
                <CardTitle className="text-white">Writer Dashboard</CardTitle>
                <CardDescription className="text-gray-400">
                  Manage your content and subscribers
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-gray-300">Writer features coming soon...</p>
              </CardContent>
            </Card>
          )}
          
          {user.user_type === 'reader' && (
            <Card className={`rounded-xl ${getPanelClasses('mainPanel')} max-w-md mx-auto`}>
              <CardHeader>
                <CardTitle className="text-white">Reader Dashboard</CardTitle>
                <CardDescription className="text-gray-400">
                  Discover and follow your favorite writers
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-gray-300">Reader features coming soon...</p>
              </CardContent>
            </Card>
          )}
        </div>
      </main>
    </GlobalBackground>
  );
};

// Forum Component
const Forum = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const [categories, setCategories] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [topics, setTopics] = useState([]);
  const [selectedTopic, setSelectedTopic] = useState(null);
  const [topicDetails, setTopicDetails] = useState(null);
  const [showNewTopicDialog, setShowNewTopicDialog] = useState(false);
  const [showNewReplyDialog, setShowNewReplyDialog] = useState(false);
  const [newTopic, setNewTopic] = useState({ title: '', content: '' });
  const [newReply, setNewReply] = useState('');
  const { toast } = useToast();

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    try {
      const response = await axios.get(`${API}/forum/categories`);
      setCategories(response.data);
    } catch (error) {
      console.error('Error fetching categories:', error);
    }
  };

  const fetchTopics = async (categoryId) => {
    try {
      const response = await axios.get(`${API}/forum/categories/${categoryId}/topics`);
      setTopics(response.data);
    } catch (error) {
      console.error('Error fetching topics:', error);
    }
  };

  const fetchTopicDetails = async (topicId) => {
    try {
      const response = await axios.get(`${API}/forum/topics/${topicId}`);
      setTopicDetails(response.data);
    } catch (error) {
      console.error('Error fetching topic details:', error);
    }
  };

  const createTopic = async (e) => {
    e.preventDefault();
    if (!selectedCategory) return;

    try {
      await axios.post(`${API}/forum/topics`, {
        category_id: selectedCategory,
        ...newTopic
      }, { withCredentials: true });
      
      toast({
        title: "Topic Created!",
        description: "Your new topic has been created successfully.",
      });
      setShowNewTopicDialog(false);
      setNewTopic({ title: '', content: '' });
      fetchTopics(selectedCategory);
    } catch (error) {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to create topic",
        variant: "destructive",
      });
    }
  };

  const createReply = async (e) => {
    e.preventDefault();
    if (!selectedTopic) return;

    try {
      await axios.post(`${API}/forum/replies`, {
        topic_id: selectedTopic,
        content: newReply
      }, { withCredentials: true });
      
      toast({
        title: "Reply Posted!",
        description: "Your reply has been posted successfully.",
      });
      setShowNewReplyDialog(false);
      setNewReply('');
      fetchTopicDetails(selectedTopic);
    } catch (error) {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to post reply",
        variant: "destructive",
      });
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              {/* Dashboard - Only visible to admins */}
              {isAdmin() && (
                <Button
                  variant="ghost"
                  onClick={() => navigate('/dashboard')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  Dashboard
                </Button>
              )}
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <>
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-red-900/20"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center space-x-2 mb-8">
          <MessageSquare className="w-6 h-6 text-gray-400" />
          <h2 className="text-3xl font-bold text-white">Community Forum</h2>
        </div>

        <div className="grid lg:grid-cols-12 gap-6">
          {/* Categories Sidebar */}
          <div className="lg:col-span-3">
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Categories</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {categories.map((category) => (
                    <Button
                      key={category.id}
                      variant={selectedCategory === category.id ? "default" : "ghost"}
                      className={`w-full justify-start ${
                        selectedCategory === category.id 
                          ? 'bg-white text-black' 
                          : 'text-gray-300 hover:text-white hover:bg-white/10'
                      }`}
                      onClick={() => {
                        setSelectedCategory(category.id);
                        setSelectedTopic(null);
                        setTopicDetails(null);
                        fetchTopics(category.id);
                      }}
                    >
                      {category.name}
                    </Button>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Main Content Area */}
          <div className="lg:col-span-9">
            {!selectedCategory ? (
              <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
                <CardContent className="text-center py-12">
                  <MessageSquare className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                  <p className="text-gray-300 text-lg mb-2">Welcome to the Community Forum</p>
                  <p className="text-gray-400">Select a category to start browsing topics and join the conversation.</p>
                </CardContent>
              </Card>
            ) : !selectedTopic ? (
              /* Topics List */
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <h3 className="text-xl font-semibold text-white">Topics</h3>
                  {user && (
                    <Button 
                      onClick={() => setShowNewTopicDialog(true)}
                      className="bg-white text-black hover:bg-gray-200"
                    >
                      New Topic
                    </Button>
                  )}
                </div>

                {topics.length === 0 ? (
                  <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
                    <CardContent className="text-center py-8">
                      <p className="text-gray-300">No topics yet in this category.</p>
                      {user && (
                        <Button 
                          onClick={() => setShowNewTopicDialog(true)}
                          variant="outline"
                          className="mt-4 border-white/20 text-white hover:bg-white/10"
                        >
                          Start the first discussion
                        </Button>
                      )}
                    </CardContent>
                  </Card>
                ) : (
                  topics.map((topic) => (
                    <Card 
                      key={topic.id} 
                      className="bg-white/5 border-white/10 cursor-pointer hover:bg-white/10 transition-colors"
                      onClick={() => {
                        setSelectedTopic(topic.id);
                        fetchTopicDetails(topic.id);
                      }}
                    >
                      <CardHeader>
                        <div className="flex justify-between items-start">
                          <div>
                            <CardTitle className="text-white">{topic.title}</CardTitle>
                            <CardDescription className="text-gray-400 mt-1">
                              By {topic.author_name} • {new Date(topic.created_at).toLocaleDateString()}
                            </CardDescription>
                          </div>
                          <div className="text-right text-sm text-gray-400">
                            <div>{topic.replies} replies</div>
                            <div>{topic.views} views</div>
                          </div>
                        </div>
                      </CardHeader>
                    </Card>
                  ))
                )}
              </div>
            ) : (
              /* Topic Details with Replies */
              topicDetails && (
                <div className="space-y-6">
                  <div className="flex items-center space-x-4">
                    <Button
                      variant="ghost"
                      onClick={() => {
                        setSelectedTopic(null);
                        setTopicDetails(null);
                      }}
                      className="text-gray-300 hover:text-white hover:bg-white/10"
                    >
                      ← Back to Topics
                    </Button>
                    {user && (
                      <Button 
                        onClick={() => setShowNewReplyDialog(true)}
                        className="bg-white text-black hover:bg-gray-200"
                      >
                        Reply
                      </Button>
                    )}
                  </div>

                  {/* Original Topic */}
                  <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
                    <CardHeader>
                      <CardTitle className="text-white">{topicDetails.title}</CardTitle>
                      <CardDescription className="text-gray-400">
                        By {topicDetails.author_name} • {new Date(topicDetails.created_at).toLocaleDateString()}
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <p className="text-gray-200 whitespace-pre-wrap">{topicDetails.content}</p>
                    </CardContent>
                  </Card>

                  {/* Replies */}
                  <div className="space-y-4">
                    <h4 className="text-lg font-semibold text-white">
                      Replies ({topicDetails.replies?.length || 0})
                    </h4>
                    
                    {topicDetails.replies?.map((reply) => (
                      <Card key={reply.id} className="bg-white/5 border-white/10 ml-6">
                        <CardHeader className="pb-3">
                          <CardDescription className="text-gray-400">
                            By {reply.author_name} • {new Date(reply.created_at).toLocaleDateString()}
                          </CardDescription>
                        </CardHeader>
                        <CardContent>
                          <p className="text-gray-200 whitespace-pre-wrap">{reply.content}</p>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </div>
              )
            )}
          </div>
        </div>

        {/* New Topic Dialog */}
        <Dialog open={showNewTopicDialog} onOpenChange={setShowNewTopicDialog}>
          <DialogContent className="sm:max-w-2xl bg-black border-white/20 text-white">
            <DialogHeader>
              <DialogTitle>Create New Topic</DialogTitle>
              <DialogDescription className="text-gray-400">
                Start a new discussion in the community
              </DialogDescription>
            </DialogHeader>
            
            <form onSubmit={createTopic} className="space-y-4">
              <div>
                <Label htmlFor="topic_title">Title</Label>
                <Input
                  id="topic_title"
                  value={newTopic.title}
                  onChange={(e) => setNewTopic({...newTopic, title: e.target.value})}
                  placeholder="What's your topic about?"
                  required
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
              
              <div>
                <Label htmlFor="topic_content">Content</Label>
                <Textarea
                  id="topic_content"
                  value={newTopic.content}
                  onChange={(e) => setNewTopic({...newTopic, content: e.target.value})}
                  placeholder="Share your thoughts..."
                  required
                  rows={6}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
              
              <DialogFooter>
                <Button type="submit" className="bg-white text-black hover:bg-gray-200">
                  Create Topic
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>

        {/* New Reply Dialog */}
        <Dialog open={showNewReplyDialog} onOpenChange={setShowNewReplyDialog}>
          <DialogContent className="sm:max-w-2xl bg-black border-white/20 text-white">
            <DialogHeader>
              <DialogTitle>Post Reply</DialogTitle>
              <DialogDescription className="text-gray-400">
                Share your thoughts on this topic
              </DialogDescription>
            </DialogHeader>
            
            <form onSubmit={createReply} className="space-y-4">
              <div>
                <Label htmlFor="reply_content">Your Reply</Label>
                <Textarea
                  id="reply_content"
                  value={newReply}
                  onChange={(e) => setNewReply(e.target.value)}
                  placeholder="What do you think?"
                  required
                  rows={6}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
              
              <DialogFooter>
                <Button type="submit" className="bg-white text-black hover:bg-gray-200">
                  Post Reply
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </main>
    </GlobalBackground>
  );
};

// Genre Component
const Genres = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const [genres, setGenres] = useState([]);

  // Mock genre data
  useEffect(() => {
    setGenres([
      { id: 1, name: 'Fantasy', storyCount: 245, description: 'Epic adventures in magical worlds' },
      { id: 2, name: 'Romance', storyCount: 189, description: 'Love stories and relationships' },
      { id: 3, name: 'Sci-Fi', storyCount: 156, description: 'Science fiction and futuristic tales' },
      { id: 4, name: 'Mystery', storyCount: 134, description: 'Suspenseful and thrilling mysteries' },
      { id: 5, name: 'Horror', storyCount: 98, description: 'Dark and terrifying stories' },
      { id: 6, name: 'Adventure', storyCount: 167, description: 'Action-packed journeys and quests' },
      { id: 7, name: 'Drama', storyCount: 123, description: 'Emotional and character-driven stories' },
      { id: 8, name: 'Comedy', storyCount: 87, description: 'Light-hearted and humorous tales' },
      { id: 9, name: 'Historical', storyCount: 92, description: 'Stories set in historical periods' },
      { id: 10, name: 'Slice of Life', storyCount: 76, description: 'Realistic everyday experiences' }
    ]);
  }, []);

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              {/* Dashboard - Only visible to admins */}
              {isAdmin() && (
                <Button
                  variant="ghost"
                  onClick={() => navigate('/dashboard')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  Dashboard
                </Button>
              )}
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8 text-center">
          <div className="flex items-center justify-center mb-4">
            <BookOpen className="w-6 h-6 text-gray-400 mr-3" />
            <h2 className="text-3xl font-bold text-white">Story Genres</h2>
          </div>
          <p className="text-gray-400">Explore stories by genre</p>
        </div>

        {/* Genre Grid */}
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {genres.map((genre) => (
            <Card 
              key={genre.id} 
              className={`rounded-xl ${getPanelClasses('mainPanel')} cursor-pointer hover:bg-white/10 transition-colors group`}
              onClick={() => navigate(`/genres/${genre.name.toLowerCase()}`)}
            >
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="text-white group-hover:text-blue-400 transition-colors">
                    {genre.name}
                  </CardTitle>
                  <span className="text-sm text-gray-400 bg-white/10 px-2 py-1 rounded">
                    {genre.storyCount} stories
                  </span>
                </div>
                <CardDescription className="text-gray-400">
                  {genre.description}
                </CardDescription>
              </CardHeader>
            </Card>
          ))}
        </div>
      </main>
    </GlobalBackground>
  );
};

// Chapter Post Component for Writers
const CreateChapter = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const [chapterData, setChapterData] = useState({
    title: '',
    content: '',
    story_title: '',
    chapter_number: '',
    is_free: true,
    price: 0,
    tags: [],
    post_type: 'chapter' // New field for post type
  });
  const [availableTags, setAvailableTags] = useState([]);
  const [tagInput, setTagInput] = useState('');
  const [publishing, setPublishing] = useState(false);
  const { toast } = useToast();

  // Mock existing tags for autocomplete
  useEffect(() => {
    setAvailableTags([
      'fantasy', 'adventure', 'romance', 'magic', 'dragons', 'medieval', 'quest', 
      'friendship', 'betrayal', 'war', 'mystery', 'dark', 'comedy', 'action',
      'coming-of-age', 'epic', 'sword-and-sorcery', 'urban-fantasy', 'steampunk',
      'political-intrigue', 'redemption', 'revenge', 'prophecy', 'magic-system'
    ]);
  }, []);

  // Redirect non-writers
  if (user && user.user_type !== 'writer') {
    return <Navigate to="/" replace />;
  }

  if (!user) {
    return <Navigate to="/" replace />;
  }

  const handleTagAdd = (tag) => {
    const cleanTag = tag.trim().toLowerCase();
    if (cleanTag && 
        !chapterData.tags.includes(cleanTag) && 
        chapterData.tags.length < 10) {
      setChapterData(prev => ({
        ...prev,
        tags: [...prev.tags, cleanTag]
      }));
      setTagInput('');
    }
  };

  const handleTagRemove = (tagToRemove) => {
    setChapterData(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToRemove)
    }));
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleTagAdd(tagInput);
    }
  };

  const getPostTypeLabel = () => {
    switch (chapterData.post_type) {
      case 'chapter': return 'Chapter';
      case 'newsletter': return 'Newsletter';
      case 'general_post': return 'General Post';
      case 'update': return 'Update';
      case 'paid_content_extras': return 'Paid Content Extras';
      default: return 'Chapter';
    }
  };

  const handlePublish = async () => {
    setPublishing(true);
    try {
      // TODO: Implement chapter publishing API
      toast({
        title: "Chapter Published!",
        description: `"${chapterData.title}" has been published with ${chapterData.tags.length} tags.`,
      });
      
      // Reset form
      setChapterData({
        title: '',
        content: '',
        story_title: '',
        chapter_number: '',
        is_free: true,
        price: 0,
        tags: [],
        post_type: 'chapter'
      });
    } catch (error) {
      toast({
        title: "Publishing Error",
        description: "Failed to publish chapter. Please try again.",
        variant: "destructive",
      });
    } finally {
      setPublishing(false);
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  const filteredSuggestions = availableTags.filter(tag => 
    tag.toLowerCase().includes(tagInput.toLowerCase()) &&
    !chapterData.tags.includes(tag)
  );

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              <Button
                variant="ghost"
                onClick={() => navigate('/profile')}
                className="text-gray-300 hover:text-white hover:bg-white/10"
              >
                ← Back to Profile
              </Button>
            </div>
            <div className="flex items-center space-x-4">
              <span 
                onClick={() => navigate('/profile')}
                className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
              >
                {user.name}
              </span>
              <Button
                variant="ghost"
                onClick={handleLogout}
                className="text-gray-300 hover:text-white hover:bg-white/10"
              >
                <LogOut className="w-4 h-4" />
              </Button>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h2 className="text-3xl font-bold text-white mb-2">Create New {getPostTypeLabel()}</h2>
          <p className="text-gray-400">Share your {getPostTypeLabel().toLowerCase()} with the Queens Mountain community</p>
        </div>

        <div className="grid gap-6">
          {/* Chapter Details */}
          <Card className={`rounded-xl ${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">{getPostTypeLabel()} Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Post Type Selection */}
              <div>
                <label className="text-sm text-gray-300 mb-2 block">Post Type</label>
                <Select 
                  value={chapterData.post_type} 
                  onValueChange={(value) => setChapterData(prev => ({...prev, post_type: value}))}
                >
                  <SelectTrigger className="bg-white/5 border-white/20 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-black border-white/20">
                    <SelectItem value="chapter" className="text-white">Chapter</SelectItem>
                    <SelectItem value="newsletter" className="text-white">Newsletter</SelectItem>
                    <SelectItem value="general_post" className="text-white">General Post</SelectItem>
                    <SelectItem value="update" className="text-white">Update</SelectItem>
                    <SelectItem value="paid_content_extras" className="text-white">Paid Content Extras</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-gray-300 mb-2 block">Story Title</label>
                  <Input
                    value={chapterData.story_title}
                    onChange={(e) => setChapterData(prev => ({...prev, story_title: e.target.value}))}
                    placeholder="Enter story title"
                    className="bg-white/5 border-white/20 text-white"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-300 mb-2 block">Chapter Number</label>
                  <Input
                    type="number"
                    value={chapterData.chapter_number}
                    onChange={(e) => setChapterData(prev => ({...prev, chapter_number: e.target.value}))}
                    placeholder="1"
                    className="bg-white/5 border-white/20 text-white"
                  />
                </div>
              </div>
              
              <div>
                <label className="text-sm text-gray-300 mb-2 block">{getPostTypeLabel()} Title</label>
                <Input
                  value={chapterData.title}
                  onChange={(e) => setChapterData(prev => ({...prev, title: e.target.value}))}
                  placeholder={`Enter ${getPostTypeLabel().toLowerCase()} title`}
                  className="bg-white/5 border-white/20 text-white"
                />
              </div>
            </CardContent>
          </Card>

          {/* Story Tags */}
          <Card className={`rounded-xl ${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">Story Tags</CardTitle>
              <CardDescription className="text-gray-400">
                Add up to 10 tags to help readers discover your story. Type and press Enter to add custom tags.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Current Tags */}
              {chapterData.tags.length > 0 && (
                <div className="flex flex-wrap gap-2">
                  {chapterData.tags.map((tag, index) => (
                    <span 
                      key={index}
                      className="inline-flex items-center gap-1 bg-blue-600/20 text-blue-400 px-3 py-1 rounded-full text-sm border border-blue-500/30"
                    >
                      {tag}
                      <button
                        onClick={() => handleTagRemove(tag)}
                        className="hover:text-blue-200 ml-1"
                      >
                        ×
                      </button>
                    </span>
                  ))}
                </div>
              )}
              
              {/* Tag Input */}
              <div className="relative">
                <Input
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder={`Add a tag... (${chapterData.tags.length}/10)`}
                  className="bg-white/5 border-white/20 text-white"
                  disabled={chapterData.tags.length >= 10}
                />
                
                {/* Tag Suggestions */}
                {tagInput && filteredSuggestions.length > 0 && (
                  <div className="absolute top-full left-0 right-0 bg-black border border-white/20 rounded-md mt-1 max-h-40 overflow-y-auto z-10">
                    {filteredSuggestions.slice(0, 5).map((tag) => (
                      <button
                        key={tag}
                        onClick={() => handleTagAdd(tag)}
                        className="w-full text-left px-3 py-2 text-gray-300 hover:bg-white/10 hover:text-white"
                      >
                        {tag}
                      </button>
                    ))}
                  </div>
                )}
              </div>
              
              {/* Popular Tags */}
              <div>
                <p className="text-sm text-gray-400 mb-2">Popular tags:</p>
                <div className="flex flex-wrap gap-2">
                  {availableTags.slice(0, 8).filter(tag => !chapterData.tags.includes(tag)).map((tag) => (
                    <button
                      key={tag}
                      onClick={() => handleTagAdd(tag)}
                      className="px-2 py-1 text-xs bg-white/5 text-gray-400 hover:bg-white/10 hover:text-white rounded border border-white/10"
                      disabled={chapterData.tags.length >= 10}
                    >
                      + {tag}
                    </button>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Chapter Content */}
          <Card className={`rounded-xl ${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">Chapter Content</CardTitle>
            </CardHeader>
            <CardContent>
              <textarea
                value={chapterData.content}
                onChange={(e) => setChapterData(prev => ({...prev, content: e.target.value}))}
                placeholder="Write your chapter content here..."
                className="w-full h-64 bg-white/5 border border-white/20 text-white p-4 rounded-md resize-none"
              />
            </CardContent>
          </Card>

          {/* Pricing & Publishing */}
          <Card className={`rounded-xl ${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">Publishing Options</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center space-x-4">
                <label className="flex items-center space-x-2">
                  <input
                    type="radio"
                    checked={chapterData.is_free}
                    onChange={() => setChapterData(prev => ({...prev, is_free: true, price: 0}))}
                    className="text-blue-600"
                  />
                  <span className="text-gray-300">Free Chapter</span>
                </label>
                <label className="flex items-center space-x-2">
                  <input
                    type="radio"
                    checked={!chapterData.is_free}
                    onChange={() => setChapterData(prev => ({...prev, is_free: false}))}
                    className="text-blue-600"
                  />
                  <span className="text-gray-300">Paid Chapter</span>
                </label>
              </div>
              
              {!chapterData.is_free && (
                <div className="max-w-xs">
                  <label className="text-sm text-gray-300 mb-2 block">Price ($)</label>
                  <Input
                    type="number"
                    step="0.01"
                    min="0.50"
                    value={chapterData.price}
                    onChange={(e) => setChapterData(prev => ({...prev, price: parseFloat(e.target.value) || 0}))}
                    className="bg-white/5 border-white/20 text-white"
                  />
                </div>
              )}
              
              <div className="flex justify-end space-x-4">
                <Button
                  variant="outline"
                  onClick={() => navigate('/profile')}
                  className="border-white/30 text-white hover:bg-white/10"
                >
                  Cancel
                </Button>
                <Button
                  onClick={handlePublish}
                  disabled={publishing || !chapterData.title || !chapterData.content || !chapterData.story_title}
                  className="bg-blue-600 text-white hover:bg-blue-700"
                >
                  {publishing ? 'Publishing...' : 'Publish Chapter'}
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </main>
    </GlobalBackground>
  );
};

// Genre Stories Component
const GenreStories = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { genre } = useParams();
  const [stories, setStories] = useState([]);
  const [sortBy, setSortBy] = useState('alphabetical');
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true);
  
  const storiesPerPage = 50;
  const totalPages = Math.ceil(stories.length / storiesPerPage);
  const startIndex = (currentPage - 1) * storiesPerPage;
  const currentStories = stories.slice(startIndex, startIndex + storiesPerPage);

  // Fetch stories data from API
  useEffect(() => {
    const fetchStories = async () => {
      setLoading(true);
      try {
        const response = await axios.get(`${API}/stories?limit=50`);
        if (response.data && response.data.stories) {
          setStories(response.data.stories);
        }
      } catch (error) {
        console.error('Error fetching stories:', error);
        // Set empty array for production - no fallback mock data
        setStories([]);
      }
      setLoading(false);
    };
    
    fetchStories();
  }, [genre]);

  const sortedStories = [...stories].sort((a, b) => {
    switch(sortBy) {
      case 'alphabetical':
        return a.title.localeCompare(b.title);
      case 'rating-high':
        return b.rating - a.rating;
      case 'rating-low':
        return a.rating - b.rating;
      default:
        return 0;
    }
  });

  const displayStories = sortedStories.slice(startIndex, startIndex + storiesPerPage);

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              <Button
                variant="ghost"
                onClick={() => navigate('/genres')}
                className="text-gray-300 hover:text-white hover:bg-white/10"
              >
                ← Back to Genres
              </Button>
              {isAdmin() && (
                <Button
                  variant="ghost"
                  onClick={() => navigate('/dashboard')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  Dashboard
                </Button>
              )}
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h2 className="text-3xl font-bold text-white capitalize mb-2">{genre} Stories</h2>
          <p className="text-gray-400">Showing {displayStories.length} of {stories.length} stories</p>
        </div>

        {/* Controls */}
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center space-x-4">
            <span className="text-gray-300">Sort by:</span>
            <Select value={sortBy} onValueChange={setSortBy}>
              <SelectTrigger className="w-48 bg-white/5 border-white/20 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-black border-white/20">
                <SelectItem value="alphabetical" className="text-white">A-Z (Alphabetical)</SelectItem>
                <SelectItem value="rating-high" className="text-white">High to Low Rating</SelectItem>
                <SelectItem value="rating-low" className="text-white">Low to High Rating</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                disabled={currentPage === 1}
                className="border-white/20 text-white hover:bg-white/10"
              >
                Previous
              </Button>
              <span className="text-gray-300 px-4">
                Page {currentPage} of {totalPages}
              </span>
              <Button
                variant="outline"
                onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                disabled={currentPage === totalPages}
                className="border-white/20 text-white hover:bg-white/10"
              >
                Next
              </Button>
            </div>
          )}
        </div>

        {/* Stories Grid */}
        {loading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto"></div>
            <p className="text-gray-400 mt-4">Loading stories...</p>
          </div>
        ) : displayStories.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {displayStories.map((story) => (
              <Card 
                key={story.id} 
                className={`rounded-xl ${getPanelClasses('mainPanel')} cursor-pointer hover:bg-white/10 transition-colors group`}
                onClick={() => navigate(`/story/${story.id}`)}
              >
                <CardHeader>
                  <CardTitle className="text-white group-hover:text-blue-400 transition-colors line-clamp-2">
                    {story.title}
                  </CardTitle>
                  <CardDescription className="text-gray-400">
                    by {story.author}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <p className="text-sm text-gray-300 line-clamp-2">{story.description}</p>
                    
                    {/* Story Tags */}
                    {story.tags && (
                      <div className="flex flex-wrap gap-1">
                        {story.tags.slice(0, 4).map((tag, tagIndex) => (
                          <button
                            key={tagIndex}
                            onClick={(e) => {
                              e.stopPropagation();
                              navigate(`/search/tags/${tag}`);
                            }}
                            className="text-xs px-2 py-1 bg-blue-600/20 text-blue-400 rounded-full border border-blue-500/30 hover:bg-blue-600/30 transition-colors"
                          >
                            {tag}
                          </button>
                        ))}
                        {story.tags.length > 4 && (
                          <span className="text-xs text-gray-400 px-2 py-1">
                            +{story.tags.length - 4} more
                          </span>
                        )}
                      </div>
                    )}
                    
                    <div className="flex items-center justify-between text-sm">
                      <div className="flex items-center space-x-1">
                        <Star className="w-4 h-4 text-yellow-400 fill-current" />
                        <span className="text-white">{story.rating}</span>
                      </div>
                      <span className="text-gray-400">{story.chapters} chapters</span>
                    </div>
                    <div className="text-xs text-gray-400">
                      {story.views.toLocaleString()} views
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <BookOpen className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-xl font-semibold text-white mb-2">No stories found</h3>
            <p className="text-gray-400 mb-4">There are no stories in the {genre} genre yet.</p>
            <Button 
              onClick={() => navigate('/auth')}
              className="bg-blue-600 hover:bg-blue-700 text-white"
            >
              <PenTool className="w-4 h-4 mr-2" />
              Start Writing
            </Button>
          </div>
        )}
      </main>
    </GlobalBackground>
  );
};

// Tag Search Results Component
const TagSearchResults = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { tag } = useParams();
  const [stories, setStories] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchTagStories = async () => {
      setLoading(true);
      try {
        const response = await axios.get(`${API}/stories?limit=20`);
        if (response.data && response.data.stories) {
          // Filter stories that have the searched tag
          const filteredStories = tag ? 
            response.data.stories.filter(story => 
              story.tags && story.tags.some(storyTag => storyTag.toLowerCase().includes(tag.toLowerCase()))
            ) :
            response.data.stories;
          
          setStories(filteredStories);
        }
      } catch (error) {
        console.error('Error fetching tag stories:', error);
        // Set empty array for production - no fallback mock data
        setStories([]);
      }
      setLoading(false);
    };
    
    fetchTagStories();
  }, [tag]);

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              <Button
                variant="ghost"
                onClick={() => navigate('/')}
                className="text-gray-300 hover:text-white hover:bg-white/10"
              >
                ← Back to Search
              </Button>
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h2 className="text-3xl font-bold text-white mb-2">
            Stories tagged with "{tag}"
          </h2>
          <p className="text-gray-400">
            Found {stories.length} stories with this tag
          </p>
        </div>

        {/* Stories Results */}
        {loading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto"></div>
            <p className="text-gray-400 mt-4">Searching for stories...</p>
          </div>
        ) : stories.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {stories.map((story) => (
              <Card 
                key={story.id} 
                className={`rounded-xl ${getPanelClasses('mainPanel')} cursor-pointer hover:bg-white/10 transition-colors group`}
                onClick={() => navigate(`/story/${story.id}`)}
              >
                <CardHeader>
                  <CardTitle className="text-white group-hover:text-blue-400 transition-colors">
                    {story.title}
                  </CardTitle>
                  <CardDescription className="text-gray-400">
                    by {story.author}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <p className="text-sm text-gray-300 line-clamp-2">{story.description}</p>
                    
                    {/* Story Tags */}
                    <div className="flex flex-wrap gap-1">
                      {story.tags.slice(0, 4).map((storyTag, index) => (
                        <span 
                          key={index}
                          className={`text-xs px-2 py-1 rounded-full border ${
                            storyTag === tag 
                              ? 'bg-blue-600/30 text-blue-400 border-blue-500/50' 
                              : 'bg-white/5 text-gray-400 border-white/20'
                          }`}
                        >
                          {storyTag}
                        </span>
                      ))}
                      {story.tags.length > 4 && (
                        <span className="text-xs text-gray-400">
                          +{story.tags.length - 4} more
                        </span>
                      )}
                    </div>

                    <div className="flex items-center justify-between text-sm">
                      <div className="flex items-center space-x-1">
                        <Star className="w-4 h-4 text-yellow-400 fill-current" />
                        <span className="text-white">{story.rating}</span>
                      </div>
                      <span className="text-gray-400">{story.chapters} chapters</span>
                    </div>
                    <div className="text-xs text-gray-400">
                      {story.views.toLocaleString()} views
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <BookOpen className="w-16 h-16 text-gray-600 mx-auto mb-4" />
            <h3 className="text-xl font-semibold text-white mb-2">No stories found</h3>
            <p className="text-gray-400">
              No stories found with the tag "{tag}". Try searching for different tags.
            </p>
          </div>
        )}
      </main>
    </GlobalBackground>
  );
};

// Review Component
const Reviews = () => {
  const { user, logout, isAdmin } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const [topRatedContent, setTopRatedContent] = useState(null);
  const [showCreateReview, setShowCreateReview] = useState(false);
  const [newReview, setNewReview] = useState({
    target_type: 'writer',
    target_id: '',
    title: '',
    content: '',
    rating: 5
  });
  const { toast } = useToast();

  useEffect(() => {
    fetchTopRatedContent();
  }, []);

  const fetchTopRatedContent = async () => {
    try {
      const response = await axios.get(`${API}/reviews/top-rated`);
      setTopRatedContent(response.data);
    } catch (error) {
      console.error('Error fetching top-rated content:', error);
    }
  };

  const createReview = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`${API}/reviews`, newReview, { withCredentials: true });
      
      toast({
        title: "Review Created!",
        description: "Your review has been posted successfully.",
      });
      setShowCreateReview(false);
      setNewReview({
        target_type: 'writer',
        target_id: '',
        title: '',
        content: '',
        rating: 5
      });
      fetchTopRatedContent();
    } catch (error) {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to create review",
        variant: "destructive",
      });
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  const renderStars = (rating) => {
    return Array.from({ length: 5 }, (_, i) => (
      <Star
        key={i}
        className={`w-4 h-4 ${i < rating ? 'text-yellow-400 fill-current' : 'text-gray-400'}`}
      />
    ));
  };

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              {/* Dashboard - Only visible to admins */}
              {isAdmin() && (
                <Button
                  variant="ghost"
                  onClick={() => navigate('/dashboard')}
                  className="text-gray-300 hover:text-white hover:bg-white/10"
                >
                  Dashboard
                </Button>
              )}
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <>
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center space-x-2">
            <Star className="w-6 h-6 text-gray-400" />
            <h2 className="text-3xl font-bold text-white">Reviews & Top Rated</h2>
          </div>
          {user && user.user_type === 'reader' && (
            <Button 
              onClick={() => setShowCreateReview(true)}
              className="bg-white text-black hover:bg-gray-200"
            >
              Write Review
            </Button>
          )}
        </div>

        {!topRatedContent ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
          </div>
        ) : (
          <div className="grid lg:grid-cols-3 gap-8">
            {/* Top Writers */}
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white flex items-center gap-2">
                  <Users className="w-5 h-5" />
                  Top Rated Writers
                </CardTitle>
              </CardHeader>
              <CardContent>
                {topRatedContent.top_writers?.length > 0 ? (
                  <div className="space-y-4">
                    {topRatedContent.top_writers.slice(0, 5).map((writer, index) => (
                      <div key={writer._id} className="flex items-center justify-between p-3 bg-white/5 rounded">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center text-sm font-bold">
                            {index + 1}
                          </div>
                          <div>
                            <p className="text-white font-medium">{writer.name}</p>
                            <div className="flex items-center gap-1">
                              {renderStars(Math.round(writer.average_rating || 0))}
                              <span className="text-sm text-gray-400 ml-1">
                                ({(writer.average_rating || 0).toFixed(1)})
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-gray-400">No rated writers yet</p>
                )}
              </CardContent>
            </Card>

            {/* Top Books */}
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white flex items-center gap-2">
                  <BookOpen className="w-5 h-5" />
                  Top Rated Books
                </CardTitle>
              </CardHeader>
              <CardContent>
                {topRatedContent.top_books?.length > 0 ? (
                  <div className="space-y-4">
                    {topRatedContent.top_books.slice(0, 5).map((book, index) => (
                      <div key={book._id} className="flex items-center justify-between p-3 bg-white/5 rounded">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center text-sm font-bold">
                            {index + 1}
                          </div>
                          <div>
                            <p className="text-white font-medium">{book._id}</p>
                            <div className="flex items-center gap-1">
                              {renderStars(Math.round(book.average_rating || 0))}
                              <span className="text-sm text-gray-400 ml-1">
                                ({(book.average_rating || 0).toFixed(1)})
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-gray-400">No rated books yet</p>
                )}
              </CardContent>
            </Card>

            {/* Recent Reviews */}
            <Card className={`rounded-xl ${getPanelClasses('leftPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white flex items-center gap-2">
                  <MessageSquare className="w-5 h-5" />
                  Recent Reviews
                </CardTitle>
              </CardHeader>
              <CardContent>
                {topRatedContent.recent_reviews?.length > 0 ? (
                  <div className="space-y-4">
                    {topRatedContent.recent_reviews.slice(0, 5).map((review) => (
                      <div key={review.id} className="p-3 bg-white/5 rounded">
                        <div className="flex items-center justify-between mb-2">
                          <p className="text-white font-medium text-sm">{review.title}</p>
                          <div className="flex items-center gap-1">
                            {renderStars(review.rating)}
                          </div>
                        </div>
                        <p className="text-gray-300 text-sm line-clamp-2 mb-2">
                          {review.content}
                        </p>
                        <div className="flex justify-between items-center text-xs text-gray-400">
                          <span>By {review.reviewer_name}</span>
                          <span>{new Date(review.created_at).toLocaleDateString()}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-gray-400">No reviews yet</p>
                )}
              </CardContent>
            </Card>
          </div>
        )}

        {/* Create Review Dialog */}
        <Dialog open={showCreateReview} onOpenChange={setShowCreateReview}>
          <DialogContent className="sm:max-w-2xl bg-black border-white/20 text-white">
            <DialogHeader>
              <DialogTitle>Write a Review</DialogTitle>
              <DialogDescription className="text-gray-400">
                Share your thoughts about a writer or book
              </DialogDescription>
            </DialogHeader>
            
            <form onSubmit={createReview} className="space-y-4">
              <div>
                <Label htmlFor="target_type">Review Type</Label>
                <Select 
                  value={newReview.target_type} 
                  onValueChange={(value) => setNewReview({...newReview, target_type: value})}
                >
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-black border-white/20">
                    <SelectItem value="writer" className="text-white">Writer</SelectItem>
                    <SelectItem value="book" className="text-white">Book</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="target_id">Target ID</Label>
                <Input
                  id="target_id"
                  value={newReview.target_id}
                  onChange={(e) => setNewReview({...newReview, target_id: e.target.value})}
                  placeholder="Enter writer or book ID"
                  required
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>

              <div>
                <Label htmlFor="rating">Rating</Label>
                <Select 
                  value={newReview.rating.toString()} 
                  onValueChange={(value) => setNewReview({...newReview, rating: parseInt(value)})}
                >
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-black border-white/20">
                    {[5, 4, 3, 2, 1].map(rating => (
                      <SelectItem key={rating} value={rating.toString()} className="text-white">
                        <div className="flex items-center gap-2">
                          {renderStars(rating)}
                          <span>{rating} star{rating !== 1 ? 's' : ''}</span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <Label htmlFor="review_title">Review Title</Label>
                <Input
                  id="review_title"
                  value={newReview.title}
                  onChange={(e) => setNewReview({...newReview, title: e.target.value})}
                  placeholder="Summarize your review"
                  required
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
              
              <div>
                <Label htmlFor="review_content">Review Content</Label>
                <Textarea
                  id="review_content"
                  value={newReview.content}
                  onChange={(e) => setNewReview({...newReview, content: e.target.value})}
                  placeholder="Share your detailed thoughts..."
                  required
                  rows={6}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
              
              <DialogFooter>
                <Button type="submit" className="bg-white text-black hover:bg-gray-200">
                  Post Review
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </main>
    </GlobalBackground>
  );
};

// Contact Us Component
const ContactUs = () => {
  const { user, logout } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { toast } = useToast();

  const [contactForm, setContactForm] = useState({
    name: '',
    email: '',
    subject: '',
    message: ''
  });
  const [sending, setSending] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    
    try {
      // TODO: Implement actual email sending
      await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate sending
      
      toast({
        title: "Message Sent!",
        description: "We'll get back to you within 24 hours.",
      });
      
      setContactForm({ name: '', email: '', subject: '', message: '' });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to send message. Please try again.",
        variant: "destructive",
      });
    } finally {
      setSending(false);
    }
  };

  return (
    <GlobalBackground>
      {/* Navigation Header */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 
                className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" 
                onClick={() => navigate('/')}
              >
                Queens Mountain
              </h1>
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={logout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      <main className="min-h-screen py-12">
        <div className="max-w-4xl mx-auto px-6">
          {/* Header */}
          <div className="text-center mb-12">
            <h1 className="text-4xl font-bold text-white mb-4">Contact Us</h1>
            <p className="text-xl text-gray-400">Get in touch with the Queens Mountain team</p>
          </div>

          <div className="grid md:grid-cols-2 gap-12">
            {/* Contact Information */}
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Get in Touch</CardTitle>
                <CardDescription className="text-gray-400">
                  We'd love to hear from you. Send us a message and we'll respond as soon as possible.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="flex items-center space-x-4">
                  <div className="w-12 h-12 bg-blue-600 rounded-lg flex items-center justify-center">
                    <MessageSquare className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <h3 className="text-white font-semibold">Email Us</h3>
                    <a 
                      href="mailto:info@queensmountain.com"
                      className="text-blue-400 hover:text-blue-300 transition-colors"
                    >
                      info@queensmountain.com
                    </a>
                  </div>
                </div>

                <div className="flex items-center space-x-4">
                  <div className="w-12 h-12 bg-green-600 rounded-lg flex items-center justify-center">
                    <Clock className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <h3 className="text-white font-semibold">Response Time</h3>
                    <p className="text-gray-400">Within 24 hours</p>
                  </div>
                </div>

                <div className="flex items-center space-x-4">
                  <div className="w-12 h-12 bg-purple-600 rounded-lg flex items-center justify-center">
                    <Users className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <h3 className="text-white font-semibold">Community Support</h3>
                    <p className="text-gray-400">Join our forum for community help</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Contact Form */}
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Send a Message</CardTitle>
                <CardDescription className="text-gray-400">
                  Fill out the form below and we'll get back to you soon.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleSubmit} className="space-y-4">
                  <div>
                    <Label className="text-white">Name</Label>
                    <Input
                      value={contactForm.name}
                      onChange={(e) => setContactForm({...contactForm, name: e.target.value})}
                      className="bg-gray-800 border-gray-600 text-white"
                      required
                    />
                  </div>

                  <div>
                    <Label className="text-white">Email</Label>
                    <Input
                      type="email"
                      value={contactForm.email}
                      onChange={(e) => setContactForm({...contactForm, email: e.target.value})}
                      className="bg-gray-800 border-gray-600 text-white"
                      required
                    />
                  </div>

                  <div>
                    <Label className="text-white">Subject</Label>
                    <Input
                      value={contactForm.subject}
                      onChange={(e) => setContactForm({...contactForm, subject: e.target.value})}
                      className="bg-gray-800 border-gray-600 text-white"
                      required
                    />
                  </div>

                  <div>
                    <Label className="text-white">Message</Label>
                    <Textarea
                      value={contactForm.message}
                      onChange={(e) => setContactForm({...contactForm, message: e.target.value})}
                      className="bg-gray-800 border-gray-600 text-white min-h-[120px]"
                      required
                    />
                  </div>

                  <Button 
                    type="submit" 
                    disabled={sending}
                    className="w-full bg-blue-600 hover:bg-blue-700 text-white"
                  >
                    {sending ? 'Sending...' : 'Send Message'}
                  </Button>
                </form>
              </CardContent>
            </Card>
          </div>
        </div>
      </main>
    </GlobalBackground>
  );
};

// About Us Component - Admin Editable
const AboutUs = () => {
  const { user, logout } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { toast } = useToast();

  const [aboutData, setAboutData] = useState({
    title: 'About Queens Mountain',
    content: 'Welcome to Queens Mountain, a premium platform for writers and readers...',
    mission: 'Our mission is to connect writers and readers in meaningful ways.',
    vision: 'To become the premier storytelling platform worldwide.',
    team_info: 'Our team is passionate about literature and technology.',
    last_updated: new Date().toISOString()
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchAboutData();
  }, []);

  const fetchAboutData = async () => {
    try {
      const response = await axios.get(`${API}/admin/about-page`);
      setAboutData(response.data);
    } catch (error) {
      console.error('Error fetching about data:', error);
      // Keep default content if API fails
    } finally {
      setLoading(false);
    }
  };

  return (
    <GlobalBackground>
      {/* Navigation Header */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 
                className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" 
                onClick={() => navigate('/')}
              >
                Queens Mountain
              </h1>
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={logout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      <main className="min-h-screen py-12">
        <div className="max-w-4xl mx-auto px-6">
          {loading ? (
            <div className="text-center">
              <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white mx-auto"></div>
              <p className="mt-4 text-white">Loading...</p>
            </div>
          ) : (
            <>
              {/* Header */}
              <div className="text-center mb-12">
                <h1 className="text-4xl font-bold text-white mb-4">{aboutData.title}</h1>
                <p className="text-xl text-gray-400">Learn more about our platform and mission</p>
              </div>

              {/* About Content */}
              <div className="space-y-8">
                {/* Main Content */}
                <Card className={`${getPanelClasses('mainPanel')}`}>
                  <CardHeader>
                    <CardTitle className="text-white">Our Story</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="prose prose-invert max-w-none">
                      <p className="text-gray-300 leading-relaxed">
                        {aboutData.content}
                      </p>
                    </div>
                  </CardContent>
                </Card>

                <div className="grid md:grid-cols-2 gap-8">
                  {/* Mission */}
                  <Card className={`${getPanelClasses('mainPanel')}`}>
                    <CardHeader>
                      <CardTitle className="text-white">Our Mission</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-gray-300">
                        {aboutData.mission}
                      </p>
                    </CardContent>
                  </Card>

                  {/* Vision */}
                  <Card className={`${getPanelClasses('mainPanel')}`}>
                    <CardHeader>
                      <CardTitle className="text-white">Our Vision</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-gray-300">
                        {aboutData.vision}
                      </p>
                    </CardContent>
                  </Card>
                </div>

                {/* Team Info */}
                <Card className={`${getPanelClasses('mainPanel')}`}>
                  <CardHeader>
                    <CardTitle className="text-white">Our Team</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <p className="text-gray-300">
                      {aboutData.team_info}
                    </p>
                  </CardContent>
                </Card>

                {/* Contact CTA */}
                <Card className={`${getPanelClasses('mainPanel')} text-center`}>
                  <CardContent className="py-8">
                    <h3 className="text-2xl font-bold text-white mb-4">Get in Touch</h3>
                    <p className="text-gray-400 mb-6">
                      Have questions or want to learn more? We'd love to hear from you.
                    </p>
                    <Button 
                      onClick={() => navigate('/contact')}
                      className="bg-blue-600 hover:bg-blue-700 text-white"
                    >
                      Contact Us
                    </Button>
                  </CardContent>
                </Card>
              </div>
            </>
          )}
        </div>
      </main>
    </GlobalBackground>
  );
};

// News Page Component - Admin Editable
const NewsPage = () => {
  const { user, logout } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { toast } = useToast();

  const [newsData, setNewsData] = useState({
    title: 'Latest News',
    content: 'Stay updated with the latest news and announcements from Queens Mountain.',
    featured_article: '',
    announcements: [],
    last_updated: new Date().toISOString()
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchNewsData();
  }, []);

  const fetchNewsData = async () => {
    try {
      const response = await axios.get(`${API}/news`);
      setNewsData(response.data);
    } catch (error) {
      console.error('Error fetching news data:', error);
      // Keep default content if API fails
    } finally {
      setLoading(false);
    }
  };

  return (
    <GlobalBackground>
      {/* Navigation Header */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 
                className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" 
                onClick={() => navigate('/')}
              >
                Queens Mountain
              </h1>
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={logout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      <main className="min-h-screen py-12">
        <div className="max-w-4xl mx-auto px-6">
          {loading ? (
            <div className="text-center">
              <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white mx-auto"></div>
              <p className="mt-4 text-white">Loading...</p>
            </div>
          ) : (
            <>
              {/* Header */}
              <div className="text-center mb-12">
                <h1 className="text-4xl font-bold text-white mb-4">{newsData.title}</h1>
                <p className="text-xl text-gray-400">Stay updated with the latest from Queens Mountain</p>
              </div>

              {/* Featured Article */}
              {newsData.featured_article && (
                <Card className={`${getPanelClasses('mainPanel')} mb-8`}>
                  <CardHeader>
                    <CardTitle className="text-white">Featured</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="prose prose-invert max-w-none">
                      <p className="text-gray-300 leading-relaxed">
                        {newsData.featured_article}
                      </p>
                    </div>
                  </CardContent>
                </Card>
              )}

              <div className="space-y-8">
                {/* Main Content */}
                <Card className={`${getPanelClasses('mainPanel')}`}>
                  <CardHeader>
                    <CardTitle className="text-white">Latest Updates</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="prose prose-invert max-w-none">
                      <p className="text-gray-300 leading-relaxed">
                        {newsData.content}
                      </p>
                    </div>
                  </CardContent>
                </Card>

                {/* Announcements */}
                {newsData.announcements && newsData.announcements.length > 0 && (
                  <Card className={`${getPanelClasses('mainPanel')}`}>
                    <CardHeader>
                      <CardTitle className="text-white">Announcements</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-4">
                        {newsData.announcements.map((announcement, index) => (
                          <div key={index} className="p-4 bg-blue-600/20 rounded-lg border border-blue-600/30">
                            <div className="flex items-start space-x-3">
                              <div className="w-2 h-2 bg-blue-500 rounded-full mt-2"></div>
                              <p className="text-gray-300">{announcement}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                )}

                {/* Contact CTA */}
                <Card className={`${getPanelClasses('mainPanel')} text-center`}>
                  <CardContent className="py-8">
                    <h3 className="text-2xl font-bold text-white mb-4">Stay Connected</h3>
                    <p className="text-gray-400 mb-6">
                      Want to be the first to know about updates? Follow us or get in touch.
                    </p>
                    <div className="flex justify-center space-x-4">
                      <Button 
                        onClick={() => navigate('/contact')}
                        className="bg-blue-600 hover:bg-blue-700 text-white"
                      >
                        Contact Us
                      </Button>
                      <Button 
                        onClick={() => navigate('/about')}
                        variant="outline"
                        className="border-white/20 text-white hover:bg-white/10"
                      >
                        Learn More
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* Last Updated */}
              <div className="text-center mt-8">
                <p className="text-gray-500 text-sm">
                  Last updated: {new Date(newsData.last_updated).toLocaleDateString()}
                </p>
              </div>
            </>
          )}
        </div>
      </main>
    </GlobalBackground>
  );
};

// Writer Tiers Display Page
const WriterTiersPage = () => {
  const { user, logout } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { writerId } = useParams();
  const { toast } = useToast();
  
  const [writerData, setWriterData] = useState({
    id: 'writer-123',
    name: 'Alex Writer',
    profile_image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face',
    banner_image: 'https://images.unsplash.com/photo-1519681393784-d120d68551aa?w=1200&h=300&fit=crop',
  });
  
  const [subscriptionTiers, setSubscriptionTiers] = useState([
    {
      id: 1,
      name: 'Supporter',
      price: 3,
      description: 'Support my writing journey',
      benefits: ['Early access to chapters', 'Monthly progress updates', 'Behind-the-scenes content'],
      color: 'from-green-500 to-green-600',
      popular: false
    },
    {
      id: 2,
      name: 'Fan',
      price: 8,
      description: 'Get exclusive content and perks',
      benefits: ['All Supporter benefits', 'Exclusive bonus chapters', 'Character art and sketches', 'Monthly Q&A sessions'],
      color: 'from-blue-500 to-blue-600',
      popular: true
    },
    {
      id: 3,
      name: 'Champion',
      price: 15,
      description: 'Maximum support with premium access',
      benefits: ['All Fan benefits', 'Your name in story credits', 'Input on story direction', 'Private Discord access', 'Monthly video calls'],
      color: 'from-purple-500 to-purple-600',
      popular: false
    }
  ]);
  
  const [isSubscribing, setIsSubscribing] = useState(false);
  const [showNotificationPrefs, setShowNotificationPrefs] = useState(false);
  const [selectedTier, setSelectedTier] = useState(null);
  const [notificationPrefs, setNotificationPrefs] = useState({
    email_notifications: true,
    new_chapters: true,
    updates: true,
    newsletters: false,
    community: true,
    frequency: 'immediate' // immediate, daily, weekly
  });

  const handleSubscribe = async (tier) => {
    if (!user) {
      toast({
        title: "Login Required",
        description: "Please log in to subscribe to this writer.",
        variant: "destructive",
      });
      return;
    }

    if (user.user_type !== 'reader') {
      toast({
        title: "Reader Account Required",
        description: "Only readers can subscribe to writers.",
        variant: "destructive",
      });
      return;
    }

    // Show notification preferences modal first
    setSelectedTier(tier);
    setShowNotificationPrefs(true);
  };

  const handleConfirmSubscription = async () => {
    if (!selectedTier) return;

    setIsSubscribing(true);
    try {
      // TODO: Implement actual subscription logic with Stripe and notification preferences
      console.log('Subscribing with preferences:', {
        tier: selectedTier,
        notifications: notificationPrefs
      });
      
      toast({
        title: "Subscription Started!",
        description: `You are now subscribed to ${selectedTier.name} tier for $${selectedTier.price}/month`,
      });
      
      setShowNotificationPrefs(false);
      setSelectedTier(null);
    } catch (error) {
      toast({
        title: "Subscription Failed",
        description: "Failed to process subscription. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsSubscribing(false);
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              <Button
                variant="ghost"
                onClick={() => navigate(`/writer/${writerId}`)}
                className="text-gray-300 hover:text-white hover:bg-white/10"
              >
                ← Back to Writer Profile
              </Button>
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span 
                    onClick={() => navigate('/profile')}
                    className="text-white hover:text-blue-400 cursor-pointer transition-colors font-medium"
                  >
                    {user.name}
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Writer Header Section */}
      <div className="relative">
        {writerData.banner_image && (
          <div 
            className="h-48 bg-cover bg-center"
            style={{ backgroundImage: `url(${writerData.banner_image})` }}
          >
            <div className="absolute inset-0 bg-black/60"></div>
          </div>
        )}
        
        <div className="relative max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center space-x-6 -mt-16 pb-8">
            <img
              src={writerData.profile_image}
              alt={writerData.name}
              className="w-24 h-24 rounded-full border-4 border-white shadow-lg object-cover"
            />
            <div>
              <h1 className="text-3xl font-bold text-white">{writerData.name}</h1>
              <p className="text-lg text-gray-300 mt-1">Subscription Tiers</p>
            </div>
          </div>
        </div>
      </div>

      {/* Subscription Tiers */}
      <main className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8 text-center">
          <h2 className="text-4xl font-bold text-white mb-4">Support {writerData.name}</h2>
          <p className="text-xl text-gray-300 max-w-3xl mx-auto">
            Choose a subscription tier that works for you and get exclusive access to content, updates, and community perks.
          </p>
        </div>

        <div className="grid md:grid-cols-3 gap-8">
          {subscriptionTiers.map((tier) => (
            <div
              key={tier.id}
              className={`relative rounded-2xl overflow-hidden ${getPanelClasses('mainPanel')} ${
                tier.popular ? 'ring-2 ring-blue-500' : ''
              }`}
            >
              {tier.popular && (
                <div className="absolute top-0 left-0 right-0 bg-blue-500 text-white text-center py-2 text-sm font-semibold">
                  Most Popular
                </div>
              )}
              
              <div className={`h-24 bg-gradient-to-r ${tier.color} ${tier.popular ? 'mt-10' : ''}`}>
                <div className="absolute inset-0 bg-black/20"></div>
              </div>
              
              <div className="p-8">
                <h3 className="text-2xl font-bold text-white mb-2">{tier.name}</h3>
                <div className="flex items-baseline mb-4">
                  <span className="text-4xl font-bold text-white">${tier.price}</span>
                  <span className="text-gray-400 ml-2">/month</span>
                </div>
                <p className="text-gray-300 mb-6">{tier.description}</p>
                
                <ul className="space-y-3 mb-8">
                  {tier.benefits.map((benefit, index) => (
                    <li key={index} className="flex items-center text-gray-300">
                      <div className="w-2 h-2 bg-green-400 rounded-full mr-3 flex-shrink-0"></div>
                      {benefit}
                    </li>
                  ))}
                </ul>
                
                <Button
                  className={`w-full bg-gradient-to-r ${tier.color} hover:opacity-90 text-white font-semibold py-3`}
                  onClick={() => handleSubscribe(tier)}
                  disabled={isSubscribing}
                >
                  {isSubscribing ? (
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  ) : (
                    `Subscribe for $${tier.price}/month`
                  )}
                </Button>
              </div>
            </div>
          ))}
        </div>

        {/* Additional Information */}
        <div className="mt-12 text-center">
          <div className={`rounded-xl p-8 ${getPanelClasses('mainPanel')}`}>
            <h3 className="text-2xl font-bold text-white mb-4">Subscription Benefits</h3>
            <div className="grid md:grid-cols-3 gap-6 text-gray-300">
              <div>
                <h4 className="font-semibold text-white mb-2">Cancel Anytime</h4>
                <p>No long-term commitments. Cancel or change your subscription anytime.</p>
              </div>
              <div>
                <h4 className="font-semibold text-white mb-2">Direct Support</h4>
                <p>Your subscription directly supports the writer and helps them create more content.</p>
              </div>
              <div>
                <h4 className="font-semibold text-white mb-2">Community Access</h4>
                <p>Connect with other supporters and get closer to your favorite writer.</p>
              </div>
            </div>
          </div>
        </div>
      </main>

      {/* Notification Preferences Dialog */}
      <Dialog open={showNotificationPrefs} onOpenChange={setShowNotificationPrefs}>
        <DialogContent className="sm:max-w-md bg-black border-white/20 text-white">
          <DialogHeader>
            <DialogTitle className="text-white">
              Notification Preferences
            </DialogTitle>
            <DialogDescription className="text-gray-400">
              {selectedTier && `Subscribing to ${selectedTier.name} tier ($${selectedTier.price}/month)`}
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <Label htmlFor="email-notifications" className="text-white">Email Notifications</Label>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="email-notifications"
                  checked={notificationPrefs.email_notifications}
                  onChange={(e) => setNotificationPrefs(prev => ({
                    ...prev,
                    email_notifications: e.target.checked
                  }))}
                  className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded"
                />
              </div>
            </div>
            
            {notificationPrefs.email_notifications && (
              <div className="ml-4 space-y-3">
                <div className="flex items-center justify-between">
                  <Label htmlFor="new-chapters" className="text-gray-300 text-sm">New Chapters</Label>
                  <input
                    type="checkbox"
                    id="new-chapters"
                    checked={notificationPrefs.new_chapters}
                    onChange={(e) => setNotificationPrefs(prev => ({
                      ...prev,
                      new_chapters: e.target.checked
                    }))}
                    className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded"
                  />
                </div>
                
                <div className="flex items-center justify-between">
                  <Label htmlFor="updates" className="text-gray-300 text-sm">Writer Updates</Label>
                  <input
                    type="checkbox"
                    id="updates"
                    checked={notificationPrefs.updates}
                    onChange={(e) => setNotificationPrefs(prev => ({
                      ...prev,
                      updates: e.target.checked
                    }))}
                    className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded"
                  />
                </div>
                
                <div className="flex items-center justify-between">
                  <Label htmlFor="newsletters" className="text-gray-300 text-sm">Newsletters</Label>
                  <input
                    type="checkbox"
                    id="newsletters"
                    checked={notificationPrefs.newsletters}
                    onChange={(e) => setNotificationPrefs(prev => ({
                      ...prev,
                      newsletters: e.target.checked
                    }))}
                    className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded"
                  />
                </div>
                
                <div className="flex items-center justify-between">
                  <Label htmlFor="community" className="text-gray-300 text-sm">Community Activity</Label>
                  <input
                    type="checkbox"
                    id="community"
                    checked={notificationPrefs.community}
                    onChange={(e) => setNotificationPrefs(prev => ({
                      ...prev,
                      community: e.target.checked
                    }))}
                    className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded"
                  />
                </div>
                
                <div>
                  <Label className="text-gray-300 text-sm block mb-2">Email Frequency</Label>
                  <Select 
                    value={notificationPrefs.frequency} 
                    onValueChange={(value) => setNotificationPrefs(prev => ({...prev, frequency: value}))}
                  >
                    <SelectTrigger className="bg-white/10 border-white/20 text-white">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="bg-black border-white/20">
                      <SelectItem value="immediate" className="text-white">Immediate</SelectItem>
                      <SelectItem value="daily" className="text-white">Daily Digest</SelectItem>
                      <SelectItem value="weekly" className="text-white">Weekly Summary</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}
            
            <div className="flex items-center justify-between">
              <Label className="text-white">In-App Notifications</Label>
              <span className="text-green-400 text-sm">Always Enabled</span>
            </div>
          </div>
          
          <DialogFooter className="flex gap-2">
            <Button
              variant="ghost"
              onClick={() => setShowNotificationPrefs(false)}
              className="text-gray-300 hover:text-white"
            >
              Cancel
            </Button>
            <Button
              onClick={handleConfirmSubscription}
              disabled={isSubscribing}
              className="bg-blue-600 hover:bg-blue-700 text-white"
            >
              {isSubscribing ? (
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
              ) : (
                `Subscribe for $${selectedTier?.price}/month`
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </GlobalBackground>
  );
};

// Writer Subscribe Page - Payment Integration
const WriterSubscribePage = () => {
  const { user } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const location = useLocation();
  const { writerId } = useParams();
  const { toast } = useToast();

  const [writerData, setWriterData] = useState({
    id: writerId || 'writer-123',
    name: 'Alex Writer',
    profile_image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face',
    banner_image: 'https://images.unsplash.com/photo-1519681393784-d120d68551aa?w=1200&h=300&fit=crop',
  });

  const [subscriptionTiers, setSubscriptionTiers] = useState([
    {
      id: 'sub_tier_1',
      name: 'Supporter',
      price: 300, // in cents
      description: 'Support my writing journey',
      benefits: ['Early access to chapters', 'Monthly progress updates', 'Behind-the-scenes content'],
      popular: false
    },
    {
      id: 'sub_tier_2', 
      name: 'Fan',
      price: 800, // in cents
      description: 'Get exclusive content and perks',
      benefits: ['All Supporter benefits', 'Exclusive bonus chapters', 'Character art and sketches', 'Monthly Q&A sessions'],
      popular: true
    },
    {
      id: 'sub_tier_3',
      name: 'Champion', 
      price: 1500, // in cents
      description: 'Maximum support with premium access',
      benefits: ['All Fan benefits', 'Your name in story credits', 'Input on story direction', 'Private Discord access', 'Monthly video calls'],
      popular: false
    }
  ]);

  const [tipAmount, setTipAmount] = useState('');
  const [showTipModal, setShowTipModal] = useState(false);
  const [selectedTier, setSelectedTier] = useState(
    location.state?.selectedTier || subscriptionTiers[1] // Default to Fan tier
  );

  // Check if user is logged in and is a reader
  useEffect(() => {
    if (!user) {
      toast({
        title: "Authentication Required",
        description: "Please log in to subscribe to this writer.",
        variant: "destructive",
      });
      navigate('/');
      return;
    }

    if (user.user_type !== 'reader') {
      toast({
        title: "Reader Account Required",
        description: "Only reader accounts can subscribe to writers.",
        variant: "destructive",
      });
      navigate('/');
      return;
    }
  }, [user, navigate, toast]);

  const handleSubscriptionPayment = (tier) => {
    // The PaymentButton component will handle the actual payment flow
    console.log(`Subscribing to ${tier.name} for ${tier.price} cents`);
  };

  const handleTipPayment = () => {
    if (!tipAmount || parseFloat(tipAmount) < 1) {
      toast({
        title: "Invalid Amount",
        description: "Tip amount must be at least $1.00",
        variant: "destructive",
      });
      return;
    }

    // Convert to cents for payment processing
    const amountInCents = Math.round(parseFloat(tipAmount) * 100);
    console.log(`Sending tip of ${amountInCents} cents`);
    setShowTipModal(false);
  };

  if (!user || user.user_type !== 'reader') {
    return null; // Will redirect in useEffect
  }

  return (
    <GlobalBackground>
      <main className="min-h-screen">
        {/* Header */}
        <div className="bg-gradient-to-r from-gray-900 to-black border-b border-white/10">
          <div className="max-w-4xl mx-auto px-6 py-8">
            <Button 
              variant="ghost" 
              className="text-gray-400 hover:text-white mb-6"
              onClick={() => navigate(`/writer/${writerId}`)}
            >
              ← Back to {writerData.name}'s Profile
            </Button>
            
            <div className="flex items-center space-x-4 mb-6">
              <img
                src={writerData.profile_image}
                alt={writerData.name}
                className="w-16 h-16 rounded-full object-cover"
              />
              <div>
                <h1 className="text-3xl font-bold text-white">Support {writerData.name}</h1>
                <p className="text-gray-400">Choose your support level</p>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="max-w-4xl mx-auto px-6 py-8">
          <div className="grid md:grid-cols-2 gap-8">
            
            {/* Subscription Tiers */}
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold text-white mb-2">Monthly Subscriptions</h2>
                <p className="text-gray-400">Recurring support with exclusive perks</p>
              </div>

              <div className="space-y-4">
                {subscriptionTiers.map((tier) => (
                  <Card 
                    key={tier.id} 
                    className={`${getPanelClasses('mainPanel')} ${
                      tier.popular ? 'ring-2 ring-orange-500' : ''
                    } relative overflow-hidden`}
                  >
                    {tier.popular && (
                      <div className="absolute top-0 right-0 bg-orange-500 text-white px-3 py-1 text-xs font-bold">
                        MOST POPULAR
                      </div>
                    )}
                    
                    <CardContent className="p-6">
                      <div className="flex justify-between items-start mb-4">
                        <div>
                          <h3 className="text-xl font-bold text-white">{tier.name}</h3>
                          <p className="text-gray-400 text-sm">{tier.description}</p>
                        </div>
                        <div className="text-right">
                          <div className="text-2xl font-bold text-white">
                            ${(tier.price / 100).toFixed(2)}
                          </div>
                          <div className="text-sm text-gray-400">per month</div>
                        </div>
                      </div>

                      <div className="space-y-2 mb-6">
                        {tier.benefits.map((benefit, index) => (
                          <div key={index} className="flex items-center space-x-2">
                            <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                            <span className="text-gray-300 text-sm">{benefit}</span>
                          </div>
                        ))}
                      </div>

                      <PaymentButton
                        packageId="subscription"
                        targetId={writerId}
                        buttonText={`Subscribe for $${(tier.price / 100).toFixed(2)}/month`}
                        className={`w-full ${
                          tier.popular 
                            ? 'bg-orange-500 hover:bg-orange-600' 
                            : 'bg-blue-600 hover:bg-blue-700'
                        } text-white`}
                        icon={Crown}
                      />
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>

            {/* One-time Support */}
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold text-white mb-2">One-time Support</h2>
                <p className="text-gray-400">Send a tip to show your appreciation</p>
              </div>

              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardContent className="p-6">
                  <div className="grid grid-cols-2 gap-3 mb-6">
                    {[3, 5, 10, 25].map((amount) => (
                      <TipWriter
                        key={amount}
                        amount={amount}
                        targetId={writerId}
                        buttonText={`$${amount}`}
                        className="bg-green-600 hover:bg-green-700 text-white"
                      />
                    ))}
                  </div>

                  <div className="border-t border-gray-700 pt-4">
                    <Button
                      variant="outline"
                      className="w-full border-gray-600 text-white hover:bg-gray-700"
                      onClick={() => setShowTipModal(true)}
                    >
                      Custom Amount
                    </Button>
                  </div>
                </CardContent>
              </Card>

              {/* Support Benefits */}
              <Card className={`${getPanelClasses('mainPanel')}`}>
                <CardHeader>
                  <CardTitle className="text-white">Why Support?</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex items-center space-x-3">
                    <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                    <span className="text-gray-300 text-sm">Help fund more amazing stories</span>
                  </div>
                  <div className="flex items-center space-x-3">
                    <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                    <span className="text-gray-300 text-sm">Enable the writer to focus on creating</span>
                  </div>
                  <div className="flex items-center space-x-3">
                    <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                    <span className="text-gray-300 text-sm">Join a supportive community of readers</span>
                  </div>
                  <div className="flex items-center space-x-3">
                    <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                    <span className="text-gray-300 text-sm">Get exclusive access to new content</span>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>

        {/* Custom Tip Modal */}
        <Dialog open={showTipModal} onOpenChange={setShowTipModal}>
          <DialogContent className="sm:max-w-md bg-black border-white/20 text-white">
            <DialogHeader>
              <DialogTitle className="text-white">Send Custom Tip</DialogTitle>
              <DialogDescription className="text-gray-400">
                Enter the amount you'd like to tip {writerData.name}
              </DialogDescription>
            </DialogHeader>
            
            <div className="space-y-4">
              <div>
                <Label htmlFor="tip-amount" className="text-white">Amount (USD)</Label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">$</span>
                  <Input
                    id="tip-amount"
                    type="number"
                    min="1"
                    step="0.01"
                    value={tipAmount}
                    onChange={(e) => setTipAmount(e.target.value)}
                    className="bg-gray-800 border-gray-600 text-white pl-8"
                    placeholder="0.00"
                  />
                </div>
              </div>
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => setShowTipModal(false)}>
                Cancel
              </Button>
              <TipWriter
                amount={tipAmount ? parseFloat(tipAmount) : 0}
                targetId={writerId}
                buttonText={`Send $${tipAmount || '0.00'} Tip`}
                className="bg-green-600 hover:bg-green-700 text-white"
                disabled={!tipAmount || parseFloat(tipAmount) < 1}
              />
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </main>
    </GlobalBackground>
  );
};

// Admin Dashboard Component
const AdminDashboard = () => {
  const { user, logout, loading: authLoading } = React.useContext(AuthContext);
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const navigate = useNavigate();
  const { toast } = useToast();
  
  const [activeTab, setActiveTab] = useState('overview');
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedUser, setSelectedUser] = useState(null);
  const [showUserModal, setShowUserModal] = useState(false);
  const [userFilter, setUserFilter] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');

  // Admin stats - will be fetched from API, start clean for production
  const [adminStats, setAdminStats] = useState({
    totalUsers: 0,
    activeUsers: 0,
    newUsersThisMonth: 0,
    totalEarnings: 0.0,
    totalPosts: 0,
    totalStories: 0,
    reportedContent: 0,
    pendingReviews: 0
  });

  const [recentUsers, setRecentUsers] = useState([
    {
      id: 1,
      name: 'Sarah Mitchell',
      email: 'sarah.mitchell@email.com',
      user_type: 'reader',
      status: 'active',
      joined: '2024-01-15',
      last_active: '2 hours ago',
      avatar: 'SM',
      subscription_count: 0,
      total_spent: 45.50
    },
    {
      id: 2,
      name: 'Alex Writer',
      email: 'alex.writer@email.com',
      user_type: 'writer',
      status: 'active',
      joined: '2023-03-15',
      last_active: '1 day ago',
      avatar: 'AW',
      subscriber_count: 1247,
      monthly_earnings: 890.25
    },
    {
      id: 3,
      name: 'Jake Davis',
      email: 'jake.davis@email.com',
      user_type: 'reader',
      status: 'suspended',
      joined: '2024-02-20',
      last_active: '1 week ago',
      avatar: 'JD',
      subscription_count: 3,
      total_spent: 156.00
    },
    {
      id: 4,
      name: 'Emma Lopez',
      email: 'emma.lopez@email.com',
      user_type: 'writer',
      status: 'pending',
      joined: '2024-03-01',
      last_active: '3 days ago',
      avatar: 'EL',
      subscriber_count: 0,
      monthly_earnings: 0
    }
  ]);

  // Check admin permissions - wait for auth to complete
  useEffect(() => {
    if (authLoading) return; // Wait for authentication to complete
    
    if (!user || user.user_type !== 'admin') {
      toast({
        title: "Access Denied",
        description: "Admin privileges required to access this page.",
        variant: "destructive",
      });
      navigate('/');
      return;
    }
    
    // Load admin data
    loadAdminData();
  }, [user, navigate, authLoading]);

  const loadAdminData = async () => {
    setLoading(false); // Remove loading delay for immediate access
    try {
      // Fetch admin stats from API
      const statsResponse = await axios.get(`${API}/stats`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      
      if (statsResponse.data) {
        setAdminStats(statsResponse.data);
      }
      
      // TODO: Replace with actual API calls for users
      setUsers(recentUsers);
    } catch (error) {
      console.error('Error loading admin data:', error);
      toast({
        title: "Error",
        description: "Failed to load admin data.",
        variant: "destructive",
      });
      
      // Set clean production stats on error
      setAdminStats({
        totalUsers: 0,
        activeUsers: 0,
        newUsersThisMonth: 0,
        totalEarnings: 0.0,
        totalPosts: 0,
        totalStories: 0,
        reportedContent: 0,
        pendingReviews: 0
      });
    }
  };

  const handleUserAction = async (userId, action) => {
    try {
      // TODO: Implement actual API calls
      let message = '';
      switch (action) {
        case 'suspend':
          message = 'User suspended successfully';
          setUsers(prev => prev.map(user => 
            user.id === userId ? { ...user, status: 'suspended' } : user
          ));
          break;
        case 'activate':
          message = 'User activated successfully';
          setUsers(prev => prev.map(user => 
            user.id === userId ? { ...user, status: 'active' } : user
          ));
          break;
        case 'delete':
          message = 'User deleted successfully';
          setUsers(prev => prev.filter(user => user.id !== userId));
          break;
        default:
          message = 'Action completed';
      }
      
      toast({
        title: "Success",
        description: message,
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to perform action.",
        variant: "destructive",
      });
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  const filteredUsers = users.filter(user => {
    const matchesFilter = userFilter === 'all' || user.user_type === userFilter || user.status === userFilter;
    const matchesSearch = user.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         user.email.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesFilter && matchesSearch;
  });

  if (authLoading) {
    return (
      <GlobalBackground className="bg-black text-white">
        <div className="flex items-center justify-center min-h-screen">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white"></div>
          <p className="ml-3 text-white">Authenticating...</p>
        </div>
      </GlobalBackground>
    );
  }

  if (loading) {
    return (
      <GlobalBackground className="bg-black text-white">
        <div className="flex items-center justify-center min-h-screen">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white"></div>
        </div>
      </GlobalBackground>
    );
  }

  return (
    <GlobalBackground className="bg-black text-white">
      {/* Admin Navigation */}
      <nav className="bg-black/90 backdrop-blur-md border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <h1 className="text-2xl font-bold text-white cursor-pointer hover:text-gray-300 transition-colors" onClick={() => navigate('/')}>
                Queens Mountain
              </h1>
              <div className="bg-red-600 text-white text-xs px-2 py-1 rounded">
                ADMIN PANEL
              </div>
            </div>
            <div className="flex items-center space-x-4">
              {user && (
                <div className="flex items-center space-x-4">
                  <span className="text-white font-medium">
                    {user.name} (Admin)
                  </span>
                  <Button
                    variant="ghost"
                    onClick={handleLogout}
                    className="text-gray-300 hover:text-white hover:bg-white/10"
                  >
                    <LogOut className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      <div className="max-w-7xl mx-auto px-6 py-8">
        {/* Admin Dashboard Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">Admin Dashboard</h1>
          <p className="text-gray-400">Manage users, moderate content, and oversee platform operations</p>
        </div>

        {/* Admin Stats Cards */}
        <div className="grid md:grid-cols-4 gap-6 mb-8">
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Total Users</p>
                  <p className="text-3xl font-bold text-white">{adminStats.totalUsers.toLocaleString()}</p>
                  <p className="text-green-400 text-xs mt-1">+{adminStats.newUsersThisMonth} this month</p>
                </div>
                <Users className="w-8 h-8 text-blue-400" />
              </div>
            </CardContent>
          </Card>

          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Active Users</p>
                  <p className="text-3xl font-bold text-green-400">{adminStats.activeUsers.toLocaleString()}</p>
                  <p className="text-gray-400 text-xs mt-1">70% of total</p>
                </div>
                <div className="text-green-400">🟢</div>
              </div>
            </CardContent>
          </Card>

          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Platform Revenue</p>
                  <p className="text-3xl font-bold text-yellow-400">${adminStats.totalEarnings.toLocaleString()}</p>
                  <p className="text-green-400 text-xs mt-1">+12.5% this month</p>
                </div>
                <div className="text-yellow-400">💰</div>
              </div>
            </CardContent>
          </Card>

          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-400 text-sm">Content Reports</p>
                  <p className="text-3xl font-bold text-red-400">{adminStats.reportedContent}</p>
                  <p className="text-red-400 text-xs mt-1">Requires attention</p>
                </div>
                <div className="text-red-400">⚠️</div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Admin Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList className="bg-gray-800/50 border border-gray-700">
            <TabsTrigger value="overview" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Overview
            </TabsTrigger>
            <TabsTrigger value="users" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              User Management
            </TabsTrigger>
            <TabsTrigger value="content" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Content Moderation
            </TabsTrigger>
            <TabsTrigger value="analytics" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Analytics
            </TabsTrigger>
            <TabsTrigger value="settings" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Platform Settings
            </TabsTrigger>
            <TabsTrigger value="pages" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Page Editor
            </TabsTrigger>
          </TabsList>

          {/* Overview Tab */}
          <TabsContent value="overview">
            <AdminOverviewTab />
          </TabsContent>

          {/* User Management Tab */}
          <TabsContent value="users">
            <UserManagementTab />
          </TabsContent>

          {/* Content Moderation Tab */}
          <TabsContent value="content">
            <ContentModerationTab />
          </TabsContent>

          {/* Analytics Tab */}
          <TabsContent value="analytics">
            <AnalyticsTab />
          </TabsContent>

          {/* Platform Settings Tab */}
          <TabsContent value="settings">
            <PlatformSettingsTab />
          </TabsContent>

          {/* Page Editor Tab */}
          <TabsContent value="pages">
            <PageEditorTab />
          </TabsContent>
        </Tabs>
      </div>

      {/* User Details Modal */}
      <Dialog open={showUserModal} onOpenChange={setShowUserModal}>
        <DialogContent className="sm:max-w-lg bg-black border-white/20 text-white">
          <DialogHeader>
            <DialogTitle className="text-white">User Details</DialogTitle>
          </DialogHeader>
          {selectedUser && (
            <div className="space-y-4">
              <div className="flex items-center space-x-4">
                <div className="w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center">
                  <span className="text-white font-bold text-lg">{selectedUser.avatar}</span>
                </div>
                <div>
                  <h3 className="text-white font-bold text-lg">{selectedUser.name}</h3>
                  <p className="text-gray-400">{selectedUser.email}</p>
                  <div className="flex items-center space-x-2 mt-1">
                    <span className={`px-2 py-1 rounded text-xs ${
                      selectedUser.status === 'active' ? 'bg-green-600' :
                      selectedUser.status === 'suspended' ? 'bg-red-600' : 'bg-yellow-600'
                    }`}>
                      {selectedUser.status.charAt(0).toUpperCase() + selectedUser.status.slice(1)}
                    </span>
                    <span className="text-gray-400 text-xs">
                      {selectedUser.user_type.charAt(0).toUpperCase() + selectedUser.user_type.slice(1)}
                    </span>
                  </div>
                </div>
              </div>
              
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <p className="text-gray-400">Joined</p>
                  <p className="text-white">{selectedUser.joined}</p>
                </div>
                <div>
                  <p className="text-gray-400">Last Active</p>
                  <p className="text-white">{selectedUser.last_active}</p>
                </div>
                {selectedUser.user_type === 'writer' ? (
                  <>
                    <div>
                      <p className="text-gray-400">Subscribers</p>
                      <p className="text-white">{selectedUser.subscriber_count}</p>
                    </div>
                    <div>
                      <p className="text-gray-400">Monthly Earnings</p>
                      <p className="text-green-400">${selectedUser.monthly_earnings}</p>
                    </div>
                  </>
                ) : (
                  <>
                    <div>
                      <p className="text-gray-400">Subscriptions</p>
                      <p className="text-white">{selectedUser.subscription_count}</p>
                    </div>
                    <div>
                      <p className="text-gray-400">Total Spent</p>
                      <p className="text-green-400">${selectedUser.total_spent}</p>
                    </div>
                  </>
                )}
              </div>

              <div className="flex justify-end space-x-2 pt-4">
                {selectedUser.status === 'active' ? (
                  <Button
                    variant="outline"
                    onClick={() => handleUserAction(selectedUser.id, 'suspend')}
                    className="border-red-400 text-red-400 hover:bg-red-400/10"
                  >
                    Suspend User
                  </Button>
                ) : (
                  <Button
                    variant="outline"
                    onClick={() => handleUserAction(selectedUser.id, 'activate')}
                    className="border-green-400 text-green-400 hover:bg-green-400/10"
                  >
                    Activate User
                  </Button>
                )}
                <Button
                  variant="outline"
                  onClick={() => handleUserAction(selectedUser.id, 'delete')}
                  className="border-red-400 text-red-400 hover:bg-red-400/10"
                >
                  Delete User
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </GlobalBackground>
  );

  // Admin Overview Tab
  function AdminOverviewTab() {
    return (
      <div className="grid lg:grid-cols-2 gap-6">
        {/* System Health */}
        <Card className={`${getPanelClasses('mainPanel')}`}>
          <CardHeader>
            <CardTitle className="text-white">System Health</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {[
              { name: 'Server Status', status: 'Online', color: 'text-green-400' },
              { name: 'Database', status: 'Healthy', color: 'text-green-400' },
              { name: 'Payment System', status: 'Operational', color: 'text-green-400' },
              { name: 'File Storage', status: 'Warning', color: 'text-yellow-400' }
            ].map((item, index) => (
              <div key={index} className="flex items-center justify-between">
                <span className="text-gray-300">{item.name}</span>
                <span className={`font-semibold ${item.color}`}>{item.status}</span>
              </div>
            ))}
          </CardContent>
        </Card>

        {/* Recent Admin Actions */}
        <Card className={`${getPanelClasses('mainPanel')}`}>
          <CardHeader>
            <CardTitle className="text-white">Recent Admin Actions</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {[
              { action: 'User suspended: jake.davis@email.com', time: '2 hours ago', admin: 'Admin' },
              { action: 'Content flagged as inappropriate', time: '4 hours ago', admin: 'Auto-Mod' },
              { action: 'New writer approved: emma.lopez', time: '1 day ago', admin: 'Admin' },
              { action: 'Platform maintenance completed', time: '2 days ago', admin: 'System' }
            ].map((item, index) => (
              <div key={index} className="border-l-2 border-blue-500 pl-3">
                <p className="text-white text-sm">{item.action}</p>
                <div className="flex items-center space-x-2 text-xs text-gray-400 mt-1">
                  <span>{item.time}</span>
                  <span>•</span>
                  <span>by {item.admin}</span>
                </div>
              </div>
            ))}
          </CardContent>
        </Card>

        {/* Quick Actions */}
        <Card className={`${getPanelClasses('mainPanel')} lg:col-span-2`}>
          <CardHeader>
            <CardTitle className="text-white">Quick Admin Actions</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-4 gap-4">
              <Button className="bg-blue-600 hover:bg-blue-700 text-white h-16 flex flex-col items-center justify-center">
                <Users className="w-6 h-6 mb-1" />
                <span className="text-sm">Manage Users</span>
              </Button>
              <Button className="bg-purple-600 hover:bg-purple-700 text-white h-16 flex flex-col items-center justify-center">
                <BookOpen className="w-6 h-6 mb-1" />
                <span className="text-sm">Review Content</span>
              </Button>
              <Button className="bg-green-600 hover:bg-green-700 text-white h-16 flex flex-col items-center justify-center">
                <TrendingUp className="w-6 h-6 mb-1" />
                <span className="text-sm">View Analytics</span>
              </Button>
              <Button className="bg-orange-600 hover:bg-orange-700 text-white h-16 flex flex-col items-center justify-center">
                <Settings className="w-6 h-6 mb-1" />
                <span className="text-sm">Site Settings</span>
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  // User Management Tab
  function UserManagementTab() {
    return (
      <div className="space-y-6">
        {/* User Management Header */}
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <div>
            <h2 className="text-2xl font-bold text-white">User Management</h2>
            <p className="text-gray-400">View, search, and manage all platform users</p>
          </div>
          <div className="flex items-center space-x-3">
            <Select value={userFilter} onValueChange={setUserFilter}>
              <SelectTrigger className="w-40 bg-gray-800 border-gray-600 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-gray-800 border-gray-600">
                <SelectItem value="all" className="text-white">All Users</SelectItem>
                <SelectItem value="reader" className="text-white">Readers</SelectItem>
                <SelectItem value="writer" className="text-white">Writers</SelectItem>
                <SelectItem value="active" className="text-white">Active</SelectItem>
                <SelectItem value="suspended" className="text-white">Suspended</SelectItem>
              </SelectContent>
            </Select>
            <Input
              placeholder="Search users..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-64 bg-gray-800 border-gray-600 text-white"
            />
          </div>
        </div>

        {/* Users Table */}
        <Card className={`${getPanelClasses('mainPanel')}`}>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-800/50 border-b border-gray-700">
                  <tr>
                    <th className="text-left p-4 text-gray-300 font-semibold">User</th>
                    <th className="text-left p-4 text-gray-300 font-semibold">Type</th>
                    <th className="text-left p-4 text-gray-300 font-semibold">Status</th>
                    <th className="text-left p-4 text-gray-300 font-semibold">Joined</th>
                    <th className="text-left p-4 text-gray-300 font-semibold">Activity</th>
                    <th className="text-left p-4 text-gray-300 font-semibold">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredUsers.map((user) => (
                    <tr key={user.id} className="border-b border-gray-700 hover:bg-gray-800/30">
                      <td className="p-4">
                        <div className="flex items-center space-x-3">
                          <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center">
                            <span className="text-white font-semibold text-sm">{user.avatar}</span>
                          </div>
                          <div>
                            <p className="text-white font-medium">{user.name}</p>
                            <p className="text-gray-400 text-sm">{user.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="p-4">
                        <span className={`px-2 py-1 rounded text-xs ${
                          user.user_type === 'writer' ? 'bg-purple-600' : 'bg-blue-600'
                        }`}>
                          {user.user_type.charAt(0).toUpperCase() + user.user_type.slice(1)}
                        </span>
                      </td>
                      <td className="p-4">
                        <span className={`px-2 py-1 rounded text-xs ${
                          user.status === 'active' ? 'bg-green-600' :
                          user.status === 'suspended' ? 'bg-red-600' : 'bg-yellow-600'
                        }`}>
                          {user.status.charAt(0).toUpperCase() + user.status.slice(1)}
                        </span>
                      </td>
                      <td className="p-4 text-gray-300">{user.joined}</td>
                      <td className="p-4 text-gray-300">{user.last_active}</td>
                      <td className="p-4">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedUser(user);
                            setShowUserModal(true);
                          }}
                          className="text-blue-400 hover:text-white hover:bg-blue-600/20"
                        >
                          View Details
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Content Moderation Tab
  function ContentModerationTab() {
    const [moderationFilter, setModerationFilter] = useState('pending');
    const [reportedContent, setReportedContent] = useState([
      {
        id: 1,
        content_type: 'post',
        title: 'Chapter 15: The Dark Forest',
        author: 'Jake Davis',
        author_email: 'jake.davis@email.com',
        reported_by: 'Sarah Mitchell',
        report_reason: 'Inappropriate content',
        report_details: 'Contains graphic violence that exceeds platform guidelines',
        status: 'pending',
        created_at: '2024-01-15T10:30:00Z',
        priority: 'high'
      },
      {
        id: 2,
        content_type: 'comment',
        title: 'Comment on "Love in the Library"',
        author: 'Mike Johnson',
        author_email: 'mike.j@email.com',
        reported_by: 'Emma Lopez',
        report_reason: 'Harassment',
        report_details: 'User is targeting the author with repeated negative comments',
        status: 'pending',
        created_at: '2024-01-14T15:45:00Z',
        priority: 'medium'
      },
      {
        id: 3,
        content_type: 'post',
        title: 'My Writing Journey - Blog Post',
        author: 'Alex Writer',
        author_email: 'alex.writer@email.com',
        reported_by: 'System Auto-Mod',
        report_reason: 'Spam detection',
        report_details: 'Auto-detected: Excessive external links and promotional content',
        status: 'reviewed',
        created_at: '2024-01-13T09:20:00Z',
        priority: 'low'
      }
    ]);

    const [autoModerationSettings, setAutoModerationSettings] = useState({
      enabled: true,
      spam_detection: true,
      profanity_filter: true,
      adult_content_detection: true,
      external_link_limit: 5,
      auto_flag_threshold: 3,
      auto_action_enabled: false,
      banned_words: 'spam, scam, fake, illegal',
      whitelist_domains: 'queensmountain.com, twitter.com, instagram.com'
    });

    const handleModerationAction = async (contentId, action) => {
      try {
        // TODO: Implement actual API calls
        let message = '';
        switch (action) {
          case 'approve':
            message = 'Content approved and published';
            setReportedContent(prev => prev.map(item => 
              item.id === contentId ? { ...item, status: 'approved' } : item
            ));
            break;
          case 'reject':
            message = 'Content rejected and removed';
            setReportedContent(prev => prev.map(item => 
              item.id === contentId ? { ...item, status: 'rejected' } : item
            ));
            break;
          case 'warning':
            message = 'Warning sent to author';
            setReportedContent(prev => prev.map(item => 
              item.id === contentId ? { ...item, status: 'warning_sent' } : item
            ));
            break;
          default:
            message = 'Action completed';
        }
        
        toast({
          title: "Moderation Action Complete",
          description: message,
        });
      } catch (error) {
        toast({
          title: "Error",
          description: "Failed to perform moderation action.",
          variant: "destructive",
        });
      }
    };

    const handleAutoModSettingChange = (key, value) => {
      setAutoModerationSettings(prev => ({
        ...prev,
        [key]: value
      }));
    };

    const saveAutoModerationSettings = async () => {
      try {
        // Save auto-moderation settings to the site-settings endpoint
        const response = await axios.put(`${API}/admin/site-settings`, {
          auto_moderation_enabled: autoModerationSettings.enabled,
          spam_detection: autoModerationSettings.spam_detection,
          profanity_filter: autoModerationSettings.profanity_filter,
          adult_content_detection: autoModerationSettings.adult_content_detection,
          external_link_limit: autoModerationSettings.external_link_limit,
          auto_flag_threshold: autoModerationSettings.auto_flag_threshold,
          auto_action_enabled: autoModerationSettings.auto_action_enabled,
          banned_words: autoModerationSettings.banned_words,
          whitelist_domains: autoModerationSettings.whitelist_domains
        });
        
        toast({
          title: "Settings Saved",
          description: "Auto-moderation settings have been updated.",
        });
      } catch (error) {
        console.error('Auto-moderation settings save error:', error);
        toast({
          title: "Error",
          description: "Failed to save moderation settings.",
          variant: "destructive",
        });
      }
    };

    const filteredReports = reportedContent.filter(item => {
      if (moderationFilter === 'all') return true;
      return item.status === moderationFilter;
    });

    return (
      <div className="space-y-6">
        {/* Content Moderation Header */}
        <div>
          <h2 className="text-2xl font-bold text-white">Content Moderation</h2>
          <p className="text-gray-400">Review reported content and manage platform moderation policies</p>
        </div>

        {/* Moderation Tabs */}
        <Tabs defaultValue="reports" className="space-y-6">
          <TabsList className="bg-gray-800/50 border border-gray-700">
            <TabsTrigger value="reports" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Content Reports
            </TabsTrigger>
            <TabsTrigger value="automod" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Auto-Moderation
            </TabsTrigger>
            <TabsTrigger value="policies" className="text-gray-300 data-[state=active]:bg-red-600 data-[state=active]:text-white">
              Moderation Policies
            </TabsTrigger>
          </TabsList>

          {/* Content Reports Tab */}
          <TabsContent value="reports" className="space-y-6">
            {/* Reports Filter */}
            <div className="flex justify-between items-center">
              <div>
                <h3 className="text-xl font-bold text-white">Reported Content Queue</h3>
                <p className="text-gray-400">Review and take action on reported content</p>
              </div>
              <Select value={moderationFilter} onValueChange={setModerationFilter}>
                <SelectTrigger className="w-48 bg-gray-800 border-gray-600 text-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-gray-800 border-gray-600">
                  <SelectItem value="all" className="text-white">All Reports</SelectItem>
                  <SelectItem value="pending" className="text-white">Pending Review</SelectItem>
                  <SelectItem value="approved" className="text-white">Approved</SelectItem>
                  <SelectItem value="rejected" className="text-white">Rejected</SelectItem>
                  <SelectItem value="warning_sent" className="text-white">Warning Sent</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Reports List */}
            <div className="space-y-4">
              {filteredReports.map((report) => (
                <Card key={report.id} className={`${getPanelClasses('mainPanel')} ${
                  report.priority === 'high' ? 'border-l-4 border-l-red-500' :
                  report.priority === 'medium' ? 'border-l-4 border-l-yellow-500' :
                  'border-l-4 border-l-blue-500'
                }`}>
                  <CardContent className="p-6">
                    <div className="flex justify-between items-start mb-4">
                      <div className="flex-1">
                        <div className="flex items-center space-x-2 mb-2">
                          <h4 className="text-white font-bold text-lg">{report.title}</h4>
                          <span className={`px-2 py-1 rounded text-xs ${
                            report.content_type === 'post' ? 'bg-blue-600' : 'bg-green-600'
                          }`}>
                            {report.content_type.charAt(0).toUpperCase() + report.content_type.slice(1)}
                          </span>
                          <span className={`px-2 py-1 rounded text-xs ${
                            report.priority === 'high' ? 'bg-red-600' :
                            report.priority === 'medium' ? 'bg-yellow-600' : 'bg-gray-600'
                          }`}>
                            {report.priority.charAt(0).toUpperCase() + report.priority.slice(1)} Priority
                          </span>
                        </div>
                        
                        <div className="grid md:grid-cols-2 gap-4 text-sm">
                          <div>
                            <p className="text-gray-400">Author:</p>
                            <p className="text-white">{report.author} ({report.author_email})</p>
                          </div>
                          <div>
                            <p className="text-gray-400">Reported by:</p>
                            <p className="text-white">{report.reported_by}</p>
                          </div>
                          <div>
                            <p className="text-gray-400">Reason:</p>
                            <p className="text-white">{report.report_reason}</p>
                          </div>
                          <div>
                            <p className="text-gray-400">Status:</p>
                            <span className={`px-2 py-1 rounded text-xs ${
                              report.status === 'pending' ? 'bg-yellow-600' :
                              report.status === 'approved' ? 'bg-green-600' :
                              report.status === 'rejected' ? 'bg-red-600' : 'bg-orange-600'
                            }`}>
                              {report.status.charAt(0).toUpperCase() + report.status.slice(1).replace('_', ' ')}
                            </span>
                          </div>
                        </div>
                        
                        <div className="mt-3">
                          <p className="text-gray-400 text-sm">Report Details:</p>
                          <p className="text-gray-300 text-sm mt-1">{report.report_details}</p>
                        </div>
                      </div>
                    </div>

                    {/* Moderation Actions */}
                    {report.status === 'pending' && (
                      <div className="flex items-center space-x-3 pt-4 border-t border-gray-700">
                        <Button
                          size="sm"
                          onClick={() => handleModerationAction(report.id, 'approve')}
                          className="bg-green-600 hover:bg-green-700 text-white"
                        >
                          Approve Content
                        </Button>
                        <Button
                          size="sm"
                          onClick={() => handleModerationAction(report.id, 'reject')}
                          className="bg-red-600 hover:bg-red-700 text-white"
                        >
                          Remove Content
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleModerationAction(report.id, 'warning')}
                          className="border-yellow-500 text-yellow-500 hover:bg-yellow-500/10"
                        >
                          Send Warning
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          className="text-blue-400 hover:text-white hover:bg-blue-600/20"
                        >
                          View Full Content
                        </Button>
                      </div>
                    )}
                  </CardContent>
                </Card>
              ))}
            </div>
          </TabsContent>

          {/* Auto-Moderation Tab */}
          <TabsContent value="automod" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Auto-Moderation Settings</CardTitle>
                <CardDescription className="text-gray-400">
                  Configure automated content moderation rules and filters
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Auto-Moderation Toggle */}
                <div className="flex items-center justify-between py-3 border-b border-gray-700">
                  <div>
                    <h4 className="text-white font-semibold">Auto-Moderation Enabled</h4>
                    <p className="text-gray-400 text-sm">Enable automatic content scanning and flagging</p>
                  </div>
                  <input
                    type="checkbox"
                    checked={autoModerationSettings.enabled}
                    onChange={(e) => handleAutoModSettingChange('enabled', e.target.checked)}
                    className="w-5 h-5 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                  />
                </div>

                {/* Auto-Mod Features */}
                <div className="space-y-4">
                  <h4 className="text-white font-semibold">Detection Features</h4>
                  
                  {[
                    { key: 'spam_detection', label: 'Spam Detection', desc: 'Automatically detect and flag spam content' },
                    { key: 'profanity_filter', label: 'Profanity Filter', desc: 'Flag content containing inappropriate language' },
                    { key: 'adult_content_detection', label: 'Adult Content Detection', desc: 'Identify potentially adult content' },
                    { key: 'auto_action_enabled', label: 'Auto-Action on Violations', desc: 'Automatically hide flagged content until reviewed' }
                  ].map((setting) => (
                    <div key={setting.key} className="flex items-center justify-between py-2">
                      <div>
                        <h5 className="text-white font-medium">{setting.label}</h5>
                        <p className="text-gray-400 text-sm">{setting.desc}</p>
                      </div>
                      <input
                        type="checkbox"
                        checked={autoModerationSettings[setting.key]}
                        onChange={(e) => handleAutoModSettingChange(setting.key, e.target.checked)}
                        className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                      />
                    </div>
                  ))}
                </div>

                {/* Threshold Settings */}
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <Label className="text-white">External Link Limit per Post</Label>
                    <Input
                      type="number"
                      min="0"
                      max="20"
                      value={autoModerationSettings.external_link_limit}
                      onChange={(e) => handleAutoModSettingChange('external_link_limit', parseInt(e.target.value) || 0)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-white">Auto-Flag Threshold (reports)</Label>
                    <Input
                      type="number"
                      min="1"
                      max="10"
                      value={autoModerationSettings.auto_flag_threshold}
                      onChange={(e) => handleAutoModSettingChange('auto_flag_threshold', parseInt(e.target.value) || 1)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>
                </div>

                {/* Banned Words */}
                <div>
                  <Label className="text-white">Banned Words/Phrases</Label>
                  <Textarea
                    value={autoModerationSettings.banned_words}
                    onChange={(e) => handleAutoModSettingChange('banned_words', e.target.value)}
                    className="bg-gray-800 border-gray-600 text-white mt-1"
                    rows="3"
                    placeholder="Enter banned words separated by commas"
                  />
                  <p className="text-gray-400 text-xs mt-1">Content containing these words will be automatically flagged</p>
                </div>

                {/* Whitelist Domains */}
                <div>
                  <Label className="text-white">Whitelist Domains</Label>
                  <Textarea
                    value={autoModerationSettings.whitelist_domains}
                    onChange={(e) => handleAutoModSettingChange('whitelist_domains', e.target.value)}
                    className="bg-gray-800 border-gray-600 text-white mt-1"
                    rows="3"
                    placeholder="Enter allowed domains separated by commas"
                  />
                  <p className="text-gray-400 text-xs mt-1">Links to these domains will not trigger spam detection</p>
                </div>

                <div className="flex justify-end pt-4">
                  <Button
                    onClick={saveAutoModerationSettings}
                    className="bg-blue-600 hover:bg-blue-700 text-white"
                  >
                    Save Auto-Moderation Settings
                  </Button>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Moderation Policies Tab */}
          <TabsContent value="policies" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Community Guidelines & Policies</CardTitle>
                <CardDescription className="text-gray-400">
                  Define and manage platform content policies
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Policy Templates */}
                <div>
                  <h4 className="text-white font-semibold mb-3">Content Policy Templates</h4>
                  <div className="grid md:grid-cols-2 gap-4">
                    <Button variant="outline" className="h-20 flex flex-col items-center justify-center border-white/20 text-white hover:bg-white/10">
                      <BookOpen className="w-6 h-6 mb-2" />
                      <span>Community Guidelines</span>
                    </Button>
                    <Button variant="outline" className="h-20 flex flex-col items-center justify-center border-white/20 text-white hover:bg-white/10">
                      <Settings className="w-6 h-6 mb-2" />
                      <span>Content Standards</span>
                    </Button>
                    <Button variant="outline" className="h-20 flex flex-col items-center justify-center border-white/20 text-white hover:bg-white/10">
                      <Users className="w-6 h-6 mb-2" />
                      <span>User Conduct Rules</span>
                    </Button>
                    <Button variant="outline" className="h-20 flex flex-col items-center justify-center border-white/20 text-white hover:bg-white/10">
                      <TrendingUp className="w-6 h-6 mb-2" />
                      <span>Monetization Policy</span>
                    </Button>
                  </div>
                </div>

                {/* Quick Policy Actions */}
                <div>
                  <h4 className="text-white font-semibold mb-3">Quick Actions</h4>
                  <div className="space-y-3">
                    <Button className="w-full justify-start bg-purple-600 hover:bg-purple-700 text-white">
                      <Edit className="w-4 h-4 mr-2" />
                      Edit Community Guidelines
                    </Button>
                    <Button className="w-full justify-start bg-orange-600 hover:bg-orange-700 text-white">
                      <MessageSquare className="w-4 h-4 mr-2" />
                      Broadcast Policy Update to Users
                    </Button>
                    <Button className="w-full justify-start bg-green-600 hover:bg-green-700 text-white">
                      <BookOpen className="w-4 h-4 mr-2" />
                      Generate Policy Report
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    );
  }

  // Analytics Tab
  function AnalyticsTab() {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-2xl font-bold text-white">Platform Analytics</h2>
          <p className="text-gray-400">Monitor platform performance and user engagement</p>
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">User Growth</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-gray-400">Analytics dashboard coming soon...</p>
            </CardContent>
          </Card>

          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">Revenue Analytics</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-gray-400">Revenue tracking coming soon...</p>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  // Platform Settings Tab
  function PlatformSettingsTab() {
    const [activeSettingsSection, setActiveSettingsSection] = useState('general');
    const [siteSettings, setSiteSettings] = useState({
      // General Settings
      site_name: 'Queens Mountain',
      site_description: 'A platform for creative writers and passionate readers',
      site_logo: null,
      favicon: null,
      default_language: 'en',
      timezone: 'UTC',
      
      // Appearance Settings
      primary_color: '#3B82F6',
      secondary_color: '#8B5CF6',
      accent_color: '#F59E0B',
      dark_mode_enabled: true,
      background_image: '',
      panel_opacity: 20,
      custom_css: '',
      
      // User Registration Settings
      registration_enabled: true,
      email_verification_required: true,
      writer_approval_required: true,
      minimum_age: 18,
      allowed_domains: '',
      
      // Content Policy Settings
      content_moderation_enabled: true,
      auto_moderation: true,
      adult_content_allowed: true,
      adult_content_warning: true,
      max_post_length: 50000,
      max_file_size_mb: 100,
      
      // Payment Settings
      stripe_enabled: true,
      platform_fee_percentage: 5,
      minimum_withdrawal: 50,
      payout_schedule: 'monthly',
      currency: 'USD',
      
      // Email Settings
      smtp_enabled: true,
      smtp_host: '',
      smtp_port: 587,
      smtp_username: '',
      smtp_password: '',
      from_email: 'noreply@queensmountain.com',
      from_name: 'Queens Mountain',
      
      // Security Settings
      two_factor_required: false,
      session_timeout_hours: 24,
      max_login_attempts: 5,
      password_min_length: 8,
      require_strong_passwords: true,
      
      // Feature Toggles
      social_features_enabled: true,
      messaging_enabled: true,
      comments_enabled: true,
      reviews_enabled: true,
      forums_enabled: true
    });

    const [saving, setSaving] = useState(false);

    const handleSettingChange = (key, value) => {
      setSiteSettings(prev => ({
        ...prev,
        [key]: value
      }));
    };

    const handleSaveSettings = async () => {
      setSaving(true);
      try {
        const response = await axios.put(`${API}/admin/site-settings`, {
          background_image: siteSettings.background_image,
          panel_opacity: siteSettings.panel_opacity,
          site_name: siteSettings.site_name,
          primary_color: siteSettings.primary_color,
          secondary_color: siteSettings.secondary_color,
          accent_color: siteSettings.accent_color
        });
        
        // Trigger a storage event to update global background
        window.dispatchEvent(new Event('storage'));
        
        toast({
          title: "Settings Saved",
          description: "Platform settings have been updated successfully.",
        });
      } catch (error) {
        console.error('Settings save error:', error);
        toast({
          title: "Error",
          description: "Failed to save settings. Please try again.",
          variant: "destructive",
        });
      } finally {
        setSaving(false);
      }
    };

    const handleImageUpload = async (settingKey, file) => {
      try {
        const formData = new FormData();
        formData.append('file', file);

        const response = await axios.post(`${API}/upload/image`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });

        if (response.data && response.data.url) {
          handleSettingChange(settingKey, response.data.url);
          
          toast({
            title: "Image Uploaded",
            description: `${settingKey.replace('_', ' ')} has been updated.`,
          });
        }
      } catch (error) {
        console.error('Image upload error:', error);
        toast({
          title: "Upload Failed",
          description: "Failed to upload image. Please try again.",
          variant: "destructive",
        });
      }
    };

    return (
      <div className="space-y-6">
        {/* Platform Settings Header */}
        <div>
          <h2 className="text-2xl font-bold text-white">Platform Settings</h2>
          <p className="text-gray-400">Configure site-wide settings and preferences for Queens Mountain</p>
        </div>

        {/* Settings Navigation */}
        <Tabs value={activeSettingsSection} onValueChange={setActiveSettingsSection} className="space-y-6">
          <TabsList className="bg-gray-800/50 border border-gray-700">
            <TabsTrigger value="general" className="text-gray-300 data-[state=active]:bg-orange-600 data-[state=active]:text-white">
              General
            </TabsTrigger>
            <TabsTrigger value="appearance" className="text-gray-300 data-[state=active]:bg-orange-600 data-[state=active]:text-white">
              Appearance
            </TabsTrigger>
            <TabsTrigger value="users" className="text-gray-300 data-[state=active]:bg-orange-600 data-[state=active]:text-white">
              User Settings
            </TabsTrigger>
            <TabsTrigger value="content" className="text-gray-300 data-[state=active]:bg-orange-600 data-[state=active]:text-white">
              Content Policy
            </TabsTrigger>
            <TabsTrigger value="payments" className="text-gray-300 data-[state=active]:bg-orange-600 data-[state=active]:text-white">
              Payments
            </TabsTrigger>
            <TabsTrigger value="security" className="text-gray-300 data-[state=active]:bg-orange-600 data-[state=active]:text-white">
              Security
            </TabsTrigger>
          </TabsList>

          {/* General Settings */}
          <TabsContent value="general" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">General Site Settings</CardTitle>
                <CardDescription className="text-gray-400">
                  Basic configuration for your Queens Mountain platform
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid md:grid-cols-2 gap-6">
                  {/* Site Name */}
                  <div>
                    <Label className="text-white">Site Name</Label>
                    <Input
                      value={siteSettings.site_name}
                      onChange={(e) => handleSettingChange('site_name', e.target.value)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>

                  {/* Default Language */}
                  <div>
                    <Label className="text-white">Default Language</Label>
                    <Select value={siteSettings.default_language} onValueChange={(value) => handleSettingChange('default_language', value)}>
                      <SelectTrigger className="bg-gray-800 border-gray-600 text-white mt-1">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent className="bg-gray-800 border-gray-600">
                        <SelectItem value="en" className="text-white">English</SelectItem>
                        <SelectItem value="es" className="text-white">Spanish</SelectItem>
                        <SelectItem value="fr" className="text-white">French</SelectItem>
                        <SelectItem value="de" className="text-white">German</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* Site Description */}
                <div>
                  <Label className="text-white">Site Description</Label>
                  <Textarea
                    value={siteSettings.site_description}
                    onChange={(e) => handleSettingChange('site_description', e.target.value)}
                    className="bg-gray-800 border-gray-600 text-white mt-1"
                    rows="3"
                    placeholder="A brief description of your platform"
                  />
                </div>

                {/* Logo Upload */}
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <Label className="text-white mb-3 block">Site Logo</Label>
                    <div className="flex items-center space-x-4">
                      <div className="w-16 h-16 bg-gray-700 rounded-lg flex items-center justify-center overflow-hidden">
                        {siteSettings.site_logo ? (
                          <img src={siteSettings.site_logo} alt="Site Logo" className="w-full h-full object-cover" />
                        ) : (
                          <Upload className="w-6 h-6 text-gray-400" />
                        )}
                      </div>
                      <div>
                        <input
                          type="file"
                          id="logo-upload"
                          accept="image/*"
                          onChange={(e) => {
                            const file = e.target.files[0];
                            if (file) handleImageUpload('site_logo', file);
                          }}
                          className="hidden"
                        />
                        <Button
                          variant="outline"
                          onClick={() => document.getElementById('logo-upload').click()}
                          className="border-white/20 text-white hover:bg-white/10"
                        >
                          Upload Logo
                        </Button>
                      </div>
                    </div>
                  </div>

                  {/* Favicon Upload */}
                  <div>
                    <Label className="text-white mb-3 block">Favicon</Label>
                    <div className="flex items-center space-x-4">
                      <div className="w-8 h-8 bg-gray-700 rounded flex items-center justify-center overflow-hidden">
                        {siteSettings.favicon ? (
                          <img src={siteSettings.favicon} alt="Favicon" className="w-full h-full object-cover" />
                        ) : (
                          <Upload className="w-3 h-3 text-gray-400" />
                        )}
                      </div>
                      <div>
                        <input
                          type="file"
                          id="favicon-upload"
                          accept="image/*"
                          onChange={(e) => {
                            const file = e.target.files[0];
                            if (file) handleImageUpload('favicon', file);
                          }}
                          className="hidden"
                        />
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => document.getElementById('favicon-upload').click()}
                          className="border-white/20 text-white hover:bg-white/10"
                        >
                          Upload Favicon
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Timezone */}
                <div>
                  <Label className="text-white">Default Timezone</Label>
                  <Select value={siteSettings.timezone} onValueChange={(value) => handleSettingChange('timezone', value)}>
                    <SelectTrigger className="bg-gray-800 border-gray-600 text-white mt-1">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="bg-gray-800 border-gray-600">
                      <SelectItem value="UTC" className="text-white">UTC</SelectItem>
                      <SelectItem value="America/New_York" className="text-white">Eastern Time (EST)</SelectItem>
                      <SelectItem value="America/Chicago" className="text-white">Central Time (CST)</SelectItem>
                      <SelectItem value="America/Denver" className="text-white">Mountain Time (MST)</SelectItem>
                      <SelectItem value="America/Los_Angeles" className="text-white">Pacific Time (PST)</SelectItem>
                      <SelectItem value="Europe/London" className="text-white">London (GMT)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Appearance Settings */}
          <TabsContent value="appearance" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Theme & Appearance</CardTitle>
                <CardDescription className="text-gray-400">
                  Customize the visual appearance of your platform
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Color Settings */}
                <div className="grid md:grid-cols-3 gap-6">
                  <div>
                    <Label className="text-white">Primary Color</Label>
                    <div className="flex items-center space-x-3 mt-2">
                      <input
                        type="color"
                        value={siteSettings.primary_color}
                        onChange={(e) => handleSettingChange('primary_color', e.target.value)}
                        className="w-12 h-10 rounded border border-gray-600"
                      />
                      <Input
                        value={siteSettings.primary_color}
                        onChange={(e) => handleSettingChange('primary_color', e.target.value)}
                        className="bg-gray-800 border-gray-600 text-white flex-1"
                      />
                    </div>
                  </div>

                  <div>
                    <Label className="text-white">Secondary Color</Label>
                    <div className="flex items-center space-x-3 mt-2">
                      <input
                        type="color"
                        value={siteSettings.secondary_color}
                        onChange={(e) => handleSettingChange('secondary_color', e.target.value)}
                        className="w-12 h-10 rounded border border-gray-600"
                      />
                      <Input
                        value={siteSettings.secondary_color}
                        onChange={(e) => handleSettingChange('secondary_color', e.target.value)}
                        className="bg-gray-800 border-gray-600 text-white flex-1"
                      />
                    </div>
                  </div>

                  <div>
                    <Label className="text-white">Accent Color</Label>
                    <div className="flex items-center space-x-3 mt-2">
                      <input
                        type="color"
                        value={siteSettings.accent_color}
                        onChange={(e) => handleSettingChange('accent_color', e.target.value)}
                        className="w-12 h-10 rounded border border-gray-600"
                      />
                      <Input
                        value={siteSettings.accent_color}
                        onChange={(e) => handleSettingChange('accent_color', e.target.value)}
                        className="bg-gray-800 border-gray-600 text-white flex-1"
                      />
                    </div>
                  </div>
                </div>

                {/* Global Background Image */}
                <div className="space-y-4">
                  <div>
                    <Label className="text-white mb-3 block">Global Background Image</Label>
                    <div className="flex items-center space-x-4">
                      <div className="w-32 h-20 bg-gray-700 rounded-lg flex items-center justify-center overflow-hidden">
                        {siteSettings.background_image ? (
                          <img src={siteSettings.background_image} alt="Background Preview" className="w-full h-full object-cover" />
                        ) : (
                          <Upload className="w-6 h-6 text-gray-400" />
                        )}
                      </div>
                      <div className="flex-1">
                        <input
                          type="file"
                          id="background-upload"
                          accept="image/*"
                          onChange={(e) => {
                            const file = e.target.files[0];
                            if (file) handleImageUpload('background_image', file);
                          }}
                          className="hidden"
                        />
                        <Button
                          variant="outline"
                          onClick={() => document.getElementById('background-upload').click()}
                          className="border-white/20 text-white hover:bg-white/10 mb-2"
                        >
                          Upload Background Image
                        </Button>
                        <p className="text-gray-400 text-xs">Upload an image to use as the global background across the platform</p>
                      </div>
                    </div>
                  </div>

                  {/* Background Opacity Slider */}
                  <div>
                    <Label className="text-white">Panel Opacity Over Background</Label>
                    <div className="mt-2 space-y-3">
                      <input
                        type="range"
                        min="0"
                        max="100"
                        value={siteSettings.panel_opacity || 20}
                        onChange={(e) => handleSettingChange('panel_opacity', parseInt(e.target.value))}
                        className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer"
                        style={{
                          background: `linear-gradient(to right, #3B82F6 0%, #3B82F6 ${siteSettings.panel_opacity || 20}%, #374151 ${siteSettings.panel_opacity || 20}%, #374151 100%)`
                        }}
                      />
                      <div className="flex justify-between text-xs text-gray-400">
                        <span>Transparent</span>
                        <span className="text-white font-medium">{siteSettings.panel_opacity || 20}% Opacity</span>
                        <span>Opaque</span>
                      </div>
                      <p className="text-gray-400 text-xs">Controls the opacity of all content panels over the background image</p>
                    </div>
                  </div>
                </div>

                <Separator className="bg-gray-700" />

                {/* Dark Mode Toggle */}
                <div className="flex items-center justify-between py-2">
                  <div>
                    <h4 className="text-white font-medium">Dark Mode Enabled</h4>
                    <p className="text-gray-400 text-sm">Enable dark mode as the default theme</p>
                  </div>
                  <input
                    type="checkbox"
                    checked={siteSettings.dark_mode_enabled}
                    onChange={(e) => handleSettingChange('dark_mode_enabled', e.target.checked)}
                    className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                  />
                </div>

                {/* Custom CSS */}
                <div>
                  <Label className="text-white">Custom CSS</Label>
                  <Textarea
                    value={siteSettings.custom_css}
                    onChange={(e) => handleSettingChange('custom_css', e.target.value)}
                    className="bg-gray-800 border-gray-600 text-white mt-1 font-mono text-sm"
                    rows="8"
                    placeholder="/* Add custom CSS styles here */
.custom-button {
  background-color: #your-color;
}"
                  />
                  <p className="text-gray-400 text-xs mt-1">Add custom CSS to override default styles</p>
                </div>

                {/* Save Settings Button */}
                <div className="flex justify-end pt-6">
                  <Button
                    onClick={handleSaveSettings}
                    disabled={saving}
                    className="bg-orange-600 hover:bg-orange-700 text-white"
                  >
                    {saving ? 'Saving...' : 'Save Appearance Settings'}
                  </Button>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* User Settings */}
          <TabsContent value="users" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">User Registration & Management</CardTitle>
                <CardDescription className="text-gray-400">
                  Configure user registration and account settings
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Registration Settings */}
                <div className="space-y-4">
                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">User Registration Enabled</h4>
                      <p className="text-gray-400 text-sm">Allow new users to register accounts</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.registration_enabled}
                      onChange={(e) => handleSettingChange('registration_enabled', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>

                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">Email Verification Required</h4>
                      <p className="text-gray-400 text-sm">Require email verification for new accounts</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.email_verification_required}
                      onChange={(e) => handleSettingChange('email_verification_required', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>

                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">Writer Approval Required</h4>
                      <p className="text-gray-400 text-sm">Require admin approval for new writer accounts</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.writer_approval_required}
                      onChange={(e) => handleSettingChange('writer_approval_required', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>
                </div>

                {/* Age and Domain Restrictions */}
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <Label className="text-white">Minimum Age Requirement</Label>
                    <Select value={siteSettings.minimum_age.toString()} onValueChange={(value) => handleSettingChange('minimum_age', parseInt(value))}>
                      <SelectTrigger className="bg-gray-800 border-gray-600 text-white mt-1">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent className="bg-gray-800 border-gray-600">
                        <SelectItem value="13" className="text-white">13 years</SelectItem>
                        <SelectItem value="16" className="text-white">16 years</SelectItem>
                        <SelectItem value="18" className="text-white">18 years</SelectItem>
                        <SelectItem value="21" className="text-white">21 years</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* Email Domain Restrictions */}
                <div>
                  <Label className="text-white">Allowed Email Domains (Optional)</Label>
                  <Textarea
                    value={siteSettings.allowed_domains}
                    onChange={(e) => handleSettingChange('allowed_domains', e.target.value)}
                    className="bg-gray-800 border-gray-600 text-white mt-1"
                    rows="3"
                    placeholder="example.com&#10;university.edu&#10;organization.org"
                  />
                  <p className="text-gray-400 text-xs mt-1">Leave empty to allow all domains. One domain per line.</p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Content Policy */}
          <TabsContent value="content" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Content Policy & Moderation</CardTitle>
                <CardDescription className="text-gray-400">
                  Configure content guidelines and moderation settings
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Moderation Settings */}
                <div className="space-y-4">
                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">Content Moderation Enabled</h4>
                      <p className="text-gray-400 text-sm">Enable content review and moderation features</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.content_moderation_enabled}
                      onChange={(e) => handleSettingChange('content_moderation_enabled', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>

                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">Auto-Moderation</h4>
                      <p className="text-gray-400 text-sm">Automatically flag potentially inappropriate content</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.auto_moderation}
                      onChange={(e) => handleSettingChange('auto_moderation', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>

                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">Adult Content Allowed</h4>
                      <p className="text-gray-400 text-sm">Allow mature/adult content on the platform</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.adult_content_allowed}
                      onChange={(e) => handleSettingChange('adult_content_allowed', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>

                  {siteSettings.adult_content_allowed && (
                    <div className="flex items-center justify-between py-2 ml-4">
                      <div>
                        <h4 className="text-white font-medium">Adult Content Warning</h4>
                        <p className="text-gray-400 text-sm">Show warnings before displaying adult content</p>
                      </div>
                      <input
                        type="checkbox"
                        checked={siteSettings.adult_content_warning}
                        onChange={(e) => handleSettingChange('adult_content_warning', e.target.checked)}
                        className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                      />
                    </div>
                  )}
                </div>

                {/* Content Limits */}
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <Label className="text-white">Maximum Post Length (characters)</Label>
                    <Input
                      type="number"
                      value={siteSettings.max_post_length}
                      onChange={(e) => handleSettingChange('max_post_length', parseInt(e.target.value) || 0)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>

                  <div>
                    <Label className="text-white">Maximum File Size (MB)</Label>
                    <Input
                      type="number"
                      value={siteSettings.max_file_size_mb}
                      onChange={(e) => handleSettingChange('max_file_size_mb', parseInt(e.target.value) || 0)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Payment Settings */}
          <TabsContent value="payments" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Payment & Revenue Settings</CardTitle>
                <CardDescription className="text-gray-400">
                  Configure payment processing and platform revenue settings
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Payment Provider */}
                <div className="flex items-center justify-between py-2">
                  <div>
                    <h4 className="text-white font-medium">Stripe Payments Enabled</h4>
                    <p className="text-gray-400 text-sm">Enable Stripe for payment processing</p>
                  </div>
                  <input
                    type="checkbox"
                    checked={siteSettings.stripe_enabled}
                    onChange={(e) => handleSettingChange('stripe_enabled', e.target.checked)}
                    className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                  />
                </div>

                {/* Revenue Settings */}
                <div className="grid md:grid-cols-3 gap-6">
                  <div>
                    <Label className="text-white">Platform Fee (%)</Label>
                    <Input
                      type="number"
                      min="0"
                      max="100"
                      step="0.1"
                      value={siteSettings.platform_fee_percentage}
                      onChange={(e) => handleSettingChange('platform_fee_percentage', parseFloat(e.target.value) || 0)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>

                  <div>
                    <Label className="text-white">Minimum Withdrawal ($)</Label>
                    <Input
                      type="number"
                      min="0"
                      value={siteSettings.minimum_withdrawal}
                      onChange={(e) => handleSettingChange('minimum_withdrawal', parseInt(e.target.value) || 0)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>

                  <div>
                    <Label className="text-white">Payout Schedule</Label>
                    <Select value={siteSettings.payout_schedule} onValueChange={(value) => handleSettingChange('payout_schedule', value)}>
                      <SelectTrigger className="bg-gray-800 border-gray-600 text-white mt-1">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent className="bg-gray-800 border-gray-600">
                        <SelectItem value="weekly" className="text-white">Weekly</SelectItem>
                        <SelectItem value="bi-weekly" className="text-white">Bi-weekly</SelectItem>
                        <SelectItem value="monthly" className="text-white">Monthly</SelectItem>
                        <SelectItem value="manual" className="text-white">Manual</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* Currency */}
                <div>
                  <Label className="text-white">Default Currency</Label>
                  <Select value={siteSettings.currency} onValueChange={(value) => handleSettingChange('currency', value)}>
                    <SelectTrigger className="w-48 bg-gray-800 border-gray-600 text-white mt-1">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="bg-gray-800 border-gray-600">
                      <SelectItem value="USD" className="text-white">USD - US Dollar</SelectItem>
                      <SelectItem value="EUR" className="text-white">EUR - Euro</SelectItem>
                      <SelectItem value="GBP" className="text-white">GBP - British Pound</SelectItem>
                      <SelectItem value="CAD" className="text-white">CAD - Canadian Dollar</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Security Settings */}
          <TabsContent value="security" className="space-y-6">
            <Card className={`${getPanelClasses('mainPanel')}`}>
              <CardHeader>
                <CardTitle className="text-white">Security & Authentication</CardTitle>
                <CardDescription className="text-gray-400">
                  Configure platform security and authentication settings
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Authentication Settings */}
                <div className="space-y-4">
                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">Two-Factor Authentication Required</h4>
                      <p className="text-gray-400 text-sm">Require 2FA for all user accounts</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.two_factor_required}
                      onChange={(e) => handleSettingChange('two_factor_required', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>

                  <div className="flex items-center justify-between py-2">
                    <div>
                      <h4 className="text-white font-medium">Require Strong Passwords</h4>
                      <p className="text-gray-400 text-sm">Enforce strong password requirements</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={siteSettings.require_strong_passwords}
                      onChange={(e) => handleSettingChange('require_strong_passwords', e.target.checked)}
                      className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                  </div>
                </div>

                {/* Security Parameters */}
                <div className="grid md:grid-cols-3 gap-6">
                  <div>
                    <Label className="text-white">Session Timeout (hours)</Label>
                    <Input
                      type="number"
                      min="1"
                      max="168"
                      value={siteSettings.session_timeout_hours}
                      onChange={(e) => handleSettingChange('session_timeout_hours', parseInt(e.target.value) || 1)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>

                  <div>
                    <Label className="text-white">Max Login Attempts</Label>
                    <Input
                      type="number"
                      min="1"
                      max="10"
                      value={siteSettings.max_login_attempts}
                      onChange={(e) => handleSettingChange('max_login_attempts', parseInt(e.target.value) || 1)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>

                  <div>
                    <Label className="text-white">Minimum Password Length</Label>
                    <Input
                      type="number"
                      min="6"
                      max="50"
                      value={siteSettings.password_min_length}
                      onChange={(e) => handleSettingChange('password_min_length', parseInt(e.target.value) || 6)}
                      className="bg-gray-800 border-gray-600 text-white mt-1"
                    />
                  </div>
                </div>

                {/* Feature Toggles */}
                <div>
                  <h4 className="text-white font-semibold mb-4">Platform Features</h4>
                  <div className="space-y-3">
                    {[
                      { key: 'social_features_enabled', label: 'Social Features', desc: 'Enable social interactions and networking' },
                      { key: 'messaging_enabled', label: 'Direct Messaging', desc: 'Allow users to send private messages' },
                      { key: 'comments_enabled', label: 'Comments', desc: 'Enable commenting on posts' },
                      { key: 'reviews_enabled', label: 'Reviews', desc: 'Allow users to review content' },
                      { key: 'forums_enabled', label: 'Community Forums', desc: 'Enable community discussion forums' }
                    ].map((feature) => (
                      <div key={feature.key} className="flex items-center justify-between py-2">
                        <div>
                          <h5 className="text-white font-medium">{feature.label}</h5>
                          <p className="text-gray-400 text-sm">{feature.desc}</p>
                        </div>
                        <input
                          type="checkbox"
                          checked={siteSettings[feature.key]}
                          onChange={(e) => handleSettingChange(feature.key, e.target.checked)}
                          className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                        />
                      </div>
                    ))}
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* Save Button */}
        <div className="flex justify-end pt-6">
          <Button
            onClick={handleSaveSettings}
            disabled={saving}
            className="bg-green-600 hover:bg-green-700 text-white px-8 py-3"
          >
            {saving ? (
              <div className="flex items-center">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                Saving...
              </div>
            ) : (
              'Save All Settings'
            )}
          </Button>
        </div>
      </div>
    );
  }
};

// Page Editor Tab - Admin editable pages
function PageEditorTab() {
  const { getPanelClasses } = React.useContext(PanelOpacityContext);
  const { toast } = useToast();
  
  const [aboutData, setAboutData] = useState({
    title: 'About Queens Mountain',
    content: '',
    mission: '',
    vision: '',
    team_info: ''
  });

  const [newsData, setNewsData] = useState({
    title: 'Latest News',
    content: '',
    featured_article: '',
    announcements: []
  });

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState('about');

  useEffect(() => {
    Promise.all([fetchAboutData(), fetchNewsData()]);
  }, []);

  const fetchAboutData = async () => {
    try {
      const response = await axios.get(`${API}/admin/about-page`);
      setAboutData(response.data);
    } catch (error) {
      console.error('Error fetching about data:', error);
      toast({
        title: "Error",
        description: "Failed to load about page data.",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const fetchNewsData = async () => {
    try {
      const response = await axios.get(`${API}/admin/news`);
      setNewsData(response.data);
    } catch (error) {
      console.error('Error fetching news data:', error);
      toast({
        title: "Error", 
        description: "Failed to load news page data.",
        variant: "destructive",
      });
    }
  };

  const handleSaveAbout = async () => {
    setSaving(true);
    try {
      const response = await axios.put(`${API}/admin/about-page`, aboutData);
      setAboutData(response.data);
      
      toast({
        title: "About Page Saved",
        description: "About page content has been updated successfully.",
      });
    } catch (error) {
      console.error('About page save error:', error);
      toast({
        title: "Error",
        description: "Failed to save about page. Please try again.",
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  const handleSaveNews = async () => {
    setSaving(true);
    try {
      const response = await axios.put(`${API}/admin/news`, newsData);
      setNewsData(response.data);
      
      toast({
        title: "News Page Saved",
        description: "News page content has been updated successfully.",
      });
    } catch (error) {
      console.error('News page save error:', error);
      toast({
        title: "Error",
        description: "Failed to save news page. Please try again.",
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="text-center py-12">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white mx-auto"></div>
        <p className="mt-4 text-white text-lg">Loading page editor...</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Page Editor Header */}
      <div>
        <h2 className="text-2xl font-bold text-white">Page Editor</h2>
        <p className="text-gray-400">Edit site pages and content</p>
      </div>

      {/* Page Selection Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="bg-gray-800">
          <TabsTrigger value="about" className="data-[state=active]:bg-blue-600">About Page</TabsTrigger>
          <TabsTrigger value="news" className="data-[state=active]:bg-blue-600">News Page</TabsTrigger>
        </TabsList>

        {/* About Page Editor */}
        <TabsContent value="about">
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">About Page</CardTitle>
              <CardDescription className="text-gray-400">
                Edit the content that appears on the /about page
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Title */}
              <div>
                <Label className="text-white">Page Title</Label>
                <Input
                  value={aboutData.title}
                  onChange={(e) => setAboutData({...aboutData, title: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="About Queens Mountain"
                />
              </div>

              {/* Main Content */}
              <div>
                <Label className="text-white">Main Content</Label>
                <Textarea
                  value={aboutData.content}
                  onChange={(e) => setAboutData({...aboutData, content: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white min-h-[120px]"
                  placeholder="Write about your platform..."
                />
              </div>

              {/* Mission */}
              <div>
                <Label className="text-white">Mission Statement</Label>
                <Textarea
                  value={aboutData.mission}
                  onChange={(e) => setAboutData({...aboutData, mission: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Our mission is..."
                />
              </div>

              {/* Vision */}
              <div>
                <Label className="text-white">Vision Statement</Label>
                <Textarea
                  value={aboutData.vision}
                  onChange={(e) => setAboutData({...aboutData, vision: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Our vision is..."
                />
              </div>

              {/* Team Info */}
              <div>
                <Label className="text-white">Team Information</Label>
                <Textarea
                  value={aboutData.team_info}
                  onChange={(e) => setAboutData({...aboutData, team_info: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Information about your team..."
                />
              </div>

              {/* Action Buttons */}
              <div className="flex justify-between">
                <Button
                  variant="outline"
                  onClick={() => window.open('/about', '_blank')}
                  className="border-white/20 text-white hover:bg-white/10"
                >
                  Preview Page
                </Button>
                
                <Button
                  onClick={handleSaveAbout}
                  disabled={saving}
                  className="bg-blue-600 hover:bg-blue-700 text-white"
                >
                  {saving ? 'Saving...' : 'Save About Page'}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* News Page Editor */}
        <TabsContent value="news">
          <Card className={`${getPanelClasses('mainPanel')}`}>
            <CardHeader>
              <CardTitle className="text-white">News Page</CardTitle>
              <CardDescription className="text-gray-400">
                Edit the content that appears on the /news page
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Title */}
              <div>
                <Label className="text-white">Page Title</Label>
                <Input
                  value={newsData.title}
                  onChange={(e) => setNewsData({...newsData, title: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Latest News"
                />
              </div>

              {/* Main Content */}
              <div>
                <Label className="text-white">Main Content</Label>
                <Textarea
                  value={newsData.content}
                  onChange={(e) => setNewsData({...newsData, content: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white min-h-[120px]"
                  placeholder="Write about your latest news and updates..."
                />
              </div>

              {/* Featured Article */}
              <div>
                <Label className="text-white">Featured Article</Label>
                <Textarea
                  value={newsData.featured_article}
                  onChange={(e) => setNewsData({...newsData, featured_article: e.target.value})}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Featured news article content..."
                />
              </div>

              {/* Announcements */}
              <div>
                <Label className="text-white">Announcements (one per line)</Label>
                <Textarea
                  value={newsData.announcements?.join('\n') || ''}
                  onChange={(e) => setNewsData({
                    ...newsData, 
                    announcements: e.target.value.split('\n').filter(line => line.trim())
                  })}
                  className="bg-gray-800 border-gray-600 text-white"
                  placeholder="Enter announcements, one per line..."
                  rows={4}
                />
              </div>

              {/* Action Buttons */}
              <div className="flex justify-between">
                <Button
                  variant="outline"
                  onClick={() => window.open('/news', '_blank')}
                  className="border-white/20 text-white hover:bg-white/10"
                >
                  Preview Page
                </Button>
                
                <Button
                  onClick={handleSaveNews}
                  disabled={saving}
                  className="bg-blue-600 hover:bg-blue-700 text-white"
                >
                  {saving ? 'Saving...' : 'Save News Page'}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

// Social Context for global messaging and friend management
const SocialContext = React.createContext();

const SocialProvider = ({ children }) => {
  const [isMessagingOpen, setIsMessagingOpen] = useState(false);
  const [isFriendsOpen, setIsFriendsOpen] = useState(false);
  const [unreadMessages, setUnreadMessages] = useState(0);
  const [unreadNotifications, setUnreadNotifications] = useState(0);
  const [onlineStatus, setOnlineStatus] = useState('online');
  const [activeConversations, setActiveConversations] = useState([]);

  return (
    <SocialContext.Provider value={{
      isMessagingOpen, setIsMessagingOpen,
      isFriendsOpen, setIsFriendsOpen,
      unreadMessages, setUnreadMessages,
      unreadNotifications, setUnreadNotifications,
      onlineStatus, setOnlineStatus,
      activeConversations, setActiveConversations
    }}>
      {children}
    </SocialContext.Provider>
  );
};

// Global Social Overlay Component
const GlobalSocialOverlay = () => {
  const { user } = React.useContext(AuthContext);
  const { 
    isMessagingOpen, setIsMessagingOpen, 
    isFriendsOpen, setIsFriendsOpen,
    unreadMessages 
  } = React.useContext(SocialContext);

  // Don't show social features for non-logged in users or on landing page
  if (!user || window.location.pathname === '/') {
    return null;
  }

  return (
    <>
      {/* Floating Message Button */}
      <div className="fixed bottom-6 right-6 z-50">
        <div className="flex flex-col space-y-3">
          {/* Messages Button */}
          <Button
            onClick={() => setIsMessagingOpen(true)}
            className="w-14 h-14 rounded-full bg-blue-600 hover:bg-blue-700 text-white shadow-lg"
            size="sm"
          >
            <MessageSquare className="w-6 h-6" />
            {unreadMessages > 0 && (
              <span className="absolute -top-2 -right-2 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                {unreadMessages}
              </span>
            )}
          </Button>

          {/* Friends Button */}
          <Button
            onClick={() => setIsFriendsOpen(true)}
            variant="outline"
            className="w-14 h-14 rounded-full border-white/20 text-white hover:bg-white/10 shadow-lg"
            size="sm"
          >
            <Users className="w-6 h-6" />
          </Button>
        </div>
      </div>

      {/* Global Social Modals */}
      <MessageChatBubble 
        isOpen={isMessagingOpen} 
        onClose={() => setIsMessagingOpen(false)} 
      />
      
      <FriendRequestsManager 
        isOpen={isFriendsOpen} 
        onClose={() => setIsFriendsOpen(false)} 
      />
    </>
  );
};

function App() {
  return (
    <ThemeProvider attribute="class" defaultTheme="dark" enableSystem>
      <QueryClientProvider client={queryClient}>
      <BrowserRouter>
      <PanelOpacityProvider>
        <AuthProvider>
          <SocialProvider>
            <div className="App">
              <Routes>
                <Route path="/" element={<LandingPage />} />
                <Route path="/dashboard" element={<Dashboard />} />
                <Route path="/profile" element={<ProfileRouter />} />
                <Route path="/profile/:userId" element={<UserProfile />} />
              <Route path="/writer/:writerId" element={<WriterProfile />} />
              <Route path="/writer/:writerId/tiers" element={<WriterTiersPage />} />
              <Route path="/writer/:writerId/subscribe" element={<WriterSubscribePage />} />
              <Route path="/admin/dashboard" element={<AdminDashboard />} />
                <Route path="/auth/*" element={<AuthHandler />} />
                {/* New Pages */}
                <Route path="/contact" element={<ContactUs />} />
                <Route path="/about" element={<AboutUs />} />
                <Route path="/news" element={<NewsPage />} />
                {/* Payment Routes */}
                <Route path="/payment/success" element={<PaymentSuccess />} />
                <Route path="/payment/cancel" element={<Navigate to="/" replace />} />
                {/* Placeholder routes for future implementation */}
                <Route path="/forum" element={<Forum />} />
                <Route path="/genres" element={<Genres />} />
                <Route path="/genres/:genre" element={<GenreStories />} />
                <Route path="/create-chapter" element={<CreateChapter />} />
                <Route path="/search/tags/:tag" element={<TagSearchResults />} />
                <Route path="/reviews" element={<Reviews />} />
                <Route path="/admin" element={<AdminPanel />} />
              </Routes>
              
              {/* Global Social Features */}
              <GlobalSocialOverlay />
              
              <Toaster />
            </div>
          </SocialProvider>
        </AuthProvider>
      </PanelOpacityProvider>
    </BrowserRouter>
  </QueryClientProvider>
  </ThemeProvider>
  );
}

export default App;