import React, { useState, useEffect } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Slider } from "@/components/ui/slider";
import { 
  Sparkles, 
  Download, 
  Image as ImageIcon, 
  Palette,
  Wand2,
  RefreshCw,
  Star,
  Zap,
  Grid3X3,
  Type,
  Heart,
  ChevronRight,
  Layers,
  Target,
  Lightbulb,
  Crown
} from 'lucide-react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useTranslation } from 'react-i18next';
import { supabase } from '@/integrations/supabase/client';
import { useSession } from '@supabase/auth-helpers-react';
import { showSuccess, showError, showLoading, dismissToast } from '@/utils/toast';

// Define interfaces for user data
interface UserProfile {
  id: string;
  logo_generations_this_month: number;
  last_logo_generation_month?: string;
}

interface UserSubscription {
  id: string;
  plan: '50' | '100' | 'unlimited';
  start_date: string;
  end_date: string;
  is_trial: boolean;
}

// Define available models for logo generation
const availableModels = [
  { id: 'FLUX-PRO', nameKey: 'Sool Designer pro', description: 'A professional logo design model' },
  { id: 'flux', nameKey: 'Sool Designer 0.2v', description: 'A logo design model' },
  { id: 'FLUX-3D', nameKey: 'Sool Designer 0.1v 3D', description: 'A 3D logo design model' },
  { id: 'Flux-cablyai', nameKey: 'Sool Designer 0.1v', description: 'A logo design model' },
];

// Enhanced color palette options
const colorPalettes = [
  { name: 'Modern Blue', colors: ['#3B82F6', '#1D4ED8', '#60A5FA'] },
  { name: 'Vibrant Purple', colors: ['#8B5CF6', '#7C3AED', '#A78BFA'] },
  { name: 'Fresh Green', colors: ['#10B981', '#059669', '#34D399'] },
  { name: 'Warm Orange', colors: ['#F59E0B', '#D97706', '#FBBF24'] },
  { name: 'Classic Black', colors: ['#000000', '#374151', '#6B7280'] },
  { name: 'Elegant Gold', colors: ['#F59E0B', '#D97706', '#FDE047'] }
];

// Industry templates with smart suggestions
const industryTemplates = {
  'Technology': {
    suggestedStyles: ['Modern', 'Futuristic', 'Minimalist'],
    suggestedColors: ['#3B82F6', '#8B5CF6', '#06B6D4'],
    suggestedElements: 'circuits, geometric shapes, abstract symbols'
  },
  'Health & Wellness': {
    suggestedStyles: ['Clean', 'Organic', 'Trustworthy'],
    suggestedColors: ['#10B981', '#3B82F6', '#F59E0B'],
    suggestedElements: 'leaves, hearts, wellness symbols'
  },
  'Finance': {
    suggestedStyles: ['Professional', 'Trustworthy', 'Classic'],
    suggestedColors: ['#1F2937', '#3B82F6', '#059669'],
    suggestedElements: 'arrows, graphs, stability symbols'
  },
  'Fashion': {
    suggestedStyles: ['Elegant', 'Modern', 'Minimalist'],
    suggestedColors: ['#E879F9', '#F472B6', '#FBCFE8'],
    suggestedElements: 'abstract shapes, flowing lines, stylized initials'
  },
  'Food & Beverage': {
    suggestedStyles: ['Playful', 'Organic', 'Bold'],
    suggestedColors: ['#F59E0B', '#EF4444', '#22C55E'],
    suggestedElements: 'fruits, vegetables, kitchen utensils, abstract food shapes'
  },
  'Real Estate': {
    suggestedStyles: ['Professional', 'Trustworthy', 'Modern'],
    suggestedColors: ['#1D4ED8', '#059669', '#F59E0B'],
    suggestedElements: 'houses, buildings, keys, roofs, geometric shapes'
  },
  'Education': {
    suggestedStyles: ['Clean', 'Inspiring', 'Friendly'],
    suggestedColors: ['#6366F1', '#3B82F6', '#F59E0B'],
    suggestedElements: 'books, graduation caps, lightbulbs, abstract learning symbols'
  },
  'Entertainment': {
    suggestedStyles: ['Creative', 'Bold', 'Vibrant'],
    suggestedColors: ['#A855F7', '#EC4899', '#F97316'],
    suggestedElements: 'stars, abstract shapes, musical notes, film reels'
  },
  'Sports & Fitness': {
    suggestedStyles: ['Dynamic', 'Bold', 'Energetic'],
    suggestedColors: ['#EF4444', '#3B82F6', '#10B981'],
    suggestedElements: 'abstract motion, athletic figures, sports equipment'
  },
  'Automotive': {
    suggestedStyles: ['Sleek', 'Modern', 'Powerful'],
    suggestedColors: ['#1F2937', '#6B7280', '#EF4444'],
    suggestedElements: 'car silhouettes, wheels, speed lines, geometric shapes'
  }
};

const LOCAL_STORAGE_LOGO_GEN_DATE_KEY = 'lastLogoGenerationDate';

