"use client"; import { useState, useEffect, useCallback } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { Menu, X, Bot, Wand2, ImageIcon, Video, Users, FolderGit2, Shield, RefreshCw, DollarSign, Clock, Film, Zap, TrendingUp, Calendar, Play, Pause, Trash2, Plus, Send, Copy, Eye, Settings, ChevronRight, CheckCircle2, AlertCircle, ExternalLink, CreditCard, Target, Sparkles, Heart, PawPrint, Star, Users2, Lightbulb, Flame, Rocket } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { toast } from "sonner"; // Types interface Content { id: string; type: string; title: string; status: string; platform: string; createdAt: string; } interface Character { id: string; name: string; description: string | null; referenceImage: string | null; } interface Platform { id: string; name: string; type: string; isActive: boolean; isVerified: boolean; } interface Post { id: string; title: string | null; type: string; status: string; scheduledAt: string | null; } interface Story { id: string; title: string; genre: string; status: string; totalEpisodes: number; } interface Automation { id: string; name: string; type: string; isActive: boolean; runCount: number; } interface Pet { id: string; name: string; type: string; breed: string | null; personality: string | null; referenceImage: string | null; } interface Influencer { name: string; handle: string; platform: string; followers: number; engagement: number; niche: string; petCompanion: boolean; petType?: string; keyLessons: string[]; } // API Helper async function apiFetch(endpoint: string, options: RequestInit = {}) { const response = await fetch(`/api${endpoint}`, { headers: { "Content-Type": "application/json", ...options.headers }, ...options, }); return response.json(); } export default function Dashboard() { const [sidebarOpen, setSidebarOpen] = useState(true); const [activeTab, setActiveTab] = useState("prompt-engineer"); const [loading, setLoading] = useState(false); // Prompt Engineer const [userPrompt, setUserPrompt] = useState(""); const [promptType, setPromptType] = useState("image"); const [targetPlatform, setTargetPlatform] = useState("general"); const [optimizedPrompt, setOptimizedPrompt] = useState | null>(null); const [promptLoading, setPromptLoading] = useState(false); // Image Generation const [imagePrompt, setImagePrompt] = useState(""); const [imageStyle, setImageStyle] = useState("realistic"); const [imagePlatform, setImagePlatform] = useState("general"); const [imageLoading, setImageLoading] = useState(false); // Monetization const [platforms, setPlatforms] = useState([]); const [selectedMonetizationPlatform, setSelectedMonetizationPlatform] = useState(""); // Posts const [posts, setPosts] = useState([]); const [postTitle, setPostTitle] = useState(""); const [postType, setPostType] = useState("reel"); const [postCaption, setPostCaption] = useState(""); const [scheduledTime, setScheduledTime] = useState(""); // Stories const [stories, setStories] = useState([]); const [storyPrompt, setStoryPrompt] = useState(""); const [storyGenre, setStoryGenre] = useState("lifestyle"); const [storyEpisodes, setStoryEpisodes] = useState(7); const [storyLoading, setStoryLoading] = useState(false); // Automation const [automations, setAutomations] = useState([]); const [automationName, setAutomationName] = useState(""); const [automationType, setAutomationType] = useState("content_generation"); // Content & Characters const [contents, setContents] = useState([]); const [characters, setCharacters] = useState([]); // Pets const [pets, setPets] = useState([]); const [petName, setPetName] = useState(""); const [petType, setPetType] = useState("dog"); const [petBreed, setPetBreed] = useState(""); const [petPersonality, setPetPersonality] = useState(""); const [includePetInContent, setIncludePetInContent] = useState(false); const [petLoading, setPetLoading] = useState(false); // Influencers const [influencers, setInfluencers] = useState([]); const [influencerNiche, setInfluencerNiche] = useState(""); const [influencerPlatform, setInfluencerPlatform] = useState(""); const [influencerWithPets, setInfluencerWithPets] = useState(false); const [influencerLoading, setInfluencerLoading] = useState(false); const [influencerAnalysis, setInfluencerAnalysis] = useState | null>(null); const [characterConcept, setCharacterConcept] = useState | null>(null); // Trends const [trends, setTrends] = useState[]>([]); const [viralStrategies, setViralStrategies] = useState[]>([]); const [contentIdeas, setContentIdeas] = useState[]>([]); const [trendAnalysis, setTrendAnalysis] = useState | null>(null); const [trendLoading, setTrendLoading] = useState(false); // Stats const [stats, setStats] = useState({ images: 0, videos: 0, stories: 0, automations: 0, pets: 0 }); // Load data const loadData = useCallback(async () => { setLoading(true); try { const [contentRes, platformsRes, postsRes, storiesRes, automationRes, petsRes] = await Promise.all([ apiFetch("/content"), apiFetch("/monetization"), apiFetch("/posts"), apiFetch("/storytelling"), apiFetch("/automation"), apiFetch("/pets"), ]); if (contentRes.success) { setContents(contentRes.contents); setStats({ images: contentRes.stats?.images || 0, videos: contentRes.stats?.videos || 0, stories: storiesRes?.total || 0, automations: automationRes?.stats?.total || 0, pets: petsRes?.total || 0, }); } if (platformsRes.success) setPlatforms(platformsRes.userPlatforms); if (postsRes.success) setPosts(postsRes.posts); if (storiesRes.success) setStories(storiesRes.stories); if (automationRes.success) setAutomations(automationRes.automations); if (petsRes.success) setPets(petsRes.pets); } catch { toast.error("Error al cargar datos"); } finally { setLoading(false); } }, []); useEffect(() => { loadData(); }, [loadData]); // Actions const handleOptimizePrompt = async () => { if (!userPrompt.trim()) { toast.error("Escribe un prompt"); return; } setPromptLoading(true); try { const result = await apiFetch("/prompt-engineer", { method: "POST", body: JSON.stringify({ prompt: userPrompt, type: promptType, platform: targetPlatform }), }); if (result.success) { setOptimizedPrompt(result); toast.success("Prompt optimizado"); } else toast.error(result.error); } catch { toast.error("Error"); } finally { setPromptLoading(false); } }; const handleGenerateImage = async () => { if (!userPrompt.trim()) { toast.error("Escribe un prompt"); return; } setImageLoading(true); try { const result = await apiFetch("/generate/image", { method: "POST", body: JSON.stringify({ prompt: userPrompt, optimizedPrompt: optimizedPrompt?.optimizedPrompt, platform: imagePlatform, style: imageStyle, includePet: includePetInContent, petId: pets[0]?.id }), }); if (result.success) { toast.success("Imagen generada"); loadData(); } else toast.error(result.error); } catch { toast.error("Error"); } finally { setImageLoading(false); } }; const handleCreateStory = async () => { if (!storyPrompt.trim()) { toast.error("Describe tu historia"); return; } setStoryLoading(true); try { const result = await apiFetch("/storytelling", { method: "POST", body: JSON.stringify({ prompt: storyPrompt, genre: storyGenre, totalEpisodes: storyEpisodes, }), }); if (result.success) { toast.success(`Historia "${result.story?.title}" creada`); setStoryPrompt(""); loadData(); } else toast.error(result.error); } catch { toast.error("Error"); } finally { setStoryLoading(false); } }; const handleCreatePost = async () => { if (!postTitle.trim()) { toast.error("Añade un título"); return; } try { const result = await apiFetch("/posts", { method: "POST", body: JSON.stringify({ title: postTitle, type: postType, caption: postCaption, scheduledAt: scheduledTime || null, autoGenerateCaption: true, }), }); if (result.success) { toast.success(scheduledTime ? "Post programado" : "Post creado"); setPostTitle(""); setPostCaption(""); setScheduledTime(""); loadData(); } else toast.error(result.error); } catch { toast.error("Error"); } }; const handleCreateAutomation = async () => { if (!automationName.trim()) { toast.error("Dale un nombre"); return; } try { const result = await apiFetch("/automation", { method: "POST", body: JSON.stringify({ name: automationName, type: automationType, trigger: "schedule", triggerConfig: { schedule: "daily:09:00" }, actions: [{ type: "generate_content", prompt: "Genera contenido de lifestyle" }], }), }); if (result.success) { toast.success("Automatización creada"); setAutomationName(""); loadData(); } else toast.error(result.error); } catch { toast.error("Error"); } }; const handleToggleAutomation = async (id: string, currentStatus: boolean) => { try { await apiFetch("/automation", { method: "PUT", body: JSON.stringify({ id, isActive: !currentStatus }), }); loadData(); } catch { toast.error("Error"); } }; const handleCreatePet = async () => { if (!petName.trim()) { toast.error("Dale un nombre a tu mascota"); return; } setPetLoading(true); try { const result = await apiFetch("/pets", { method: "POST", body: JSON.stringify({ name: petName, type: petType, breed: petBreed || undefined, personality: petPersonality || undefined, generateReference: true }), }); if (result.success) { toast.success(`Mascota "${petName}" creada (+${result.engagementBoost}% engagement)`); setPetName(""); setPetBreed(""); setPetPersonality(""); loadData(); } else toast.error(result.error); } catch { toast.error("Error"); } finally { setPetLoading(false); } }; const handleAnalyzeInfluencers = async () => { setInfluencerLoading(true); try { const result = await apiFetch("/influencers", { method: "POST", body: JSON.stringify({ targetNiche: influencerNiche || "lifestyle", targetPlatform: influencerPlatform || undefined, includePets: influencerWithPets }), }); if (result.success) { setInfluencers(result.referenceInfluencers || []); setInfluencerAnalysis(result.analysis); setCharacterConcept(result.characterConcept); toast.success("Análisis completado"); } else toast.error(result.error); } catch { toast.error("Error"); } finally { setInfluencerLoading(false); } }; const handleAnalyzeTrends = async () => { setTrendLoading(true); try { const result = await apiFetch("/trends", { method: "POST", body: JSON.stringify({ niche: influencerNiche || "lifestyle", platform: influencerPlatform || undefined, includePets: includePetInContent, daysToViral: 14 }), }); if (result.success) { setTrendAnalysis(result.analysis); toast.success("Análisis de tendencias completado"); } else toast.error(result.error); } catch { toast.error("Error"); } finally { setTrendLoading(false); } }; const loadTrends = async () => { try { const result = await apiFetch(`/trends?includePets=${includePetInContent}`); if (result.success) { setTrends(result.trends); setViralStrategies(result.viralStrategies); setContentIdeas(result.contentIdeas); } } catch { toast.error("Error cargando tendencias"); } }; useEffect(() => { if (activeTab === "trends") loadTrends(); }, [activeTab, includePetInContent]); const copyToClipboard = (text: string) => { navigator.clipboard.writeText(text); toast.success("Copiado"); }; const getStatusColor = (status: string) => { const colors: Record = { completed: "bg-green-500/10 text-green-500", published: "bg-green-500/10 text-green-500", scheduled: "bg-blue-500/10 text-blue-500", draft: "bg-slate-500/10 text-slate-400", pending: "bg-yellow-500/10 text-yellow-500", active: "bg-green-500/10 text-green-500", }; return colors[status] || "bg-slate-500/10 text-slate-400"; }; const petTypes = [ { value: "dog", label: "🐕 Perro" }, { value: "cat", label: "🐱 Gato" }, { value: "bird", label: "🐦 Pájaro" }, { value: "rabbit", label: "🐰 Conejo" }, { value: "hamster", label: "🐹 Hámster" } ]; return (
{/* Sidebar */} {sidebarOpen && (

Sofía Cloud

Monetización Pro

{stats.images}

Imágenes

{stats.videos}

Videos

{stats.stories}

Historias

{stats.pets}

Mascotas

)}
{/* Main */}

{activeTab.replace("-", " ")}

{/* Prompt Engineer */} {activeTab === "prompt-engineer" && (
Ingeniero de Prompts Describe en lenguaje natural lo que quieres crear