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 (
{/* Header */}

AI Logo Designer

Create stunning, professional logos in seconds with AI-powered design intelligence

Premium Quality
{displayUsageText} generations left
Industry-specific
{/* Form Section */}
Design Brief {progress}% Complete
Basic Info Style & Advanced
setBrandName(e.target.value)} placeholder="Enter your brand name" className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-400" />