const LogoDesigner = () => {
  const { t } = useTranslation();
  const session = useSession();
  const isAuthenticated = !!session;

  // Form State
  const [brandName, setBrandName] = useState('');
  const [industry, setIndustry] = useState('');
  const [targetAudience, setTargetAudience] = useState('');
  const [style, setStyle] = useState('');
  const [colors, setColors] = useState('#6366f1');
  const [keyElements, setKeyElements] = useState('');
  const [textInLogo, setTextInLogo] = useState('');
  const [negativeConstraints, setNegativeConstraints] = useState('');
  
  // Advanced options
  const [logoComplexity, setLogoComplexity] = useState([50]);
  const [logoSize, setLogoSize] = useState('medium');
  const [logoOrientation, setLogoOrientation] = useState('square');
  const [selectedModel, setSelectedModel] = useState(availableModels[0].id);
  
  // UI State
  const [generatedImageUrls, setGeneratedImageUrls] = useState(null);
  const [loadingGeneration, setLoadingGeneration] = useState(false);
  const [errorGeneration, setErrorGeneration] = useState(null);
  const [isDownloading, setIsDownloading] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');
  const [favoriteLogos, setFavoriteLogos] = useState(new Set());
  const [limitReachedReason, setLimitReachedReason] = useState(null);
  
  // User Data State
  const [userProfile, setUserProfile] = useState(null);
  const [userSubscription, setUserSubscription] = useState(null);
  const [isLoadingUserData, setIsLoadingUserData] = useState(true);

  // Fetch user profile and subscription
  useEffect(() => {
    const fetchUserData = async () => {
      if (!isAuthenticated || !session?.user?.id) {
        setUserProfile(null);
        setUserSubscription(null);
        setIsLoadingUserData(false);
        return;
      }

      setIsLoadingUserData(true);
      const userId = session.user.id;

      // Fetch profile
      let { data: profileData, error: profileError } = await supabase
        .from('profiles')
        .select('id, logo_generations_this_month, last_logo_generation_month')
        .eq('id', userId)
        .single();

      if (profileError && profileError.code === 'PGRST116') {
        const { data: newProfileData, error: insertError } = await supabase
          .from('profiles')
          .insert([{ id: userId }])
          .select('id, logo_generations_this_month, last_logo_generation_month')
          .single();

        if (insertError) {
          showError(t('accountPage.toast.createProfileError') + `: ${insertError.message}`);
          setUserProfile(null);
        } else {
          profileData = newProfileData;
        }
      } else if (profileError) {
        showError(t('accountPage.toast.fetchProfileError') + `: ${profileError.message}`);
        setUserProfile(null);
      }

      if (profileData) {
        const currentMonth = new Date();
        const lastMonth = profileData.last_logo_generation_month ? new Date(profileData.last_logo_generation_month) : null;
        const isSameMonth = lastMonth && lastMonth.getMonth() === currentMonth.getMonth() && lastMonth.getFullYear() === currentMonth.getFullYear();

        if (!isSameMonth) {
          const { error: updateError } = await supabase
            .from('profiles')
            .update({
              logo_generations_this_month: 0,
              last_logo_generation_month: currentMonth.toISOString().split('T')[0]
            })
            .eq('id', userId);

          if (updateError) {
            showError(t('accountPage.toast.resetCountError'));
            setUserProfile(profileData);
          } else {
            setUserProfile({ ...profileData, logo_generations_this_month: 0, last_logo_generation_month: currentMonth.toISOString().split('T')[0] });
          }
        } else {
          setUserProfile(profileData);
        }
      }

      // Fetch subscription
      const { data: subscriptionData, error: subscriptionError } = await supabase
        .from('subscriptions')
        .select('id, plan, end_date, is_trial')
        .eq('company_id', userId)
        .gte('end_date', new Date().toISOString().split('T')[0])
        .single();

      if (subscriptionError && subscriptionError.code !== 'PGRST116') {
        showError(t('accountPage.toast.fetchSubscriptionError') + `: ${subscriptionError.message}`);
        setUserSubscription(null);
      } else {
        setUserSubscription(subscriptionData);
      }

      setIsLoadingUserData(false);
    };

    fetchUserData();
  }, [session, isAuthenticated, t]);

  // Smart suggestions
  const getSmartSuggestions = () => {
    const suggestions = [];
    
    if (industry && industryTemplates[industry]) {
      const template = industryTemplates[industry];
      if (!style) {
        suggestions.push({
          type: 'style',
          text: `Try "${template.suggestedStyles[0]}" style for ${industry}`,
          action: () => setStyle(template.suggestedStyles[0])
        });
      }
      if (!keyElements) {
        suggestions.push({
          type: 'elements',
          text: `Consider adding: ${template.suggestedElements}`,
          action: () => setKeyElements(template.suggestedElements)
        });
      }
    }
    
    if (brandName && !textInLogo) {
      suggestions.push({
        type: 'text',
        text: `Include "${brandName}" in the logo`,
        action: () => setTextInLogo(brandName)
      });
    }
    
    return suggestions;
  };

  // Progress calculation
  const getFormProgress = () => {
    const fields = [brandName, industry, targetAudience, style, colors, keyElements];
    const filledFields = fields.filter(field => field && field.trim()).length;
    return Math.round((filledFields / fields.length) * 100);
  };

  // Logo generation
  const handleGenerateLogo = async () => {
    if (loadingGeneration) return;

    // Validate required fields
    if (!brandName.trim() && !industry.trim() && !keyElements.trim()) {
      setErrorGeneration(t('logoDesignerPage.validation.minimumInput'));
      return;
    }

    let logoGenerationLimit = 3;
    let currentLogoGenerations = 0;
    let canGenerate = false;
    let limitReason = null;

    if (!isAuthenticated) {
      const lastGenDate = localStorage.getItem(LOCAL_STORAGE_LOGO_GEN_DATE_KEY);
      const today = new Date().toDateString();
      if (lastGenDate === today) {
        limitReason = 'free_tier';
      } else {
        canGenerate = true;
        logoGenerationLimit = 1;
      }
    } else {
      if (isLoadingUserData || !userProfile) {
        showError(t('logoDesignerPage.toast.userDataLoading'));
        return;
      }

      currentLogoGenerations = userProfile.logo_generations_this_month || 0;
      const lastMonth = userProfile.last_logo_generation_month ? new Date(userProfile.last_logo_generation_month) : null;
      const currentMonth = new Date();
      const isSameMonth = lastMonth && lastMonth.getMonth() === currentMonth.getMonth() && lastMonth.getFullYear() === currentMonth.getFullYear();

      if (userSubscription) {
        if (userSubscription.is_trial) {
          logoGenerationLimit = 10;
        } else {
          switch (userSubscription.plan) {
            case '50': logoGenerationLimit = 25; break;
            case '100': logoGenerationLimit = 50; break;
            case 'unlimited': logoGenerationLimit = 'unlimited'; break;
            default: logoGenerationLimit = 3; break;
          }
        }
      }

      if (logoGenerationLimit !== 'unlimited' && currentLogoGenerations >= logoGenerationLimit && isSameMonth) {
        limitReason = userSubscription ? 'plan_limit' : 'free_tier';
      } else {
        canGenerate = true;
      }
    }

    if (limitReason) {
      setLimitReachedReason(limitReason);
      return;
    }

    setLoadingGeneration(true);
    setErrorGeneration(null);
    setGeneratedImageUrls(null);
    const toastId = showLoading(t('logoDesignerPage.toast.generating'));

    const constructedPrompt = `
      Create a professional logo design for "${brandName.trim() || 'Brand'}".

      Brand Specifications:
      - Industry: ${industry.trim() || 'General Business'}
      - Target Audience: ${targetAudience.trim() || 'Professional Market'}

      Design Requirements:
      - Style: ${style.trim() || 'Modern minimalist'}
      - Color Palette: ${colors} with strategic accent colors
      - Typography: ${textInLogo.trim() ? `Include text "${textInLogo.trim()}"` : 'Icon-focused design'}
      - Key Elements: ${keyElements.trim() || 'Clean geometric forms'}
      - Complexity Level: ${logoComplexity[0]}% visual detail
      - Format: ${logoOrientation} layout, optimized for ${logoSize}

      Technical Specifications:
      - Vector-based design for infinite scalability
      - High contrast for readability at any size
      - Production-ready with proper spacing and proportions
      - Versatile across print and digital media

      Constraints:
      ${negativeConstraints.trim() || 'Avoid: overcomplicated details, poor legibility, generic clipart, inconsistent styling'}

      Output: Single definitive logo design that embodies the brand essence while maintaining professional versatility.
    `.trim();

    try {
      const { data, error: functionError } = await supabase.functions.invoke(
        'generate-image',
        {
          body: {
            prompt: constructedPrompt,
            modelType: selectedModel,
            outputType: 'multiple'
          }
        }
      );

      dismissToast(toastId);

      if (functionError || (data && data.error)) {
        const errorMsg = functionError?.message || data?.error?.message || t('logoDesignerPage.toast.generationError');
        setErrorGeneration(errorMsg);
      } else if (data && data.imageUrls && data.imageUrls.length > 0) {
        setGeneratedImageUrls(data.imageUrls);
        showSuccess(t('logoDesignerPage.toast.generationSuccess'));

        const logosToInsert = data.imageUrls.map(url => ({
          user_id: session?.user?.id || null,
          prompt: constructedPrompt,
          image_url: url
        }));

        const { error: insertError } = await supabase
          .from('generated_logos')
          .insert(logosToInsert);

        if (insertError) {
          showError(t('logoDesignerPage.toast.saveError') + `: ${insertError.message}`);
        } else if (isAuthenticated && session?.user?.id && logoGenerationLimit !== 'unlimited') {
          const userId = session.user.id;
          const { data: latestProfile, error: latestProfileError } = await supabase
            .from('profiles')
            .select('logo_generations_this_month, last_logo_generation_month')
            .eq('id', userId)
            .single();

          if (latestProfileError && latestProfileError.code !== 'PGRST116') {
            showError(t('logoDesignerPage.toast.incrementCountError'));
          } else {
            const latestGenerations = latestProfile?.logo_generations_this_month || 0;
            const latestLastMonth = latestProfile?.last_logo_generation_month ? new Date(latestProfile.last_logo_generation_month) : null;
            const latestCurrentMonth = new Date();
            const isLatestSameMonth = latestLastMonth && latestLastMonth.getMonth() === latestCurrentMonth.getMonth() && latestLastMonth.getFullYear() === latestCurrentMonth.getFullYear();

            let generationsToUpdate = latestGenerations;
            let lastMonthToUpdate = latestLastMonth;

            if (!isLatestSameMonth) {
              generationsToUpdate = 0;
              lastMonthToUpdate = latestCurrentMonth;
            }

            const { error: updateError } = await supabase
              .from('profiles')
              .update({
                logo_generations_this_month: generationsToUpdate + 1,
                last_logo_generation_month: lastMonthToUpdate?.toISOString().split('T')[0] || latestCurrentMonth.toISOString().split('T')[0]
              })
              .eq('id', userId);

            if (updateError) {
              showError(t('logoDesignerPage.toast.incrementCountError'));
            } else {
              setUserProfile(prevProfile => ({
                ...prevProfile,
                logo_generations_this_month: generationsToUpdate + 1,
                last_logo_generation_month: lastMonthToUpdate?.toISOString().split('T')[0] || latestCurrentMonth.toISOString().split('T')[0]
              }));
            }
          }
        } else if (!isAuthenticated) {
          localStorage.setItem(LOCAL_STORAGE_LOGO_GEN_DATE_KEY, new Date().toDateString());
          setLimitReachedReason('free_tier');
        }
      } else {
        setErrorGeneration(t('logoDesignerPage.toast.unexpectedResponse'));
      }
    } catch (err) {
      dismissToast(toastId);
      setErrorGeneration(t('logoDesignerPage.toast.generationErrorUnexpected') + `: ${err.message}`);
    } finally {
      setLoadingGeneration(false);
    }
  };

  // Download image
  const handleDownloadImage = async (imageUrl, format = 'png') => {
    if (!imageUrl || isDownloading) {
      if (!imageUrl) showError(t('logoDesignerPage.toast.downloadErrorEmpty'));
      return;
    }

    setIsDownloading(true);
    const toastId = showLoading(t('logoDesignerPage.toast.downloading'));

    try {
      const response = await fetch(imageUrl, { mode: 'cors' });
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${brandName || 'logo'}-${Date.now()}.${format}`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      dismissToast(toastId);
      showSuccess(t('logoDesignerPage.toast.downloadSuccess'));
    } catch (err) {
      dismissToast(toastId);
      showError(t('logoDesignerPage.toast.downloadError') + `: ${err.message}`);
    } finally {
      setIsDownloading(false);
    }
  };

  // Toggle favorite logo
  const toggleFavorite = (index) => {
    const newFavorites = new Set(favoriteLogos);
    if (newFavorites.has(index)) {
      newFavorites.delete(index);
    } else {
      newFavorites.add(index);
    }
    setFavoriteLogos(newFavorites);
  };

  // Reset form
  const handleResetForm = () => {
    setBrandName('');
    setIndustry('');
    setTargetAudience('');
    setStyle('');
    setColors('#6366f1');
    setKeyElements('');
    setTextInLogo('');
    setNegativeConstraints('');
    setLogoComplexity([50]);
    setLogoSize('medium');
    setLogoOrientation('square');
    setSelectedModel(availableModels[0].id);
    setGeneratedImageUrls(null);
    setErrorGeneration(null);
    setFavoriteLogos(new Set());
  };

  // Auto-save to local storage
  useEffect(() => {
    const formData = {
      brandName, industry, targetAudience, style, colors,
      keyElements, textInLogo, negativeConstraints,
      logoComplexity, logoSize, logoOrientation, selectedModel
    };
    localStorage.setItem('logoDesignerForm', JSON.stringify(formData));
  }, [brandName, industry, targetAudience, style, colors, keyElements, textInLogo, negativeConstraints, logoComplexity, logoSize, logoOrientation, selectedModel]);

  // Load from local storage
  useEffect(() => {
    const saved = localStorage.getItem('logoDesignerForm');
    if (saved) {
      try {
        const data = JSON.parse(saved);
        setBrandName(data.brandName || '');
        setIndustry(data.industry || '');
        setTargetAudience(data.targetAudience || '');
        setStyle(data.style || '');
        setColors(data.colors || '#6366f1');
        setKeyElements(data.keyElements || '');
        setTextInLogo(data.textInLogo || '');
        setNegativeConstraints(data.negativeConstraints || '');
        setLogoComplexity(data.logoComplexity || [50]);
        setLogoSize(data.logoSize || 'medium');
        setLogoOrientation(data.logoOrientation || 'square');
        setSelectedModel(data.selectedModel || availableModels[0].id);
      } catch (e) {
        console.error('Failed to load saved form data');
      }
    }
  }, []);

  const suggestions = getSmartSuggestions();
  const progress = getFormProgress();
  let logoGenerationLimitDisplay = isAuthenticated && userSubscription ? 
    (userSubscription.is_trial ? 10 : 
     userSubscription.plan === 'unlimited' ? t('accountPage.unlimited') : 
     userSubscription.plan === '100' ? 50 : 25) : 3;
  const currentLogoGenerationsDisplay = userProfile?.logo_generations_this_month || 0;
  const displayUsageText = isAuthenticated && logoGenerationLimitDisplay !== t('accountPage.unlimited') ?
    `${currentLogoGenerationsDisplay}/${logoGenerationLimitDisplay}` : logoGenerationLimitDisplay;

  return (
    <TooltipProvider>
      <div className="min-h-screen">
        <div className="container mx-auto p-4 lg:p-8 space-y-8">
          {/* Header */}
          <div className="text-center space-y-4">
            <div className="flex items-center justify-center space-x-3 mb-6">
              <div className="relative">
                <Palette className="h-12 w-12 text-purple-400" />
                <Sparkles className="h-6 w-6 text-yellow-400 absolute -top-1 -right-1 animate-pulse" />
              </div>
            </div>
            <h1 className="text-4xl lg:text-6xl font-bold bg-gradient-to-r from-purple-400 via-pink-400 to-indigo-400 bg-clip-text text-transparent">
              AI Logo Designer
            </h1>
            <p className="text-xl text-slate-300 max-w-2xl mx-auto">
              Create stunning, professional logos in seconds with AI-powered design intelligence
            </p>
            <div className="flex items-center justify-center space-x-8 text-sm text-slate-400 bg-slate-800/50 rounded-full px-6 py-3 backdrop-blur-sm">
              <div className="flex items-center space-x-2">
                <Crown className="h-4 w-4 text-yellow-400" />
                <span>Premium Quality</span>
              </div>
              <div className="flex items-center space-x-2">
                <Zap className="h-4 w-4 text-blue-400" />
                <span>{displayUsageText} generations left</span>
              </div>
              <div className="flex items-center space-x-2">
                <Target className="h-4 w-4 text-green-400" />
                <span>Industry-specific</span>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 xl:grid-cols-5 gap-8">
            {/* Form Section */}
            <div className="xl:col-span-2 space-y-6">
              <Card className="bg-slate-900/50 border-slate-700/50 backdrop-blur-sm">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-xl text-white flex items-center space-x-2">
                      <Wand2 className="h-5 w-5 text-purple-400" />
                      <span>Design Brief</span>
                    </CardTitle>
                    <Badge variant="outline" className="text-purple-400 border-purple-400">
                      {progress}% Complete
                    </Badge>
                  </div>
                  <Progress value={progress} className="h-2" />
                </CardHeader>
                
                <CardContent className="space-y-6">
                  <Tabs value={activeTab} onValueChange={setActiveTab}>
                    <TabsList className="grid w-full grid-cols-2 bg-slate-800">
                      <TabsTrigger value="basic" className="text-xs">Basic Info</TabsTrigger>
                      <TabsTrigger value="advanced" className="text-xs">Style & Advanced</TabsTrigger>
                    </TabsList>
                    
                    <TabsContent value="basic" className="space-y-4 mt-6">
                      <div className="space-y-2">
                        <Label className="text-white flex items-center space-x-2">
                          <Type className="h-4 w-4" />
                          <span>Brand Name</span>
                        </Label>
                        <Input
                          value={brandName}
                          onChange={(e) => setBrandName(e.target.value)}
                          placeholder="Enter your brand name"
                          className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-400"
                        />
                      </div>

                      <div className="space-y-2">
                        <Label className="text-white flex items-center space-x-2">
                          <Layers className="h-4 w-4" />
                          <span>Industry</span>
                        </Label>
                        <Select value={industry} onValueChange={setIndustry}>
                          <SelectTrigger className="bg-slate-800 border-slate-600 text-white">
                            <SelectValue placeholder="Select your industry" />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-800 border-slate-600">
                            <SelectItem value="Technology">💻 Technology</SelectItem>
                            <SelectItem value="Health & Wellness">🏥 Health & Wellness</SelectItem>
                            <SelectItem value="Finance">💰 Finance</SelectItem>
                            <SelectItem value="Fashion">👗 Fashion</SelectItem>
                            <SelectItem value="Food & Beverage">🍕 Food & Beverage</SelectItem>
                            <SelectItem value="Real Estate">🏠 Real Estate</SelectItem>
                            <SelectItem value="Education">📚 Education</SelectItem>
                            <SelectItem value="Entertainment">🎬 Entertainment</SelectItem>
                            <SelectItem value="Sports & Fitness">⚽ Sports & Fitness</SelectItem>
                            <SelectItem value="Automotive">🚗 Automotive</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label className="text-white flex items-center space-x-2">
                          <Target className="h-4 w-4" />
                          <span>Target Audience</span>
                        </Label>
                        <Select value={targetAudience} onValueChange={setTargetAudience}>
                          <SelectTrigger className="bg-slate-800 border-slate-600 text-white">
                            <SelectValue placeholder="Who is your target audience?" />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-800 border-slate-600">
                            <SelectItem value="General Consumers">👥 General Consumers</SelectItem>
                            <SelectItem value="Small Businesses">🏪 Small Businesses</SelectItem>
                            <SelectItem value="Corporate Clients">🏢 Corporate Clients</SelectItem>
                            <SelectItem value="Young Adults">🎯 Young Adults (18-35)</SelectItem>
                            <SelectItem value="Luxury Market">💎 Luxury Market</SelectItem>
                            <SelectItem value="Tech Enthusiasts">⚡ Tech Enthusiasts</SelectItem>
                            <SelectItem value="Eco-Conscious">🌱 Eco-Conscious Consumers</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label className="text-white flex items-center space-x-2">
                          <Lightbulb className="h-4 w-4" />
                          <span>Key Elements</span>
                        </Label>
                        <Textarea
                          value={keyElements}
                          onChange={(e) => setKeyElements(e.target.value)}
                          placeholder="Describe elements you want in your logo (e.g., mountain, star, abstract shape)"
                          className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-400 min-h-[80px]"
                        />
                      </div>
                    </TabsContent>
                    
                    <TabsContent value="advanced" className="space-y-4 mt-6">
                      <div className="space-y-2">
                        <Label className="text-white">Design Style</Label>
                        <Select value={style} onValueChange={setStyle}>
                          <SelectTrigger className="bg-slate-800 border-slate-600 text-white">
                            <SelectValue placeholder="Choose a design style" />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-800 border-slate-600">
                            <SelectItem value="Minimalist">✨ Minimalist</SelectItem>
                            <SelectItem value="Modern">🔥 Modern</SelectItem>
                            <SelectItem value="Classic">👑 Classic</SelectItem>
                            <SelectItem value="Vintage">📜 Vintage</SelectItem>
                            <SelectItem value="Bold">💪 Bold</SelectItem>
                            <SelectItem value="Elegant">💫 Elegant</SelectItem>
                            <SelectItem value="Playful">🎨 Playful</SelectItem>
                            <SelectItem value="Geometric">📐 Geometric</SelectItem>
                            <SelectItem value="Abstract">🌀 Abstract</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label className="text-white">Model Selection</Label>
                        <Select value={selectedModel} onValueChange={setSelectedModel}>
                          <SelectTrigger className="bg-slate-800 border-slate-600 text-white">
                            <SelectValue placeholder="Select a model" />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-800 border-slate-600">
                            {availableModels.map((model) => (
                              <SelectItem key={model.id} value={model.id}>
                                {t(model.nameKey)}
                                <br />
                                <p className="text-xs text-slate-400">{t(model.description)}</p>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-3">
                        <Label className="text-white">Color Palette</Label>
                        <div className="flex items-center space-x-3">
                          <input
                            type="color"
                            value={colors}
                            onChange={(e) => setColors(e.target.value)}
                            className="w-12 h-10 rounded border-2 border-slate-600 bg-slate-800"
                          />
                          <Input
                            value={colors}
                            onChange={(e) => setColors(e.target.value)}
                            placeholder="#6366f1"
                            className="bg-slate-800 border-slate-600 text-white"
                          />
                        </div>
                        <div className="grid grid-cols-3 gap-2">
                          {colorPalettes.map((palette, index) => (
                            <Tooltip key={index}>
                              <TooltipTrigger asChild>
                                <button
                                  onClick={() => setColors(palette.colors[0])}
                                  className="flex items-center space-x-1 p-2 rounded bg-slate-800 hover:bg-slate-700 transition-colors"
                                >
                                  {palette.colors.map((color, i) => (
                                    <div
                                      key={i}
                                      className="w-4 h-4 rounded-full border border-slate-600"
                                      style={{ backgroundColor: color }}
                                    />
                                  ))}
                                </button>
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{palette.name}</p>
                              </TooltipContent>
                            </Tooltip>
                          ))}
                        </div>
                      </div>

                      <div className="space-y-3">
                        <Label className="text-white flex items-center justify-between">
                          <span>Design Complexity</span>
                          <span className="text-sm text-slate-400">{logoComplexity[0]}%</span>
                        </Label>
                        <Slider
                          value={logoComplexity}
                          onValueChange={setLogoComplexity}
                          max={100}
                          step={10}
                          className="w-full"
                        />
                        <div className="flex justify-between text-xs text-slate-400">
                          <span>Minimal</span>
                          <span>Balanced</span>
                          <span>Detailed</span>
                        </div>
                      </div>

                      <div className="space-y-2">
                        <Label className="text-white">Logo Orientation</Label>
                        <Select value={logoOrientation} onValueChange={setLogoOrientation}>
                          <SelectTrigger className="bg-slate-800 border-slate-600 text-white">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-800 border-slate-600">
                            <SelectItem value="square">⬜ Square</SelectItem>
                            <SelectItem value="horizontal">➖ Horizontal</SelectItem>
                            <SelectItem value="vertical">📏 Vertical</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label className="text-white">Text in Logo (Optional)</Label>
                        <Input
                          value={textInLogo}
                          onChange={(e) => setTextInLogo(e.target.value)}
                          placeholder="Enter text to include in logo"
                          className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-400"
                        />
                      </div>

                      <div className="space-y-2">
                        <Label className="text-white">Avoid These Elements</Label>
                        <Textarea
                          value={negativeConstraints}
                          onChange={(e) => setNegativeConstraints(e.target.value)}
                          placeholder="What should be avoided in the design? (e.g., too much text, dark colors)"
                          className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-400"
                        />
                      </div>
                    </TabsContent>
                  </Tabs>

                  {suggestions.length > 0 && (
                    <Card className="bg-blue-950/30 border-blue-800/50">
                      <CardContent className="p-4">
                        <div className="flex items-center space-x-2 text-blue-400 mb-3">
                          <Lightbulb className="h-4 w-4" />
                          <span className="font-medium">Smart Suggestions</span>
                        </div>
                        <div className="space-y-2">
                          {suggestions.map((suggestion, index) => (
                            <button
                              key={index}
                              onClick={suggestion.action}
                              className="flex items-center justify-between w-full p-2 text-left text-sm bg-blue-900/30 hover:bg-blue-900/50 rounded border border-blue-800/30 text-blue-100 transition-colors"
                            >
                              <span>{suggestion.text}</span>
                              <ChevronRight className="h-4 w-4" />
                            </button>
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  )}

                  <div className="flex space-x-3 pt-4">
                    <Button
                      onClick={handleGenerateLogo}
                      disabled={loadingGeneration || isLoadingUserData}
                      className="flex-1 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white font-semibold py-3 rounded-lg transition-all duration-200 transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {loadingGeneration ? (
                        <>
                          <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                          Creating Magic...
                        </>
                      ) : (
                        <>
                          <Sparkles className="mr-2 h-4 w-4" />
                          Generate Logo
                        </>
                      )}
                    </Button>
                    
                    <Button
                      variant="outline"
                      onClick={handleResetForm}
                      className="px-4 border-slate-600 text-slate-300 hover:bg-slate-800"
                    >
                      <RefreshCw className="h-4 w-4" />
                    </Button>
                  </div>

                  {errorGeneration && (
                    <Alert className="border-red-800 bg-red-950/30">
                      <AlertDescription className="text-red-200">
                        {errorGeneration}
                      </AlertDescription>
                    </Alert>
                  )}
                </CardContent>
              </Card>
            </div>

            {/* Results Section */}
            <div className="xl:col-span-3 space-y-6">
              {loadingGeneration && (
                <Card className="bg-slate-900/50 border-slate-700/50 backdrop-blur-sm">
                  <CardContent className="p-8">
                    <div className="text-center space-y-4">
                      <div className="relative mx-auto w-16 h-16">
                        <div className="absolute inset-0 rounded-full border-4 border-purple-600/30"></div>
                        <div className="absolute inset-0 rounded-full border-4 border-purple-600 border-t-transparent animate-spin"></div>
                        <Sparkles className="absolute inset-0 m-auto h-6 w-6 text-purple-400 animate-pulse" />
                      </div>
                      <div className="space-y-2">
                        <h3 className="text-lg font-semibold text-white">Creating Your Logo</h3>
                        <p className="text-slate-400">Our AI is crafting unique designs tailored to your brand...</p>
                      </div>
                      <div className="grid grid-cols-2 gap-4 mt-6">
                        {[1, 2, 3, 4].map((i) => (
                          <Skeleton key={i} className="aspect-square rounded-lg bg-slate-800" />
                        ))}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {generatedImageUrls && !loadingGeneration && (
                <Card className="bg-slate-900/50 border-slate-700/50 backdrop-blur-sm">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-xl text-white flex items-center space-x-2">
                        <ImageIcon className="h-5 w-5 text-green-400" />
                        <span>Your Logo Variations</span>
                      </CardTitle>
                      <Badge className="bg-green-900/50 text-green-300 border-green-700">
                        {generatedImageUrls.length} Designs Created
                      </Badge>
                    </div>
                  </CardHeader>
                  
                  <CardContent className="space-y-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      {generatedImageUrls.map((imageUrl, index) => (
                        <div key={index} className="group relative">
                          <div className="relative overflow-hidden rounded-lg bg-slate-800 border border-slate-700 hover:border-purple-500 transition-all duration-300">
                            <img
                              src={imageUrl}
                              alt={`Logo variation ${index + 1}`}
                              className="w-full aspect-square object-cover transition-transform duration-300 group-hover:scale-105"
                            />
                            
                            <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center">
                              <div className="flex space-x-3">
                                <Button
                                  size="sm"
                                  variant="secondary"
                                  onClick={() => toggleFavorite(index)}
                                  className={`${favoriteLogos.has(index) ? 'bg-red-600 hover:bg-red-700' : 'bg-slate-700 hover:bg-slate-600'}`}
                                >
                                  <Heart className={`h-4 w-4 ${favoriteLogos.has(index) ? 'fill-current' : ''}`} />
                                </Button>
                                
                                <Button
                                  size="sm"
                                  onClick={() => handleDownloadImage(imageUrl)}
                                  disabled={isDownloading}
                                  className="bg-purple-600 hover:bg-purple-700"
                                >
                                  <Download className="h-4 w-4" />
                                </Button>
                              </div>
                            </div>
                            
                            <div className="absolute top-3 left-3">
                              <Badge className="bg-black/70 text-white border-none">
                                {index === 0 ? 'Primary' : 
                                 index === 1 ? 'Icon Only' : 
                                 index === 2 ? 'Horizontal' : 'Monochrome'}
                              </Badge>
                            </div>
                            
                            {favoriteLogos.has(index) && (
                              <div className="absolute top-3 right-3">
                                <Star className="h-5 w-5 text-yellow-400 fill-current" />
                              </div>
                            )}
                          </div>
                          
                          <div className="mt-3 space-y-2">
                            <div className="flex items-center justify-between">
                              <span className="text-sm font-medium text-white">
                                Variation {index + 1}
                              </span>
                              <div className="flex space-x-2">
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() => handleDownloadImage(imageUrl, 'png')}
                                  className="text-xs border-slate-600 text-slate-300 hover:bg-slate-800"
                                >
                                  PNG
                                </Button>
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() => handleDownloadImage(imageUrl, 'svg')}
                                  className="text-xs border-slate-600 text-slate-300 hover:bg-slate-800"
                                >
                                  SVG
                                </Button>
                              </div>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                    
                    <div className="flex flex-wrap gap-3 pt-4 border-t border-slate-700">
                      <Button
                        onClick={() => generatedImageUrls.forEach(url => handleDownloadImage(url))}
                        disabled={isDownloading}
                        className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700"
                      >
                        <Download className="mr-2 h-4 w-4" />
                        Download All
                      </Button>
                      
                      <Button
                        variant="outline"
                        onClick={() => setGeneratedImageUrls(null)}
                        className="border-slate-600 text-slate-300 hover:bg-slate-800"
                      >
                        <RefreshCw className="mr-2 h-4 w-4" />
                        Clear Results
                      </Button>
                      
                      <Button
                        variant="outline"
                        onClick={handleGenerateLogo}
                        disabled={loadingGeneration}
                        className="border-slate-600 text-slate-300 hover:bg-slate-800"
                      >
                        <Wand2 className="mr-2 h-4 w-4" />
                        Generate More
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              )}

              {!generatedImageUrls && !loadingGeneration && (
                <Card className="bg-slate-900/50 border-slate-700/50 backdrop-blur-sm">
                  <CardContent className="p-12 text-center">
                    <div className="space-y-6">
                      <div className="relative mx-auto w-24 h-24">
                        <div className="absolute inset-0 rounded-full bg-gradient-to-r from-purple-600 to-pink-600 opacity-20"></div>
                        <Palette className="absolute inset-0 m-auto h-12 w-12 text-purple-400" />
                      </div>
                      
                      <div className="space-y-3">
                        <h3 className="text-2xl font-bold text-white">Ready to Create Amazing Logos?</h3>
                        <p className="text-slate-400 max-w-md mx-auto">
                          Fill out the design brief on the left and click "Generate Logo" to create professional logos powered by AI.
                        </p>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-8 text-sm">
                        <div className="p-4 bg-slate-800/50 rounded-lg border border-slate-700">
                          <Zap className="h-6 w-6 text-yellow-400 mx-auto mb-2" />
                          <div className="font-medium text-white mb-1">Lightning Fast</div>
                          <div className="text-slate-400">Get results in seconds</div>
                        </div>
                        
                        <div className="p-4 bg-slate-800/50 rounded-lg border border-slate-700">
                          <Star className="h-6 w-6 text-purple-400 mx-auto mb-2" />
                          <div className="font-medium text-white mb-1">Professional Quality</div>
                          <div className="text-slate-400">Industry-grade designs</div>
                        </div>
                        
                        <div className="p-4 bg-slate-800/50 rounded-lg border border-slate-700">
                          <Grid3X3 className="h-6 w-6 text-green-400 mx-auto mb-2" />
                          <div className="font-medium text-white mb-1">Multiple Formats</div>
                          <div className="text-slate-400">PNG, SVG, and more</div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          </div>

          <Card className="bg-slate-900/30 border-purple-500/20 backdrop-blur-sm">
            <CardContent className="p-6">
              <div className="flex items-start space-x-4">
                <Lightbulb className="h-6 w-6 text-purple-400 mt-1 flex-shrink-0" />
                <div className="space-y-2">
                  <h4 className="font-semibold text-white">Pro Tips for Better Logos</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-slate-300">
                    <div>
                      <strong className="text-purple-400">Be Specific:</strong> The more details you provide about your brand and industry, the better your results will be.
                    </div>
                    <div>
                      <strong className="text-purple-400">Try Different Styles:</strong> Experiment with various design styles to find what resonates with your brand.
                    </div>
                    <div>
                      <strong className="text-purple-400">Color Psychology:</strong> Choose colors that align with your brand personality and target audience.
                    </div>
                    <div>
                      <strong className="text-purple-400">Keep It Simple:</strong> The best logos work at both large and small sizes - simplicity is key.
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </TooltipProvider>
  );
};

export default LogoDesigner;