import React, { useState, useEffect, useRef } from 'react';
import { Camera, Plus, Trash2, Edit3, Download, Play, Pause, ChevronDown, 
  Settings, Save, X, FileText, Upload, RefreshCw, Globe, Volume2, Image, 
  Clock, Copy, FileVideo, Check, AlertTriangle, Zap, Layers, UploadCloud, 
  Grid, CheckCircle, Move, ArrowLeft, ArrowRight, SkipBack, SkipForward,
  Music, Mic, Eye, EyeOff, Maximize, Minimize, Monitor, Wind } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import * as d3 from 'd3';

// Mock imports for shadcn UI components
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Slider } from '@/components/ui/slider';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from '@/components/ui/dialog';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import { Progress } from '@/components/ui/progress';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Checkbox } from '@/components/ui/checkbox';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';

// Animation presets for elements
const animationPresets = {
  fadeIn: {
    initial: { opacity: 0 },
    animate: { opacity: 1 },
    exit: { opacity: 0 },
    transition: { duration: 0.5 }
  },
  slideIn: {
    initial: { x: -100, opacity: 0 },
    animate: { x: 0, opacity: 1 },
    exit: { x: 100, opacity: 0 },
    transition: { duration: 0.5 }
  },
  zoomIn: {
    initial: { scale: 0, opacity: 0 },
    animate: { scale: 1, opacity: 1 },
    exit: { scale: 0, opacity: 0 },
    transition: { duration: 0.5 }
  },
  bounceIn: {
    initial: { scale: 0, opacity: 0 },
    animate: { scale: 1, opacity: 1 },
    exit: { scale: 0, opacity: 0 },
    transition: { type: "spring", stiffness: 200, damping: 10 }
  },
  flipIn: {
    initial: { rotateY: 90, opacity: 0 },
    animate: { rotateY: 0, opacity: 1 },
    exit: { rotateY: -90, opacity: 0 },
    transition: { duration: 0.5 }
  }
};

// Helper for getting element animation based on time
const getElementAnimationState = (element, currentTime) => {
  if (currentTime < element.start) {
    return "before";
  } else if (currentTime >= element.start && currentTime < element.start + element.duration) {
    return "active";
  } else {
    return "after";
  }
};

const VideoGeneratorApp = () => {
  // References
  const canvasRef = useRef(null);
  const videoRef = useRef(null);
  const timelineRef = useRef(null);
  const previewContainerRef = useRef(null);
  
  // State management
  const [activeTab, setActiveTab] = useState("templates");
  const [currentTemplate, setCurrentTemplate] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);
  const [showEditor, setShowEditor] = useState(false);
  const [targetLanguage, setTargetLanguage] = useState("es-ES");
  const [nativeLanguage, setNativeLanguage] = useState("en-US");
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(15);
  const [isDraggingTimeline, setIsDraggingTimeline] = useState(false);
  const [showWaveform, setShowWaveform] = useState(true);
  const [fullscreenPreview, setFullscreenPreview] = useState(false);
  const [exportProgress, setExportProgress] = useState(0);
  const [isExporting, setIsExporting] = useState(false);
  const [exportFormat, setExportFormat] = useState("mp4");
  const [exportResolution, setExportResolution] = useState("1080p");
  const [savedProjects, setSavedProjects] = useState([]);
  const [showLoadProjectDialog, setShowLoadProjectDialog] = useState(false);
  const [previewQuality, setPreviewQuality] = useState("medium");
  const [draggedElement, setDraggedElement] = useState(null);
  
  const [content, setContent] = useState([
    {
      id: 1,
      image: "medico.jpg",
      targetWord: "médico",
      nativeWord: "doctor",
      targetPhrase1: "quiere ser médico",
      nativePhrase1: "he wants to be a doctor",
      targetPhrase2: "su médico es bueno",
      nativePhrase2: "his doctor is good",
      audio: "medico-audio.mp3"
    },
    {
      id: 2,
      image: "abogado.jpg",
      targetWord: "abogado",
      nativeWord: "lawyer",
      targetPhrase1: "estudia para abogado",
      nativePhrase1: "he studies to be a lawyer",
      targetPhrase2: "necesita un abogado",
      nativePhrase2: "he needs a lawyer",
      audio: "abogado-audio.mp3"
    }
  ]);
  
  const [currentContentIndex, setCurrentContentIndex] = useState(0);
  const [newRow, setNewRow] = useState({
    image: "",
    targetWord: "",
    nativeWord: "",
    targetPhrase1: "",
    nativePhrase1: "",
    targetPhrase2: "",
    nativePhrase2: ""
  });
  
  const [selectedAnimationStyle, setSelectedAnimationStyle] = useState("fadeIn");
  const [audioSyncEnabled, setAudioSyncEnabled] = useState(true);
  const [generatingStatus, setGeneratingStatus] = useState(null);
  const [renderQueue, setRenderQueue] = useState([]);
  const [projectName, setProjectName] = useState("Vocabulary Project");
  const [showNotification, setShowNotification] = useState(false);
  const [notificationMessage, setNotificationMessage] = useState("");
  const [notificationType, setNotificationType] = useState("success");
  const [editingElement, setEditingElement] = useState(null);
  const [audioData, setAudioData] = useState(null);
  const [audioWaveform, setAudioWaveform] = useState([]);
  const [templates, setTemplates] = useState([
    { 
      id: "vocab-template", 
      name: "Vocabulary Template", 
      description: "Standard vocabulary template with word and phrases",
      thumbnail: "template1.jpg",
      duration: 15,
      background: "#1a1a2e"
    },
    { 
      id: "grammar-template", 
      name: "Grammar Template", 
      description: "Template for grammar explanations with examples",
      thumbnail: "template2.jpg",
      duration: 20,
      background: "#16213e"
    },
    { 
      id: "conversation-template", 
      name: "Conversation Template", 
      description: "Dialog-based template for conversation practice",
      thumbnail: "template3.jpg",
      duration: 30,
      background: "#0f3460"
    }
  ]);
  
  const [timelineElements, setTimelineElements] = useState([
    { 
      id: "el-1", 
      type: "text", 
      content: "Vocabulary Word", 
      start: 0, 
      duration: 3, 
      position: {x: 400, y: 150}, 
      style: {color: "#ffffff", fontSize: 36, fontWeight: "bold"},
      animation: "fadeIn",
      contentKey: "targetWord" 
    },
    { 
      id: "el-2", 
      type: "image", 
      content: "medico.jpg", 
      start: 0.5, 
      duration: 12, 
      position: {x: 200, y: 250}, 
      style: {width: 300, height: 300, borderRadius: "8px"},
      animation: "zoomIn",
      contentKey: "image"
    },
    { 
      id: "el-3", 
      type: "text", 
      content: "Example Phrase 1", 
      start: 4, 
      duration: 3, 
      position: {x: 400, y: 350}, 
      style: {color: "#ffffff", fontSize: 24},
      animation: "slideIn",
      contentKey: "targetPhrase1"
    },
    { 
      id: "el-4", 
      type: "text", 
      content: "Example Phrase 2", 
      start: 8, 
      duration: 3, 
      position: {x: 400, y: 450}, 
      style: {color: "#ffffff", fontSize: 24},
      animation: "slideIn",
      contentKey: "targetPhrase2"
    },
    { 
      id: "el-5", 
      type: "audio", 
      content: "narration.mp3", 
      start: 0, 
      duration: 15,
      contentKey: "audio"
    },
  ]);
  
  // Initialize local storage and load saved projects
  useEffect(() => {
    const loadSavedProjects = () => {
      try {
        const projectsJson = localStorage.getItem('videogen-projects');
        if (projectsJson) {
          const projects = JSON.parse(projectsJson);
          setSavedProjects(projects);
        }
      } catch (error) {
        console.error("Error loading saved projects:", error);
        showNotify("Error loading saved projects", "error");
      }
    };
    
    loadSavedProjects();
    
    // Setup auto-save
    const autoSaveInterval = setInterval(() => {
      if (currentTemplate && content.length > 0) {
        saveCurrentProject(true);
      }
    }, 60000); // Auto-save every minute
    
    return () => clearInterval(autoSaveInterval);
  }, []);
  
  // Save current project
  const saveCurrentProject = (isAutoSave = false) => {
    try {
      const project = {
        id: Date.now().toString(),
        name: projectName,
        template: currentTemplate,
        content: content,
        timelineElements: timelineElements,
        lastSaved: new Date().toISOString()
      };
      
      let projects = [];
      const projectsJson = localStorage.getItem('videogen-projects');
      
      if (projectsJson) {
        projects = JSON.parse(projectsJson);
        // Check if project with same name exists
        const existingProjectIndex = projects.findIndex(p => p.name === projectName);
        if (existingProjectIndex >= 0) {
          projects[existingProjectIndex] = project;
        } else {
          projects.push(project);
        }
      } else {
        projects = [project];
      }
      
      localStorage.setItem('videogen-projects', JSON.stringify(projects));
      setSavedProjects(projects);
      
      if (!isAutoSave) {
        showNotify("Project saved successfully");
      }
    } catch (error) {
      console.error("Error saving project:", error);
      showNotify("Error saving project", "error");
    }
  };
  
  // Load a saved project
  const loadProject = (project) => {
    setProjectName(project.name);
    setCurrentTemplate(project.template);
    setContent(project.content);
    setTimelineElements(project.timelineElements);
    setActiveTab("content");
    setShowLoadProjectDialog(false);
    showNotify(`Project "${project.name}" loaded successfully`);
  };
  
  // Template selection
  const selectTemplate = (templateId) => {
    setCurrentTemplate(templates.find(t => t.id === templateId));
    showNotify("Template selected: " + templates.find(t => t.id === templateId).name);
    setActiveTab("content");
  };
  
  // Notification helper
  const showNotify = (message, type = "success") => {
    setNotificationMessage(message);
    setNotificationType(type);
    setShowNotification(true);
    setTimeout(() => setShowNotification(false), 3000);
  };
  
  // Add new content row
  const addContentRow = () => {
    if (!newRow.targetWord || !newRow.nativeWord) {
      showNotify("Target and native words are required", "error");
      return;
    }
    
    setContent([...content, { 
      id: content.length + 1,
      ...newRow,
      audio: `audio-${content.length + 1}.mp3` // Placeholder for generated audio
    }]);
    
    setNewRow({
      image: "",
      targetWord: "",
      nativeWord: "",
      targetPhrase1: "",
      nativePhrase1: "",
      targetPhrase2: "",
      nativePhrase2: ""
    });
    
    showNotify("New content row added");
  };
  
  // Delete content row
  const deleteContentRow = (id) => {
    setContent(content.filter(row => row.id !== id));
    showNotify("Content row deleted");
  };
  
  // Toggle play/pause
  const togglePlayback = () => {
    setIsPlaying(!isPlaying);
  };
  
  // Add new element to timeline
  const addTimelineElement = (type) => {
    const newElement = {
      id: `el-${Date.now()}`,
      type,
      content: type === 'text' ? 'New Text' : type === 'image' ? 'image.jpg' : 'audio.mp3',
      start: currentTime,
      duration: type === 'audio' ? 5 : 3,
      position: type !== 'audio' ? {x: 400, y: 300} : undefined,
      style: type === 'text' ? {color: "#ffffff", fontSize: 24} : 
             type === 'image' ? {width: 200, height: 200, borderRadius: "8px"} : undefined,
      animation: type !== 'audio' ? selectedAnimationStyle : undefined
    };
    
    setTimelineElements([...timelineElements, newElement]);
    setEditingElement(newElement);
    setShowEditor(true);
    showNotify(`New ${type} element added`);
  };
  
  // Animation preview
  useEffect(() => {
    let interval;
    if (isPlaying) {
      interval = setInterval(() => {
        setCurrentTime(time => {
          const newTime = time + 0.1;
          if (newTime >= duration) {
            setIsPlaying(false);
            return 0;
          }
          return newTime;
        });
        
        setProgress(prog => {
          const newProg = prog + (100 / (duration * 10));
          return newProg > 100 ? 0 : newProg;
        });
      }, 100);
    }
    
    return () => clearInterval(interval);
  }, [isPlaying, duration]);
  
  // Handle timeline scrubbing
  const handleTimelineClick = (e) => {
    if (!timelineRef.current) return;
    
    const rect = timelineRef.current.getBoundingClientRect();
    const clickPosition = e.clientX - rect.left;
    const percentClicked = clickPosition / rect.width;
    const newTime = percentClicked * duration;
    
    setCurrentTime(Math.max(0, Math.min(newTime, duration)));
    setProgress(percentClicked * 100);
  };
  
  // Handle timeline drag
  const handleTimelineDragStart = () => {
    setIsDraggingTimeline(true);
    setIsPlaying(false);
  };
  
  const handleTimelineDragMove = (e) => {
    if (!isDraggingTimeline || !timelineRef.current) return;
    
    const rect = timelineRef.current.getBoundingClientRect();
    const dragPosition = e.clientX - rect.left;
    const percentDragged = Math.max(0, Math.min(dragPosition / rect.width, 1));
    const newTime = percentDragged * duration;
    
    setCurrentTime(newTime);
    setProgress(percentDragged * 100);
  };
  
  const handleTimelineDragEnd = () => {
    setIsDraggingTimeline(false);
  };
  
  // Effect for handling window mouse events during timeline dragging
  useEffect(() => {
    const handleMouseMove = (e) => handleTimelineDragMove(e);
    const handleMouseUp = () => handleTimelineDragEnd();
    
    if (isDraggingTimeline) {
      window.addEventListener('mousemove', handleMouseMove);
      window.addEventListener('mouseup', handleMouseUp);
    }
    
    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDraggingTimeline]);
  
  // Generate videos for all content
  const generateAllVideos = () => {
    if (!currentTemplate) {
      showNotify("Please select a template first", "error");
      return;
    }
    
    if (content.length === 0) {
      showNotify("No content to generate", "error");
      return;
    }
    
    // Create render queue
    const queue = content.map(item => ({
      id: `render-${item.id}`,
      content: item,
      template: currentTemplate,
      status: "pending",
      progress: 0
    }));
    
    setRenderQueue(queue);
    setGeneratingStatus("preparing");
    
    // Simulate processing
    setTimeout(() => {
      setGeneratingStatus("processing");
      
      let currentIndex = 0;
      const processNext = () => {
        if (currentIndex >= queue.length) {
          setGeneratingStatus("complete");
          showNotify(`Successfully generated ${queue.length} videos`);
          return;
        }
        
        const updatedQueue = [...queue];
        updatedQueue[currentIndex].status = "processing";
        setRenderQueue(updatedQueue);
        
        // Simulate processing time (in real app, this would be actual rendering)
        let progress = 0;
        const interval = setInterval(() => {
          progress += 5;
          
          const newQueue = [...updatedQueue];
          newQueue[currentIndex].progress = progress;
          setRenderQueue(newQueue);
          
          if (progress >= 100) {
            clearInterval(interval);
            newQueue[currentIndex].status = "complete";
            setRenderQueue(newQueue);
            currentIndex++;
            setTimeout(processNext, 500);
          }
        }, 300);
      };
      
      processNext();
    }, 1500);
  };
  
  // Open element editor
  const openElementEditor = (element) => {
    setEditingElement(element);
    setShowEditor(true);
  };
  
  // Update element
  const updateElement = (updatedElement) => {
    setTimelineElements(elements => 
      elements.map(el => el.id === updatedElement.id ? updatedElement : el)
    );
    setShowEditor(false);
    showNotify("Element updated");
  };
  
  // Handle element drag in preview
  const startElementDrag = (element) => {
    setDraggedElement(element);
  };
  
  const handleElementDrag = (e, element) => {
    if (!previewContainerRef.current) return;
    
    const rect = previewContainerRef.current.getBoundingClientRect();
    const newX = e.clientX - rect.left;
    const newY = e.clientY - rect.top;
    
    setTimelineElements(elements => 
      elements.map(el => {
        if (el.id === element.id && el.position) {
          return {
            ...el,
            position: {
              x: Math.max(0, Math.min(newX, rect.width)),
              y: Math.max(0, Math.min(newY, rect.height))
            }
          };
        }
        return el;
      })
    );
  };
  
  const endElementDrag = () => {
    setDraggedElement(null);
  };
  
  // Effect for mouse events during element dragging
  useEffect(() => {
    const handleMouseMove = (e) => {
      if (draggedElement) {
        handleElementDrag(e, draggedElement);
      }
    };
    
    const handleMouseUp = () => {
      if (draggedElement) {
        endElementDrag();
      }
    };
    
    if (draggedElement) {
      window.addEventListener('mousemove', handleMouseMove);
      window.addEventListener('mouseup', handleMouseUp);
    }
    
    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    };
  }, [draggedElement]);
  
  // Generate audio for content
  const generateAudio = () => {
    showNotify("Generating audio for content...");
    
    // Simulate audio generation
    let generatedCount = 0;
    
    const processNext = () => {
      if (generatedCount >= content.length) {
        showNotify("Audio generation complete!");
        // Generate mock waveform data
        generateMockWaveform();
        return;
      }
      
      setTimeout(() => {
        generatedCount++;
        processNext();
      }, 500);
    };
    
    processNext();
  };
  
  // Generate mock waveform for audio visualization
  const generateMockWaveform = () => {
    const waveformPoints = [];
    const numPoints = 100;
    
    for (let i = 0; i < numPoints; i++) {
      // Create a semi-random waveform height, with more activity in the middle
      const x = i / numPoints;
      let height = 0.2 + 0.6 * Math.sin(x * Math.PI) * Math.random();
      waveformPoints.push(height);
    }
    
    setAudioWaveform(waveformPoints);
  };
  
  // Export current video
  const exportCurrentVideo = () => {
    if (currentContentIndex >= content.length) {
      showNotify("No content selected for export", "error");
      return;
    }
    
    setIsExporting(true);
    setExportProgress(0);
    
    // Simulate export process
    const interval = setInterval(() => {
      setExportProgress(prev => {
        const next = prev + 5;
        if (next >= 100) {
          clearInterval(interval);
          setTimeout(() => {
            setIsExporting(false);
            showNotify(`Video exported successfully as ${projectName}-${currentContentIndex + 1}.${exportFormat}`);
          }, 500);
          return 100;
        }
        return next;
      });
    }, 200);
  };
  
  // Reset progress for new render
  const startNewProject = () => {
    setCurrentTemplate(null);
    setActiveTab("templates");
    setProjectName("New Project");
    setContent([]);
    setRenderQueue([]);
    setGeneratingStatus(null);
    setCurrentTime(0);
    setProgress(0);
    showNotify("Started new project");
  };
  
  // Define placeholder thumbnails and assets
  const getImageUrl = (name) => {
    if (name === "medico.jpg") {
      return "/api/placeholder/300/300";
    } else if (name === "abogado.jpg") {
      return "/api/placeholder/300/300";
    } else if (name === "template1.jpg" || name === "template2.jpg" || name === "template3.jpg") {
      return "/api/placeholder/400/220";
    }
    return "/api/placeholder/200/200";
  };
  
  // Get real content based on timeline element
  const getElementContent = (element) => {
    if (!element.contentKey || currentContentIndex >= content.length) {
      return element.content;
    }
    
    const contentItem = content[currentContentIndex];
    return contentItem[element.contentKey] || element.content;
  };
  
  // Timeline rendering
  const renderTimeline = () => {
    // Find the time range to display
    const visibleTimeStart = Math.max(0, currentTime - 5);
    const visibleTimeEnd = Math.min(duration, currentTime + 10);
    
    return (
      <div className="relative h-24 bg-slate-800 rounded overflow-hidden">
        {/* Time markers */}
        <div className="absolute top-0 left-0 right-0 h-6 flex text-xs text-slate-400">
          {Array.from({ length: Math.ceil(duration) + 1 }).map((_, i) => (
            <div 
              key={i} 
              className="border-l border-slate-700 h-full flex items-center px-1"
              style={{ 
                position: 'absolute', 
                left: `${(i / duration) * 100}%`,
                opacity: i % 5 === 0 ? 1 : 0.5
              }}
            >
              {i}s
            </div>
          ))}
        </div>
        
        {/* Waveform */}
        {showWaveform && audioWaveform.length > 0 && (
          <div className="absolute top-6 left-0 right-0 h-10 px-2">
            <svg width="100%" height="100%" className="opacity-50">
              <defs>
                <linearGradient id="waveformGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                  <stop offset="0%" stopColor="#4F46E5" />
                  <stop offset="100%" stopColor="#818CF8" />
                </linearGradient>
              </defs>
              <path 
                d={`M0,${10} ${audioWaveform.map((h, i) => `L${(i / audioWaveform.length) * 100}%,${(1-h) * 10} `).join('')}`} 
                stroke="url(#waveformGradient)" 
                strokeWidth="1.5" 
                fill="none" 
              />
            </svg>
          </div>
        )}
        
        {/* Elements timeline */}
        <div className="absolute top-16 left-0 right-0 bottom-0 px-2">
          {timelineElements.map(element => (
            <div 
              key={element.id}
              className={`absolute h-6 rounded cursor-pointer ${
                element.type === 'text' ? 'bg-blue-600/70' : 
                element.type === 'image' ? 'bg-green-600/70' : 
                'bg-purple-600/70'
              } ${currentTime >= element.start && currentTime < element.start + element.duration ? 'ring-2 ring-white' : ''}`}
              style={{
                left: `${(element.start / duration) * 100}%`,
                width: `${(element.duration / duration) * 100}%`,
                top: element.type === 'audio' ? 'auto' : 
                     element.type === 'text' ? '0px' : '8px',
                bottom: element.type === 'audio' ? '0px' : 'auto'
              }}
              onClick={() => openElementEditor(element)}
            >
              <div className="truncate text-xs text-white px-2 py-1">
                {element.type === 'text' ? getElementContent(element).substring(0, 15) : element.type}
                {element.type === 'text' && getElementContent(element).length > 15 ? '...' : ''}
              </div>
            </div>
          ))}
        </div>
        
        {/* Current time indicator */}
        <div className="absolute top-0 bottom-0 w-px bg-red-500 z-10" style={{ left: `${(currentTime / duration) * 100}%` }}>
          <div className="w-3 h-3 bg-red-500 rounded-full -ml-1.5 -mt-1"></div>
        </div>
        
        {/* Click area */}
        <div 
          ref={timelineRef}
          className="absolute inset-0 cursor-pointer"
          onClick={handleTimelineClick}
          onMouseDown={handleTimelineDragStart}
        ></div>
      </div>
    );
  };
  
  // Render preview with elements
  const renderPreview = () => {
    const currentContent = content[currentContentIndex];
    const backgroundColor = currentTemplate?.background || "#1a1a2e";
    
    return (
      <div 
        ref={previewContainerRef}
        className={`aspect-video bg-slate-800 rounded-lg relative overflow-hidden ${fullscreenPreview ? 'fixed inset-0 z-50 rounded-none' : ''}`}
        style={{ backgroundColor }}
      >
        {/* Background elements */}
        {currentTemplate && (
          <div className="absolute inset-0 opacity-20">
            <svg width="100%" height="100%">
              <defs>
                <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                  <path d="M 40 0 L 0 0 0 40" fill="none" stroke="white" strokeWidth="0.5" />
                </pattern>
              </defs>
              <rect width="100%" height="100%" fill="url(#grid)" />
            </svg>
          </div>
        )}
        
        {/* Display timeline elements */}
        {timelineElements.map(element => {
          if (element.type === 'audio') return null; // Don't visually render audio
          
          const animationState = getElementAnimationState(element, currentTime);
          if (animationState === "before") return null;
          
          const content = getElementContent(element);
          const animationPreset = animationPresets[element.animation || "fadeIn"];
          
          // Determine animation based on time
          const animationProgress = Math.min(1, (currentTime - element.start) / 0.5); // 0.5s animation duration
          const exitProgress = Math.min(1, (currentTime - (element.start + element.duration - 0.5)) / 0.5);
          
          const shouldExit = animationState === "after" || exitProgress > 0;
          const shouldAnimate = animationProgress < 1 && !shouldExit;
          
          // Calculate final animation values
          const opacity = shouldExit ? 1 - exitProgress : shouldAnimate ? animationProgress : 1;
          
          // Determine transform based on animation type
          let transform = '';
          if (element.animation === 'slideIn') {
            const xOffset = shouldExit ? (exitProgress * 100) : shouldAnimate ? ((1 - animationProgress) * -100) : 0;
            transform = `translateX(${xOffset}px)`;
          } else if (element.animation === 'zoomIn') {
            const scale = shouldExit ? (1 - exitProgress * 0.5) : shouldAnimate ? animationProgress : 1;
            transform = `scale(${scale})`;
          } else if (element.animation === 'bounceIn') {
            const scale = shouldExit ? (1 - exitProgress * 0.5) : shouldAnimate ? (animationProgress < 0.5 ? 2 * animationProgress : 1 + (1 - animationProgress)) : 1;
            transform = `scale(${scale})`;
          } else if (element.animation === 'flipIn') {
            const rotateY = shouldExit ? (exitProgress * 90) : shouldAnimate ? ((1 - animationProgress) * 90) : 0;
            transform = `perspective(800px) rotateY(${rotateY}deg)`;
          }
          
          return (
            <div
              key={element.id}
              className="absolute p-1"
              style={{
                left: element.position?.x || 0,
                top: element.position?.y || 0,
                opacity,
                transform,
                transition: 'opacity 0.1s, transform 0.1s',
                cursor: activeTab === 'editor' ? 'move' : 'default',
                transformOrigin: 'center'
              }}
              onMouseDown={activeTab === 'editor' ? () => startElementDrag(element) : undefined}
            >
              {element.type === 'text' ? (
                <div 
                  style={{
                    color: element.style?.color || 'white',
                    fontSize: `${element.style?.fontSize || 24}px`,
                    fontWeight: element.style?.fontWeight || 'normal',
                    fontFamily: element.style?.fontFamily || 'Inter, sans-serif',
                    textShadow: '0 1px 3px rgba(0,0,0,0.5)'
                  }}
                >
                  {content}
                </div>
              ) : element.type === 'image' ? (
                <img 
                  src={getImageUrl(content)}
                  alt={content}
                  style={{
                    width: `${element.style?.width || 200}px`,
                    height: `${element.style?.height || 200}px`,
                    borderRadius: element.style?.borderRadius || '0px',
                    objectFit: 'cover',
                    boxShadow: '0 4px 6px rgba(0,0,0,0.1)'
                  }}
                />
              ) : null}
            </div>
          );
        })}
        
        {/* Playback controls */}
        <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2 bg-black/70 rounded-full p-2 backdrop-blur-sm">
          <Button variant="ghost" size="icon" className="text-white" onClick={() => setCurrentTime(Math.max(0, currentTime - 1))}>
            <SkipBack className="h-4 w-4" />
          </Button>
          <Button variant="ghost" size="icon" className="text-white" onClick={togglePlayback}>
            {isPlaying ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}
          </Button>
          <Button variant="ghost" size="icon" className="text-white" onClick={() => setCurrentTime(Math.min(duration, currentTime + 1))}>
            <SkipForward className="h-4 w-4" />
          </Button>
        </div>
        
        {/* Additional controls */}
        <div className="absolute top-2 right-2 flex space-x-1">
          <Button 
            variant="ghost" 
            size="icon" 
            className="text-white/70 hover:text-white bg-black/20 hover:bg-black/40"
            onClick={() => setShowWaveform(!showWaveform)}
          >
            {showWaveform ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
          </Button>
          <Button 
            variant="ghost" 
            size="icon" 
            className="text-white/70 hover:text-white bg-black/20 hover:bg-black/40"
            onClick={() => setFullscreenPreview(!fullscreenPreview)}
          >
            {fullscreenPreview ? <Minimize className="h-4 w-4" /> : <Maximize className="h-4 w-4" />}
          </Button>
        </div>
        
        {/* Export progress overlay */}
        {isExporting && (
          <div className="absolute inset-0 bg-black/80 flex flex-col items-center justify-center">
            <div className="w-64 mb-4">
              <Progress value={exportProgress} className="h-2" />
            </div>
            <div className="text-white font-medium">Exporting video... {exportProgress}%</div>
          </div>
        )}
        
        {/* Timeline progress */}
        <div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-700 z-10">
          <div 
            className="h-full bg-blue-500 transition-all" 
            style={{ width: `${progress}%` }}
          ></div>
        </div>
      </div>
    );
  };
  
  return (
    <div className="flex flex-col h-screen bg-slate-50 overflow-hidden">
      {/* Header */}
      <header className="border-b bg-white shadow-sm">
        <div className="container mx-auto px-4 py-3 flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <FileVideo className="h-6 w-6 text-blue-600" />
            <h1 className="text-xl font-bold tracking-tight">VideoGen Pro</h1>
          </div>
          
          <div className="flex space-x-2">
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Input
                    className="w-60"
                    value={projectName}
                    onChange={(e) => setProjectName(e.target.value)}
                  />
                </TooltipTrigger>
                <TooltipContent>
                  <p>Project Name</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm">
                  <FileText className="h-4 w-4 mr-1" /> Project
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <DropdownMenuItem onClick={startNewProject}>
                  <FileText className="h-4 w-4 mr-2" />
                  New Project
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setShowLoadProjectDialog(true)}>
                  <Upload className="h-4 w-4 mr-2" />
                  Load Project
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => saveCurrentProject()}>
                  <Save className="h-4 w-4 mr-2" />
                  Save Project
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
            
            <Button size="sm" onClick={() => exportCurrentVideo()}>
              <Download className="h-4 w-4 mr-1" /> Export
            </Button>
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon">
                  <Settings className="h-5 w-5" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>Settings</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => setPreviewQuality("low")}>
                  <div className="flex items-center">
                    <span className="mr-2">Low Quality Preview</span>
                    {previewQuality === "low" && <Check className="h-4 w-4" />}
                  </div>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setPreviewQuality("medium")}>
                  <div className="flex items-center">
                    <span className="mr-2">Medium Quality Preview</span>
                    {previewQuality === "medium" && <Check className="h-4 w-4" />}
                  </div>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setPreviewQuality("high")}>
                  <div className="flex items-center">
                    <span className="mr-2">High Quality Preview</span>
                    {previewQuality === "high" && <Check className="h-4 w-4" />}
                  </div>
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem>Project Settings</DropdownMenuItem>
                <DropdownMenuItem>Export Settings</DropdownMenuItem>
                <DropdownMenuItem>User Preferences</DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </header>
      
      {/* Main Content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Left Sidebar */}
        <div className="w-56 border-r bg-white">
          <div className="p-4">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
              <TabsList className="grid grid-cols-2 mb-4">
                <TabsTrigger value="templates">Templates</TabsTrigger>
                <TabsTrigger value="content">Content</TabsTrigger>
              </TabsList>
            </Tabs>
            
            <div className="space-y-2">
              <Button 
                variant={activeTab === "templates" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("templates")}
              >
                <Layers className="h-4 w-4 mr-2" />
                Templates
              </Button>
              
              <Button 
                variant={activeTab === "content" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("content")}
              >
                <FileText className="h-4 w-4 mr-2" />
                Content
              </Button>
              
              <Button 
                variant={activeTab === "editor" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("editor")}
              >
                <Edit3 className="h-4 w-4 mr-2" />
                Editor
              </Button>
              
              <Button 
                variant={activeTab === "generate" ? "default" : "outline"} 
                className="w-full justify-start" 
                onClick={() => setActiveTab("generate")}
              >
                <Zap className="h-4 w-4 mr-2" />
                Generate
              </Button>
            </div>
            
            {activeTab === "editor" && (
              <div className="mt-6 space-y-2 border-t pt-4">
                <h3 className="text-sm font-medium text-slate-500">Add Elements</h3>
                <div className="grid grid-cols-3 gap-2">
                  <Button variant="outline" size="sm" className="w-full p-1" onClick={() => addTimelineElement("text")}>
                    <FileText className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" className="w-full p-1" onClick={() => addTimelineElement("image")}>
                    <Image className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" className="w-full p-1" onClick={() => addTimelineElement("audio")}>
                    <Volume2 className="h-4 w-4" />
                  </Button>
                </div>
                
                <h3 className="text-sm font-medium text-slate-500 mt-4">Animation Style</h3>
                <Select value={selectedAnimationStyle} onValueChange={setSelectedAnimationStyle}>
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Animation Style" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="fadeIn">Fade In</SelectItem>
                    <SelectItem value="slideIn">Slide In</SelectItem>
                    <SelectItem value="zoomIn">Zoom In</SelectItem>
                    <SelectItem value="bounceIn">Bounce In</SelectItem>
                    <SelectItem value="flipIn">Flip In</SelectItem>
                  </SelectContent>
                </Select>
                
                <div className="flex items-center justify-between mt-4">
                  <Label htmlFor="audio-sync" className="text-sm">
                    Auto-sync to Audio
                  </Label>
                  <Switch 
                    id="audio-sync" 
                    checked={audioSyncEnabled} 
                    onCheckedChange={setAudioSyncEnabled} 
                  />
                </div>
              </div>
            )}
          </div>
        </div>
        
        {/* Main Panel */}
        <div className="flex-1 overflow-auto">
          <div className="container mx-auto p-6">
            {activeTab === "templates" && (
              <div className="space-y-6">
                <div className="flex justify-between items-center">
                  <h2 className="text-2xl font-bold">Video Templates</h2>
                  <Button size="sm">
                    <Plus className="h-4 w-4 mr-1" /> Import Template
                  </Button>
                </div>
                
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {templates.map(template => (
                    <Card key={template.id} className={`overflow-hidden transition-all ${currentTemplate?.id === template.id ? 'ring-2 ring-blue-500' : ''}`}>
                      <div className="aspect-video bg-slate-100 relative overflow-hidden">
                        <img 
                          src={getImageUrl(template.thumbnail)}
                          alt={template.name} 
                          className="w-full h-full object-cover"
                        />
                        <div 
                          className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent flex flex-col justify-end p-4"
                        >
                          <h3 className="text-lg font-medium text-white">{template.name}</h3>
                          <p className="text-sm text-white/80">{template.description}</p>
                        </div>
                        <Badge className="absolute top-2 right-2">
                          {template.duration}s
                        </Badge>
                      </div>
                      <CardFooter className="bg-white p-3">
                        <Button 
                          className="w-full" 
                          onClick={() => selectTemplate(template.id)}
                        >
                          {currentTemplate?.id === template.id ? (
                            <>
                              <CheckCircle className="h-4 w-4 mr-1" />
                              Selected
                            </>
                          ) : "Select Template"}
                        </Button>
                      </CardFooter>
                    </Card>
                  ))}
                </div>
              </div>
            )}
            
            {activeTab === "content" && (
              <div className="space-y-6">
                <div className="flex justify-between items-center">
                  <h2 className="text-2xl font-bold">Content</h2>
                  <div className="flex space-x-2">
                    <Select value={targetLanguage} onValueChange={setTargetLanguage}>
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="Target Language" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="es-ES">Español</SelectItem>
                        <SelectItem value="fr-FR">Français</SelectItem>
                        <SelectItem value="de-DE">Deutsch</SelectItem>
                        <SelectItem value="it-IT">Italiano</SelectItem>
                        <SelectItem value="pt-PT">Português</SelectItem>
                      </SelectContent>
                    </Select>
                    
                    <Select value={nativeLanguage} onValueChange={setNativeLanguage}>
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="Native Language" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="en-US">English</SelectItem>
                        <SelectItem value="es-ES">Español</SelectItem>
                        <SelectItem value="fr-FR">Français</SelectItem>
                        <SelectItem value="de-DE">Deutsch</SelectItem>
                        <SelectItem value="it-IT">Italiano</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                
                <div className="bg-white rounded-md shadow overflow-hidden">
                  <div className="border-b px-4 py-2 bg-slate-50 grid grid-cols-9 gap-4 font-medium text-sm">
                    <div className="col-span-1">Image</div>
                    <div className="col-span-1">Target Word</div>
                    <div className="col-span-1">Native Word</div>
                    <div className="col-span-2">Target Phrase 1</div>
                    <div className="col-span-2">Native Phrase 1</div>
                    <div className="col-span-1">Target Phrase 2</div>
                    <div className="col-span-1">Actions</div>
                  </div>
                  
                  {content.map(row => (
                    <div key={row.id} className="px-4 py-3 border-b grid grid-cols-9 gap-4 items-center">
                      <div className="col-span-1">
                        <div className="w-10 h-10 bg-slate-100 rounded overflow-hidden">
                          <img 
                            src={getImageUrl(row.image)} 
                            alt={row.targetWord} 
                            className="w-full h-full object-cover"
                          />
                        </div>
                      </div>
                      <div className="col-span-1">{row.targetWord}</div>
                      <div className="col-span-1">{row.nativeWord}</div>
                      <div className="col-span-2">{row.targetPhrase1}</div>
                      <div className="col-span-2">{row.nativePhrase1}</div>
                      <div className="col-span-1">{row.targetPhrase2}</div>
                      <div className="col-span-1 flex space-x-1">
                        <Button variant="ghost" size="icon" onClick={() => setCurrentContentIndex(content.indexOf(row))}>
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => deleteContentRow(row.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  
                  <div className="px-4 py-3 grid grid-cols-9 gap-4 items-center bg-slate-50">
                    <div className="col-span-1">
                      <Button variant="outline" size="sm" className="w-10 h-10 p-0">
                        <Upload className="h-4 w-4" />
                      </Button>
                    </div>
                    <div className="col-span-1">
                      <Input 
                        placeholder="Word" 
                        value={newRow.targetWord}
                        onChange={(e) => setNewRow({...newRow, targetWord: e.target.value})}
                      />
                    </div>
                    <div className="col-span-1">
                      <Input 
                        placeholder="Word" 
                        value={newRow.nativeWord}
                        onChange={(e) => setNewRow({...newRow, nativeWord: e.target.value})}
                      />
                    </div>
                    <div className="col-span-2">
                      <Input 
                        placeholder="Phrase" 
                        value={newRow.targetPhrase1}
                        onChange={(e) => setNewRow({...newRow, targetPhrase1: e.target.value})}
                      />
                    </div>
                    <div className="col-span-2">
                      <Input 
                        placeholder="Phrase" 
                        value={newRow.nativePhrase1}
                        onChange={(e) => setNewRow({...newRow, nativePhrase1: e.target.value})}
                      />
                    </div>
                    <div className="col-span-1">
                      <Input 
                        placeholder="Phrase" 
                        value={newRow.targetPhrase2}
                        onChange={(e) => setNewRow({...newRow, targetPhrase2: e.target.value})}
                      />
                    </div>
                    <div className="col-span-1">
                      <Button onClick={addContentRow}>
                        <Plus className="h-4 w-4 mr-1" /> Add
                      </Button>
                    </div>
                  </div>
                </div>
                
                <div className="flex justify-between">
                  <Button variant="outline" onClick={generateAudio}>
                    <Volume2 className="h-4 w-4 mr-1" /> Generate Audio
                  </Button>
                  
                  <Button onClick={() => setActiveTab("editor")}>
                    Continue to Editor <ChevronDown className="h-4 w-4 ml-1 rotate-270" />
                  </Button>
                </div>
              </div>
            )}
            
            {(activeTab === "editor" || activeTab === "generate") && (
              <div className="space-y-6">
                <div className="flex justify-between items-center">
                  <h2 className="text-2xl font-bold">
                    {activeTab === "editor" ? "Template Editor" : "Generate Videos"}
                  </h2>
                  {activeTab === "generate" && (
                    <div className="flex space-x-2">
                      <Select value={exportResolution} onValueChange={setExportResolution}>
                        <SelectTrigger className="w-32">
                          <SelectValue placeholder="Resolution" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="720p">720p</SelectItem>
                          <SelectItem value="1080p">1080p</SelectItem>
                          <SelectItem value="4k">4K</SelectItem>
                        </SelectContent>
                      </Select>
                      
                      <Select value={exportFormat} onValueChange={setExportFormat}>
                        <SelectTrigger className="w-32">
                          <SelectValue placeholder="Format" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="mp4">MP4 (H.264)</SelectItem>
                          <SelectItem value="webm">WebM</SelectItem>
                          <SelectItem value="gif">GIF</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  )}
                </div>
                
                {/* Preview and Timeline Area */}
                <div className="space-y-4">
                  {/* Preview Area */}
                  {renderPreview()}
                  
                  {/* Timeline */}
                  {renderTimeline()}
                  
                  <div className="flex justify-between">
                    <div className="flex space-x-2">
                      <Button 
                        variant="outline" 
                        size="sm" 
                        onClick={() => setCurrentContentIndex(prev => (prev > 0 ? prev - 1 : 0))}
                        disabled={currentContentIndex <= 0}
                      >
                        <ArrowLeft className="h-4 w-4 mr-1" />
                        Previous
                      </Button>
                      <Button 
                        variant="outline" 
                        size="sm" 
                        onClick={() => setCurrentContentIndex(prev => (prev < content.length - 1 ? prev + 1 : prev))}
                        disabled={currentContentIndex >= content.length - 1}
                      >
                        Next
                        <ArrowRight className="h-4 w-4 ml-1" />
                      </Button>
                      <div className="bg-slate-100 rounded px-2 py-1 text-sm flex items-center">
                        Item {currentContentIndex + 1} of {content.length}
                      </div>
                    </div>
                    
                    {activeTab === "editor" && (
                      <Button onClick={() => setActiveTab("generate")}>
                        Continue to Generate <ChevronDown className="h-4 w-4 ml-1 rotate-270" />
                      </Button>
                    )}
                    
                    {activeTab === "generate" && (
                      <Button onClick={generateAllVideos} disabled={generatingStatus === "processing" || generatingStatus === "preparing"}>
                        {generatingStatus === "complete" ? 
                          <><RefreshCw className="h-4 w-4 mr-1" /> Generate More</> : 
                          generatingStatus === "processing" || generatingStatus === "preparing" ? 
                            <><RefreshCw className="h-4 w-4 mr-1 animate-spin" /> Processing...</> : 
                            <><Zap className="h-4 w-4 mr-1" /> Generate All Videos</>}
                      </Button>
                    )}
                  </div>
                </div>
                
                {activeTab === "generate" && (
                  <div className="mt-6">
                    <Alert variant={generatingStatus === "complete" ? "success" : "default"}>
                      <CheckCircle className="h-4 w-4" />
                      <AlertTitle>
                        {generatingStatus === "complete" ? 
                          "Generation Complete!" : 
                          generatingStatus === "processing" ? 
                            "Processing Videos..." : 
                            generatingStatus === "preparing" ?
                              "Preparing..." :
                              "Ready to Generate"}
                      </AlertTitle>
                      <AlertDescription>
                        {generatingStatus === "complete" ? 
                          `Successfully generated ${renderQueue.length} videos.` : 
                          generatingStatus === "processing" ? 
                            `Processing ${renderQueue.filter(item => item.status === "complete").length} of ${renderQueue.length} videos...` : 
                            generatingStatus === "preparing" ?
                              "Setting up render queue..." :
                              "Click the button below to generate videos for all content."}
                      </AlertDescription>
                    </Alert>
                    
                    <Card className="mt-4">
                      <CardHeader>
                        <CardTitle>Generation Queue</CardTitle>
                        <CardDescription>
                          {content.length} videos to generate using {currentTemplate?.name || "selected template"}
                        </CardDescription>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        {renderQueue.length > 0 ? (
                          renderQueue.map(item => (
                            <div key={item.id} className="flex items-center space-x-4">
                              <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center">
                                {item.status === "complete" ? 
                                  <Check className="h-4 w-4 text-green-500" /> : 
                                  item.status === "processing" ?
                                    <RefreshCw className="h-4 w-4 text-blue-500 animate-spin" /> :
                                    <Clock className="h-4 w-4 text-slate-400" />}
                              </div>
                              <div className="flex-1">
                                <div className="font-medium">{item.content.targetWord} - {item.content.nativeWord}</div>
                                <Progress 
                                  value={item.progress} 
                                  className="h-2 mt-1"
                                />
                              </div>
                              <div className="text-sm text-slate-500">
                                {item.status === "complete" ? 
                                  "Complete" : 
                                  item.status === "processing" ?
                                    `${item.progress}%` :
                                    "Pending"}
                              </div>
                              <Button 
                                variant="ghost" 
                                size="icon" 
                                disabled={item.status !== "complete"}
                              >
                                <Download className="h-4 w-4" />
                              </Button>
                            </div>
                          ))
                        ) : (
                          <div className="text-center py-8 text-slate-500">
                            <Grid className="h-8 w-8 mx-auto mb-2" />
                            <p>No videos in queue yet</p>
                            <p className="text-sm">Click the "Generate All Videos" button to start generation</p>
                          </div>
                        )}
                      </CardContent>
                      <CardFooter className="flex justify-between">
                        <div>
                          <div className="flex items-center space-x-2">
                            <Checkbox id="audio-checkbox" checked />
                            <Label htmlFor="audio-checkbox">Include audio</Label>
                          </div>
                        </div>
                      </CardFooter>
                    </Card>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Element Editor Dialog */}
      <Dialog open={showEditor} onOpenChange={setShowEditor}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Edit Element</DialogTitle>
            <DialogDescription>
              Adjust properties for this timeline element
            </DialogDescription>
          </DialogHeader>
          
          {editingElement && (
            <div className="space-y-4 pt-2">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Start Time (seconds)</Label>
                  <Input 
                    type="number" 
                    min="0" 
                    step="0.1" 
                    value={editingElement.start} 
                    onChange={(e) => setEditingElement({...editingElement, start: parseFloat(e.target.value)})}
                  />
                </div>
                
                <div className="space-y-2">
                  <Label>Duration (seconds)</Label>
                  <Input 
                    type="number" 
                    min="0.1" 
                    step="0.1" 
                    value={editingElement.duration} 
                    onChange={(e) => setEditingElement({...editingElement, duration: parseFloat(e.target.value)})}
                  />
                </div>
              </div>
              
              {editingElement.type === "text" && (
                <>
                  <div className="space-y-2">
                    <Label>Text Content</Label>
                    <Textarea 
                      value={editingElement.content} 
                      onChange={(e) => setEditingElement({...editingElement, content: e.target.value})}
                    />
                  </div>
                  
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Font Size</Label>
                      <Input 
                        type="number" 
                        value={editingElement.style?.fontSize || 24} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, fontSize: parseInt(e.target.value)}
                        })}
                      />
                    </div>
                    
                    <div className="space-y-2">
                      <Label>Text Color</Label>
                      <Input 
                        type="color" 
                        value={editingElement.style?.color || "#ffffff"} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, color: e.target.value}
                        })}
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Content Link</Label>
                    <Select 
                      value={editingElement.contentKey || "none"} 
                      onValueChange={(val) => setEditingElement({
                        ...editingElement,
                        contentKey: val === "none" ? undefined : val
                      })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Link to content field" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">No link (use fixed text)</SelectItem>
                        <SelectItem value="targetWord">Target Word</SelectItem>
                        <SelectItem value="nativeWord">Native Word</SelectItem>
                        <SelectItem value="targetPhrase1">Target Phrase 1</SelectItem>
                        <SelectItem value="nativePhrase1">Native Phrase 1</SelectItem>
                        <SelectItem value="targetPhrase2">Target Phrase 2</SelectItem>
                        <SelectItem value="nativePhrase2">Native Phrase 2</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Animation</Label>
                    <Select 
                      value={editingElement.animation || "fadeIn"} 
                      onValueChange={(val) => setEditingElement({
                        ...editingElement,
                        animation: val
                      })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Choose animation" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="fadeIn">Fade In</SelectItem>
                        <SelectItem value="slideIn">Slide In</SelectItem>
                        <SelectItem value="zoomIn">Zoom In</SelectItem>
                        <SelectItem value="bounceIn">Bounce In</SelectItem>
                        <SelectItem value="flipIn">Flip In</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}
              
              {editingElement.type === "image" && (
                <>
                  <div className="space-y-2">
                    <Label>Image Source</Label>
                    <div className="flex space-x-2">
                      <Input 
                        value={editingElement.content} 
                        onChange={(e) => setEditingElement({...editingElement, content: e.target.value})}
                      />
                      <Button variant="outline" size="icon">
                        <Upload className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Width (px)</Label>
                      <Input 
                        type="number" 
                        value={editingElement.style?.width || 200} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, width: parseInt(e.target.value)}
                        })}
                      />
                    </div>
                    
                    <div className="space-y-2">
                      <Label>Height (px)</Label>
                      <Input 
                        type="number" 
                        value={editingElement.style?.height || 200} 
                        onChange={(e) => setEditingElement({
                          ...editingElement, 
                          style: {...editingElement.style, height: parseInt(e.target.value)}
                        })}
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Border Radius (px)</Label>
                    <Slider 
                      value={[parseInt(editingElement.style?.borderRadius) || 0]} 
                      max={50}
                      step={1}
                      onValueChange={(val) => setEditingElement({
                        ...editingElement, 
                        style: {...editingElement.style, borderRadius: `${val[0]}px`}
                      })}
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Content Link</Label>
                    <Select 
                      value={editingElement.contentKey || "none"} 
                      onValueChange={(val) => setEditingElement({
                        ...editingElement,
                        contentKey: val === "none" ? undefined : val
                      })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Link to content field" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">No link (use fixed image)</SelectItem>
                        <SelectItem value="image">Content Image</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Animation</Label>
                    <Select 
                      value={editingElement.animation || "fadeIn"} 
                      onValueChange={(val) => setEditingElement({
                        ...editingElement,
                        animation: val
                      })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Choose animation" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="fadeIn">Fade In</SelectItem>
                        <SelectItem value="slideIn">Slide In</SelectItem>
                        <SelectItem value="zoomIn">Zoom In</SelectItem>
                        <SelectItem value="bounceIn">Bounce In</SelectItem>
                        <SelectItem value="flipIn">Flip In</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}
              
              {editingElement.type === "audio" && (
                <>
                  <div className="space-y-2">
                    <Label>Audio Source</Label>
                    <div className="flex space-x-2">
                      <Input 
                        value={editingElement.content} 
                        onChange={(e) => setEditingElement({...editingElement, content: e.target.value})}
                      />
                      <Button variant="outline" size="icon">
                        <Upload className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Content Link</Label>
                    <Select 
                      value={editingElement.contentKey || "none"} 
                      onValueChange={(val) => setEditingElement({
                        ...editingElement,
                        contentKey: val === "none" ? undefined : val
                      })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Link to content field" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">No link (use fixed audio)</SelectItem>
                        <SelectItem value="audio">Content Audio</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}
              
              <Alert className="bg-blue-50 border-blue-200">
                <AlertTriangle className="h-4 w-4 text-blue-500" />
                <AlertDescription className="text-blue-700 text-sm">
                  {audioSyncEnabled ? 
                    "Audio synchronization is enabled. Element timing will adapt based on audio duration." :
                    "Audio synchronization is disabled. Element timing will use fixed values."}
                </AlertDescription>
              </Alert>
            </div>
          )}
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditor(false)}>Cancel</Button>
            <Button onClick={() => updateElement(editingElement)}>Save Changes</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {/* Load Project Dialog */}
      <Dialog open={showLoadProjectDialog} onOpenChange={setShowLoadProjectDialog}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Load Project</DialogTitle>
            <DialogDescription>
              Select a project to load
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 pt-2">
            {savedProjects.length > 0 ? (
              <div className="space-y-2">
                {savedProjects.map(project => (
                  <div 
                    key={project.id} 
                    className="flex items-center justify-between p-3 border rounded-md hover:bg-gray-50 cursor-pointer"
                    onClick={() => loadProject(project)}
                  >
                    <div>
                      <h3 className="font-medium">{project.name}</h3>
                      <p className="text-sm text-gray-500">
                        Last saved: {new Date(project.lastSaved).toLocaleString()}
                      </p>
                    </div>
                    <Button variant="ghost" size="sm">
                      <Upload className="h-4 w-4 mr-1" />
                      Load
                    </Button>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-slate-500">
                <FileText className="h-8 w-8 mx-auto mb-2" />
                <p>No saved projects found</p>
              </div>
            )}
          </div>
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowLoadProjectDialog(false)}>Cancel</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {/* Notification Toast */}
      <div className={`fixed bottom-4 right-4 ${notificationType === 'error' ? 'bg-red-600' : 'bg-slate-800'} text-white px-4 py-2 rounded-md shadow-lg transition-opacity duration-300 flex items-center ${showNotification ? 'opacity-100' : 'opacity-0'}`}>
        {notificationType === 'error' ? (
          <AlertTriangle className="h-4 w-4 mr-2 text-white" />
        ) : (
          <Check className="h-4 w-4 mr-2 text-green-400" />
        )}
        {notificationMessage}
      </div>
    </div>
  );
};

export default VideoGeneratorApp;
