     1→'use client';
     2→
     3→import { useEffect, useCallback, useRef } from 'react';
     4→import { motion, AnimatePresence } from 'framer-motion';
     5→import {
     6→  Sparkles, Play, Square, Trash2, ArrowLeft, Film,
     7→  Image, Mic, Loader2, Wand2, Clapperboard, Clock,
     8→  ChevronLeft, ChevronRight, Pause, Volume2, VolumeX,
     9→  RotateCcw, LayoutGrid, MonitorPlay
    10→} from 'lucide-react';
    11→import { Button } from '@/components/ui/button';
    12→import { Textarea } from '@/components/ui/textarea';
    13→import { Slider } from '@/components/ui/slider';
    14→import { Card, CardContent } from '@/components/ui/card';
    15→import { Badge } from '@/components/ui/badge';
    16→import { Progress } from '@/components/ui/progress';
    17→import { Skeleton } from '@/components/ui/skeleton';
    18→import { useVideoStore, type VideoProject } from '@/store/video-store';
    19→import { toast } from 'sonner';
    20→
    21→const STYLES = [
    22→  { id: 'cinematic', label: 'سينمائي', icon: '🎬', desc: 'جودة سينمائية عالية' },
    23→  { id: 'anime', label: 'أنمي', icon: '🎨', desc: 'رسوم أنمي يابانية' },
    24→  { id: 'realistic', label: 'واقعي', icon: '📷', desc: 'تصوير واقعي' },
    25→  { id: 'fantasy', label: 'خيالي', icon: '🧙', desc: 'عوالم خيالية' },
    26→  { id: 'documentary', label: 'وثائقي', icon: '📹', desc: 'أسلوب وثائقي' },
    27→  { id: 'watercolor', label: 'مائي', icon: '🖌️', desc: 'رسم مائي فني' },
    28→];
    29→
    30→const EXAMPLE_PROMPTS = [
    31→  'رحلة عبر الغابات المطيرة الاستوائية مع أصوات الطيور والشلالات',
    32→  'مدينة مستقبلية في عام 2150 مع السيارات الطائرة والأبنية الشفافة',
    33→  'قصة فتاة صغيرة تكتشف عالماً سحرياً خلف خزانة قديمة',
    34→  'غروب الشمس على شاطئ هادئ مع الأمواج والنورس الأبيض',
    35→];
    36→
    37→export default function Home() {
    38→  return (
    39→    <div className="min-h-screen flex flex-col">
    40→      <Header />
    41→      <main className="flex-1">
    42→        <AppContent />
    43→      </main>
    44→      <Footer />
    45→    </div>
    46→  );
    47→}
    48→
    49→/* ───────────────────── Header ───────────────────── */
    50→function Header() {
    51→  const { activeView, setActiveView, projects } = useVideoStore();
    52→
    53→  return (
    54→    <header className="glass sticky top-0 z-50 border-b border-border/50">
    55→      <div className="max-w-7xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between">
    56→        <button
    57→          onClick={() => setActiveView('create')}
    58→          className="flex items-center gap-3 group"
    59→        >
    60→          <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-purple-500 to-emerald-500 flex items-center justify-center shadow-lg">
    61→            <Clapperboard className="w-5 h-5 text-white" />
    62→          </div>
    63→          <div>
    64→            <h1 className="text-lg font-bold gradient-text leading-tight">مبدع الفيديو</h1>
    65→            <p className="text-[10px] text-muted-foreground -mt-0.5">AI Video Creator</p>
    66→          </div>
    67→        </button>
    68→
    69→        <nav className="flex items-center gap-2">
    70→          <Button
    71→            variant={activeView === 'create' ? 'default' : 'ghost'}
    72→            size="sm"
    73→            onClick={() => setActiveView('create')}
    74→            className="gap-1.5 text-sm"
    75→          >
    76→            <Wand2 className="w-4 h-4" />
    77→            <span className="hidden sm:inline">إنشاء</span>
    78→          </Button>
    79→          <Button
    80→            variant={activeView === 'gallery' ? 'default' : 'ghost'}
    81→            size="sm"
    82→            onClick={() => setActiveView('gallery')}
    83→            className="gap-1.5 text-sm"
    84→          >
    85→            <LayoutGrid className="w-4 h-4" />
    86→            <span className="hidden sm:inline">المكتبة</span>
    87→            {projects.length > 0 && (
    88→              <Badge variant="secondary" className="h-5 min-w-5 px-1.5 text-xs">
    89→                {projects.length}
    90→              </Badge>
    91→            )}
    92→          </Button>
    93→        </nav>
    94→      </div>
    95→    </header>
    96→  );
    97→}
    98→
    99→/* ───────────────────── App Content Router ───────────────────── */
   100→function AppContent() {
   101→  const { activeView, isGenerating } = useVideoStore();
   102→
   103→  return (
   104→    <AnimatePresence mode="wait">
   105→      {isGenerating ? (
   106→        <motion.div
   107→          key="generating"
   108→          initial={{ opacity: 0, y: 20 }}
   109→          animate={{ opacity: 1, y: 0 }}
   110→          exit={{ opacity: 0, y: -20 }}
   111→          className="max-w-4xl mx-auto px-4 sm:px-6 py-12"
   112→        >
   113→          <GenerationProgress />
   114→        </motion.div>
   115→      ) : activeView === 'player' ? (
   116→        <motion.div
   117→          key="player"
   118→          initial={{ opacity: 0, y: 20 }}
   119→          animate={{ opacity: 1, y: 0 }}
   120→          exit={{ opacity: 0, y: -20 }}
   121→          className="max-w-5xl mx-auto px-4 sm:px-6 py-8"
   122→        >
   123→          <VideoPlayer />
   124→        </motion.div>
   125→      ) : activeView === 'gallery' ? (
   126→        <motion.div
   127→          key="gallery"
   128→          initial={{ opacity: 0, y: 20 }}
   129→          animate={{ opacity: 1, y: 0 }}
   130→          exit={{ opacity: 0, y: -20 }}
   131→          className="max-w-7xl mx-auto px-4 sm:px-6 py-8"
   132→        >
   133→          <VideoGallery />
   134→        </motion.div>
   135→      ) : (
   136→        <motion.div
   137→          key="create"
   138→          initial={{ opacity: 0, y: 20 }}
   139→          animate={{ opacity: 1, y: 0 }}
   140→          exit={{ opacity: 0, y: -20 }}
   141→        >
   142→          <CreateSection />
   143→        </motion.div>
   144→      )}
   145→    </AnimatePresence>
   146→  );
   147→}
   148→
   149→/* ───────────────────── Create Section ───────────────────── */
   150→function CreateSection() {
   151→  const { prompt, setPrompt, selectedStyle, setSelectedStyle, sceneCount, setSceneCount, isGenerating, setIsGenerating, setGenerationProgress, setActiveView, setCurrentProject, addProject, projects, setProjects } = useVideoStore();
   152→
   153→  const handleGenerate = useCallback(async () => {
   154→    if (!prompt.trim()) {
   155→      toast.error('يرجى كتابة وصف للفيديو');
   156→      return;
   157→    }
   158→
   159→    setIsGenerating(true);
   160→    setGenerationProgress({ step: 'جاري تحليل الوصف وإنشاء المشاهد...', progress: 10 });
   161→
   162→    try {
   163→      const res = await fetch('/api/generate-video', {
   164→        method: 'POST',
   165→        headers: { 'Content-Type': 'application/json' },
   166→        body: JSON.stringify({ prompt: prompt.trim(), style: selectedStyle, sceneCount }),
   167→      });
   168→
   169→      if (!res.ok) {
   170→        const err = await res.json();
   171→        throw new Error(err.error || 'حدث خطأ أثناء التوليد');
   172→      }
   173→
   174→      const project = await res.json();
   175→      addProject(project);
   176→      setCurrentProject(project);
   177→      setActiveView('player');
   178→      toast.success('تم إنشاء الفيديو بنجاح!');
   179→    } catch (err: any) {
   180→      toast.error(err.message || 'حدث خطأ غير متوقع');
   181→      // Fetch updated project list
   182→      try {
   183→        const listRes = await fetch('/api/videos');
   184→        if (listRes.ok) {
   185→          const data = await listRes.json();
   186→          setProjects(data.projects || []);
   187→        }
   188→      } catch { /* ignore */ }
   189→    } finally {
   190→      setIsGenerating(false);
   191→    }
   192→  }, [prompt, selectedStyle, sceneCount]);
   193→
   194→  const handleExampleClick = (example: string) => {
   195→    setPrompt(example);
   196→  };
   197→
   198→  return (
   199→    <div className="relative overflow-hidden">
   200→      {/* Hero background */}
   201→      <div className="absolute inset-0 z-0">
   202→        <img src="/hero-bg.png" alt="" className="w-full h-full object-cover opacity-20" />
   203→        <div className="absolute inset-0 bg-gradient-to-b from-background/50 via-background/80 to-background" />
   204→      </div>
   205→
   206→      <div className="relative z-10 max-w-4xl mx-auto px-4 sm:px-6 pt-12 pb-20">
   207→        {/* Hero Text */}
   208→        <motion.div
   209→          initial={{ opacity: 0, y: 30 }}
   210→          animate={{ opacity: 1, y: 0 }}
   211→          transition={{ duration: 0.8 }}
   212→          className="text-center mb-10"
   213→        >
   214→          <motion.div
   215→            initial={{ scale: 0.8, opacity: 0 }}
   216→            animate={{ scale: 1, opacity: 1 }}
   217→            transition={{ delay: 0.2 }}
   218→            className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full glass text-sm text-muted-foreground mb-6"
   219→          >
   220→            <Sparkles className="w-4 h-4 text-purple-400" />
   221→            <span>مدعوم بالذكاء الاصطناعي المتقدم</span>
   222→          </motion.div>
   223→          <h2 className="text-3xl sm:text-5xl font-bold mb-4 leading-tight">
   224→            حوّل أفكارك إلى{' '}
   225→            <span className="gradient-text">فيديوهات مذهلة</span>
   226→          </h2>
   227→          <p className="text-muted-foreground text-base sm:text-lg max-w-2xl mx-auto">
   228→            اكتب وصفاً لما تريده وسيقوم الذكاء الاصطناعي بإنشاء مشاهد وصور وسرد صوتي تلقائياً
   229→          </p>
   230→        </motion.div>
   231→
   232→        {/* Main Creation Card */}
   233→        <motion.div
   234→          initial={{ opacity: 0, y: 30 }}
   235→          animate={{ opacity: 1, y: 0 }}
   236→          transition={{ delay: 0.4, duration: 0.6 }}
   237→        >
   238→          <Card className="glass glow-purple overflow-hidden">
   239→            <CardContent className="p-4 sm:p-6 space-y-5">
   240→              {/* Prompt Input */}
   241→              <div className="space-y-2">
   242→                <label className="text-sm font-medium flex items-center gap-2">
   243→                  <Film className="w-4 h-4 text-purple-400" />
   244→                  وصف الفيديو
   245→                </label>
   246→                <Textarea
   247→                  value={prompt}
   248→                  onChange={(e) => setPrompt(e.target.value)}
   249→                  placeholder="مثال: رحلة عبر الغابات المطيرة الاستوائية مع أصوات الطيور والشلالات..."
   250→                  className="min-h-[100px] sm:min-h-[120px] bg-background/50 border-border/50 resize-none text-base leading-relaxed placeholder:text-muted-foreground/50"
   251→                  dir="rtl"
   252→                />
   253→                <div className="flex justify-between items-center">
   254→                  <p className="text-xs text-muted-foreground">
   255→                    {prompt.length} حرف
   256→                  </p>
   257→                </div>
   258→              </div>
   259→
   260→              {/* Example Prompts */}
   261→              <div className="space-y-2">
   262→                <p className="text-xs text-muted-foreground font-medium">أفكار سريعة:</p>
   263→                <div className="flex flex-wrap gap-2">
   264→                  {EXAMPLE_PROMPTS.map((ex, i) => (
   265→                    <button
   266→                      key={i}
   267→                      onClick={() => handleExampleClick(ex)}
   268→                      className="text-xs px-3 py-1.5 rounded-full glass hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground truncate max-w-[250px]"
   269→                    >
   270→                      {ex}
   271→                    </button>
   272→                  ))}
   273→                </div>
   274→              </div>
   275→
   276→              {/* Style Selection */}
   277→              <div className="space-y-2">
   278→                <label className="text-sm font-medium flex items-center gap-2">
   279→                  <Image className="w-4 h-4 text-emerald-400" />
   280→                  نمط الفيديو
   281→                </label>
   282→                <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2">
   283→                  {STYLES.map((style) => (
   284→                    <button
   285→                      key={style.id}
   286→                      onClick={() => setSelectedStyle(style.id)}
   287→                      className={`relative p-3 rounded-xl border text-center transition-all duration-200 ${
   288→                        selectedStyle === style.id
   289→                          ? 'border-purple-500/50 bg-purple-500/10 glow-purple'
   290→                          : 'border-border/50 hover:border-border bg-background/30 hover:bg-accent/30'
   291→                      }`}
   292→                    >
   293→                      <span className="text-xl mb-1 block">{style.icon}</span>
   294→                      <span className="text-xs font-medium block">{style.label}</span>
   295→                      <span className="text-[10px] text-muted-foreground hidden sm:block">{style.desc}</span>
   296→                      {selectedStyle === style.id && (
   297→                        <div className="absolute -top-1 -left-1 w-4 h-4 bg-purple-500 rounded-full flex items-center justify-center">
   298→                          <svg className="w-2.5 h-2.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" /></svg>
   299→                        </div>
   300→                      )}
   301→                    </button>
   302→                  ))}
   303→                </div>
   304→              </div>
   305→
   306→              {/* Scene Count & Generate Button */}
   307→              <div className="flex flex-col sm:flex-row items-stretch sm:items-end gap-4 pt-2">
   308→                <div className="flex-1 space-y-2">
   309→                  <label className="text-sm font-medium flex items-center gap-2">
   310→                    <Clock className="w-4 h-4 text-orange-400" />
   311→                    عدد المشاهد: <span className="text-purple-400 font-bold">{sceneCount}</span>
   312→                  </label>
   313→                  <Slider
   314→                    value={[sceneCount]}
   315→                    onValueChange={([v]) => setSceneCount(v)}
   316→                    min={2}
   317→                    max={6}
   318→                    step={1}
   319→                    className="py-2"
   320→                  />
   321→                  <div className="flex justify-between text-[10px] text-muted-foreground">
   322→                    <span>2 مشاهد</span>
   323→                    <span>6 مشاهد</span>
   324→                  </div>
   325→                </div>
   326→
   327→                <Button
   328→                  onClick={handleGenerate}
   329→                  disabled={!prompt.trim() || isGenerating}
   330→                  className="w-full sm:w-auto h-12 px-8 bg-gradient-to-r from-purple-600 to-emerald-600 hover:from-purple-500 hover:to-emerald-500 text-white font-bold text-base gap-2 rounded-xl shadow-lg transition-all duration-300 hover:shadow-purple-500/20 hover:scale-[1.02] active:scale-[0.98]"
   331→                >
   332→                  {isGenerating ? (
   333→                    <Loader2 className="w-5 h-5 animate-spin" />
   334→                  ) : (
   335→                    <Sparkles className="w-5 h-5" />
   336→                  )}
   337→                  إنشاء الفيديو
   338→                </Button>
   339→              </div>
   340→            </CardContent>
   341→          </Card>
   342→        </motion.div>
   343→
   344→        {/* Recent projects preview */}
   345→        {projects.length > 0 && (
   346→          <motion.div
   347→            initial={{ opacity: 0 }}
   348→            animate={{ opacity: 1 }}
   349→            transition={{ delay: 0.8 }}
   350→            className="mt-10"
   351→          >
   352→            <div className="flex items-center justify-between mb-4">
   353→              <h3 className="text-lg font-semibold flex items-center gap-2">
   354→                <MonitorPlay className="w-5 h-5 text-purple-400" />
   355→                آخر الإبداعات
   356→              </h3>
   357→              <Button variant="ghost" size="sm" onClick={() => useVideoStore.getState().setActiveView('gallery')} className="text-muted-foreground text-sm">
   358→                عرض الكل
   359→              </Button>
   360→            </div>
   361→            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
   362→              {projects.slice(0, 4).map((project) => (
   363→                <ProjectCard key={project.id} project={project} compact />
   364→              ))}
   365→            </div>
   366→          </motion.div>
   367→        )}
   368→      </div>
   369→    </div>
   370→  );
   371→}
   372→
   373→/* ───────────────────── Generation Progress ───────────────────── */
   374→function GenerationProgress() {
   375→  const { generationProgress, prompt, selectedStyle, sceneCount } = useVideoStore();
   376→
   377→  const steps = [
   378→    { label: 'تحليل الوصف', icon: '🧠', threshold: 10 },
   379→    { label: 'كتابة السيناريو', icon: '📝', threshold: 25 },
   380→    { label: 'إنشاء المشاهد', icon: '🎨', threshold: 40 },
   381→    { label: 'توليد الصور', icon: '🖼️', threshold: 70 },
   382→    { label: 'تسجيل الصوت', icon: '🎙️', threshold: 90 },
   383→    { label: 'المعالجة النهائية', icon: '✨', threshold: 100 },
   384→  ];
   385→
   386→  return (
   387→    <div className="text-center space-y-8">
   388→      {/* Animated icon */}
   389→      <motion.div
   390→        animate={{ rotate: 360 }}
   391→        transition={{ duration: 3, repeat: Infinity, ease: 'linear' }}
   392→        className="inline-flex"
   393→      >
   394→        <div className="w-20 h-20 rounded-2xl bg-gradient-to-br from-purple-500/20 to-emerald-500/20 border border-purple-500/30 flex items-center justify-center">
   395→          <Sparkles className="w-10 h-10 text-purple-400" />
   396→        </div>
   397→      </motion.div>
   398→
   399→      <div>
   400→        <h2 className="text-2xl font-bold mb-2">جاري إنشاء الفيديو...</h2>
   401→        <p className="text-muted-foreground">{generationProgress.step}</p>
   402→      </div>
   403→
   404→      {/* Progress bar */}
   405→      <div className="max-w-md mx-auto space-y-3">
   406→        <Progress value={generationProgress.progress} className="h-2" />
   407→        <p className="text-sm text-muted-foreground">{generationProgress.progress}%</p>
   408→      </div>
   409→
   410→      {/* Steps */}
   411→      <div className="max-w-sm mx-auto grid grid-cols-3 gap-3">
   412→        {steps.map((step, i) => {
   413→          const isActive = generationProgress.progress >= step.threshold - 5;
   414→          const isDone = generationProgress.progress >= step.threshold + 5;
   415→          return (
   416→            <motion.div
   417→              key={i}
   418→              initial={{ opacity: 0, y: 10 }}
   419→              animate={{ opacity: 1, y: 0 }}
   420→              transition={{ delay: i * 0.1 }}
   421→              className={`p-3 rounded-xl border text-center transition-all duration-500 ${
   422→                isDone
   423→                  ? 'border-emerald-500/30 bg-emerald-500/10'
   424→                  : isActive
   425→                  ? 'border-purple-500/30 bg-purple-500/10 animate-pulse'
   426→                  : 'border-border/30 bg-background/30'
   427→              }`}
   428→            >
   429→              <span className="text-xl block mb-1">{step.icon}</span>
   430→              <span className="text-[10px] sm:text-xs text-muted-foreground block">{step.label}</span>
   431→              {isDone && (
   432→                <span className="text-emerald-400 text-[10px]">تم ✓</span>
   433→              )}
   434→            </motion.div>
   435→          );
   436→        })}
   437→      </div>
   438→
   439→      {/* Summary */}
   440→      <div className="inline-flex flex-wrap justify-center gap-2">
   441→        <Badge variant="secondary" className="gap-1"><Film className="w-3 h-3" />{STYLES.find(s => s.id === selectedStyle)?.label}</Badge>
   442→        <Badge variant="secondary" className="gap-1"><Image className="w-3 h-3" />{sceneCount} مشاهد</Badge>
   443→        <Badge variant="secondary" className="gap-1"><Mic className="w-3 h-3" />سرد صوتي</Badge>
   444→      </div>
   445→    </div>
   446→  );
   447→}
   448→
   449→/* ───────────────────── Video Player ───────────────────── */
   450→function VideoPlayer() {
   451→  const { currentProject, currentSceneIndex, setCurrentSceneIndex, isPlaying, setIsPlaying, setActiveView } = useVideoStore();
   452→  const audioRef = useRef<HTMLAudioElement>(null);
   453→  const timerRef = useRef<NodeJS.Timeout | null>(null);
   454→
   455→  const scenes = currentProject?.scenes || [];
   456→  const currentScene = scenes[currentSceneIndex];
   457→  const totalDuration = scenes.reduce((sum, s) => sum + (s.duration || 5), 0);
   458→
   459→  // Auto-advance scenes
   460→  useEffect(() => {
   461→    if (!isPlaying || !currentScene) return;
   462→
   463→    // Play audio if available
   464→    if (audioRef.current && currentScene.audioPath) {
   465→      audioRef.current.src = currentScene.audioPath;
   466→      audioRef.current.play().catch(() => {});
   467→    }
   468→
   469→    timerRef.current = setTimeout(() => {
   470→      if (currentSceneIndex < scenes.length - 1) {
   471→        setCurrentSceneIndex(currentSceneIndex + 1);
   472→      } else {
   473→        setIsPlaying(false);
   474→        setCurrentSceneIndex(0);
   475→      }
   476→    }, (currentScene.duration || 5) * 1000);
   477→
   478→    return () => {
   479→      if (timerRef.current) clearTimeout(timerRef.current);
   480→    };
   481→  }, [currentSceneIndex, isPlaying, scenes.length]);
   482→
   483→  const togglePlay = () => {
   484→    if (isPlaying) {
   485→      setIsPlaying(false);
   486→      if (timerRef.current) clearTimeout(timerRef.current);
   487→      if (audioRef.current) audioRef.current.pause();
   488→    } else {
   489→      setIsPlaying(true);
   490→    }
   491→  };
   492→
   493→  const goToScene = (index: number) => {
   494→    if (timerRef.current) clearTimeout(timerRef.current);
   495→    if (audioRef.current) audioRef.current.pause();
   496→    setCurrentSceneIndex(index);
   497→    setIsPlaying(false);
   498→  };
   499→
   500→  const prevScene = () => {
   501→    if (currentSceneIndex > 0) goToScene(currentSceneIndex - 1);
   502→  };
   503→
   504→  const nextScene = () => {
   505→    if (currentSceneIndex < scenes.length - 1) goToScene(currentSceneIndex + 1);
   506→  };
   507→
   508→  if (!currentProject || scenes.length === 0) {
   509→    return (
   510→      <div className="text-center py-20">
   511→        <p className="text-muted-foreground">لم يتم العثور على الفيديو</p>
   512→        <Button variant="outline" onClick={() => setActiveView('create')} className="mt-4">
   513→          العودة للإنشاء
   514→        </Button>
   515→      </div>
   516→    );
   517→  }
   518→
   519→  return (
   520→    <div className="space-y-6">
   521→      {/* Back button & Title */}
   522→      <div className="flex items-center gap-4">
   523→        <Button variant="ghost" size="icon" onClick={() => setActiveView('gallery')} className="shrink-0">
   524→          <ArrowLeft className="w-5 h-5" />
   525→        </Button>
   526→        <div className="min-w-0">
   527→          <h2 className="text-xl sm:text-2xl font-bold truncate">{currentProject.title}</h2>
   528→          <p className="text-sm text-muted-foreground truncate">{currentProject.prompt}</p>
   529→        </div>
   530→      </div>
   531→
   532→      {/* Video Player */}
   533→      <Card className="overflow-hidden glow-purple">
   534→        <div className="relative video-container bg-black">
   535→          {currentScene?.imagePath ? (
   536→            <img
   537→              key={currentScene.id}
   538→              src={currentScene.imagePath}
   539→              alt={currentScene.narrationText || currentScene.description || 'مشهد فيديو'}
   540→              className="w-full h-full object-cover scene-enter"
   541→            />
   542→          ) : (
   543→            <div className="w-full h-full flex items-center justify-center shimmer" />
   544→          )}
   545→
   546→          {/* Scene info overlay */}
   547→          <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 sm:p-6">
   548→            <p className="text-white text-sm sm:text-base leading-relaxed max-w-2xl">
   549→              {currentScene?.narrationText || currentScene?.description}
   550→            </p>
   551→            <div className="flex items-center gap-3 mt-2">
   552→              <Badge variant="secondary" className="bg-white/10 text-white border-white/20 text-xs">
   553→                مشهد {currentSceneIndex + 1} من {scenes.length}
   554→              </Badge>
   555→              {currentScene?.duration && (
   556→                <span className="text-white/60 text-xs flex items-center gap-1">
   557→                  <Clock className="w-3 h-3" />
   558→                  {currentScene.duration} ثانية
   559→                </span>
   560→              )}
   561→            </div>
   562→          </div>
   563→
   564→          {/* Play/Pause overlay button */}
   565→          <button
   566→            onClick={togglePlay}
   567→            className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-16 h-16 sm:w-20 sm:h-20 rounded-full bg-white/10 backdrop-blur-sm border border-white/20 flex items-center justify-center hover:bg-white/20 transition-all duration-200 group"
   568→          >
   569→            {isPlaying ? (
   570→              <Pause className="w-7 h-7 sm:w-8 sm:h-8 text-white group-hover:scale-110 transition-transform" />
   571→            ) : (
   572→              <Play className="w-7 h-7 sm:w-8 sm:h-8 text-white group-hover:scale-110 transition-transform mr-[-2px]" />
   573→            )}
   574→          </button>
   575→        </div>
   576→
   577→        {/* Controls */}
   578→        <div className="p-3 sm:p-4 space-y-3">
   579→          {/* Progress bar */}
   580→          <div className="flex items-center gap-3">
   581→            <span className="text-xs text-muted-foreground w-12 text-center">
   582→              {currentSceneIndex + 1}/{scenes.length}
   583→            </span>
   584→            <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
   585→              <motion.div
   586→                className="h-full bg-gradient-to-r from-purple-500 to-emerald-500 rounded-full"
   587→                animate={{ width: `${((currentSceneIndex + 1) / scenes.length) * 100}%` }}
   588→                transition={{ duration: 0.3 }}
   589→              />
   590→            </div>
   591→            <span className="text-xs text-muted-foreground w-16 text-left">
   592→              {totalDuration} ثانية
   593→            </span>
   594→          </div>
   595→
   596→          {/* Buttons */}
   597→          <div className="flex items-center justify-center gap-2">
   598→            <Button variant="ghost" size="icon" onClick={prevScene} disabled={currentSceneIndex === 0}>
   599→              <ChevronRight className="w-5 h-5" />
   600→            </Button>
   601→            <Button variant="ghost" size="icon" onClick={togglePlay} className="w-12 h-12 rounded-full">
   602→              {isPlaying ? <Square className="w-5 h-5" /> : <Play className="w-5 h-5 mr-[-2px]" />}
   603→            </Button>
   604→            <Button variant="ghost" size="icon" onClick={nextScene} disabled={currentSceneIndex === scenes.length - 1}>
   605→              <ChevronLeft className="w-5 h-5" />
   606→            </Button>
   607→            <Button variant="ghost" size="icon" onClick={() => goToScene(0)} className="mr-2">
   608→              <RotateCcw className="w-4 h-4" />
   609→            </Button>
   610→          </div>
   611→        </div>
   612→      </Card>
   613→
   614→      {/* Scene Thumbnails */}
   615→      <div className="space-y-2">
   616→        <h3 className="text-sm font-medium text-muted-foreground">المشاهد</h3>
   617→        <div className="flex gap-2 overflow-x-auto pb-2">
   618→          {scenes.map((scene, i) => (
   619→            <button
   620→              key={scene.id}
   621→              onClick={() => goToScene(i)}
   622→              className={`shrink-0 w-28 sm:w-36 rounded-lg overflow-hidden border-2 transition-all duration-200 ${
   623→                i === currentSceneIndex
   624→                  ? 'border-purple-500 glow-purple scale-105'
   625→                  : 'border-transparent hover:border-border'
   626→              }`}
   627→            >
   628→              <div className="aspect-video bg-muted">
   629→                {scene.imagePath ? (
   630→                  <img src={scene.imagePath} alt={`مشهد ${i + 1}`} className="w-full h-full object-cover" />
   631→                ) : (
   632→                  <Skeleton className="w-full h-full" />
   633→                )}
   634→              </div>
   635→              <div className="p-1.5 bg-card">
   636→                <p className="text-[10px] text-muted-foreground truncate">مشهد {i + 1}</p>
   637→              </div>
   638→            </button>
   639→          ))}
   640→        </div>
   641→      </div>
   642→
   643→      {/* Audio element */}
   644→      <audio ref={audioRef} preload="auto" />
   645→
   646→      {/* Project Info */}
   647→      <Card className="glass">
   648→        <CardContent className="p-4">
   649→          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-center">
   650→            <div>
   651→              <p className="text-xs text-muted-foreground">النمط</p>
   652→              <p className="font-medium">{STYLES.find(s => s.id === currentProject.style)?.label || currentProject.style}</p>
   653→            </div>
   654→            <div>
   655→              <p className="text-xs text-muted-foreground">المشاهد</p>
   656→              <p className="font-medium">{scenes.length}</p>
   657→            </div>
   658→            <div>
   659→              <p className="text-xs text-muted-foreground">المدة</p>
   660→              <p className="font-medium">{totalDuration} ثانية</p>
   661→            </div>
   662→            <div>
   663→              <p className="text-xs text-muted-foreground">تاريخ الإنشاء</p>
   664→              <p className="font-medium text-xs">{new Date(currentProject.createdAt).toLocaleDateString('ar-EG')}</p>
   665→            </div>
   666→          </div>
   667→        </CardContent>
   668→      </Card>
   669→    </div>
   670→  );
   671→}
   672→
   673→/* ───────────────────── Video Gallery ───────────────────── */
   674→function VideoGallery() {
   675→  const { projects, setProjects, removeProject, setActiveView, setCurrentProject } = useVideoStore();
   676→
   677→  const fetchProjects = async () => {
   678→    try {
   679→      const res = await fetch('/api/videos');
   680→      if (res.ok) {
   681→        const data = await res.json();
   682→        setProjects(data.projects || []);
   683→      }
   684→    } catch {
   685→      // silently fail
   686→    }
   687→  };
   688→
   689→  useEffect(() => {
   690→    fetchProjects();
   691→  }, []);
   692→
   693→  const handleDelete = async (id: string) => {
   694→    try {
   695→      await fetch(`/api/videos/${id}`, { method: 'DELETE' });
   696→      removeProject(id);
   697→      toast.success('تم حذف الفيديو');
   698→    } catch {
   699→      toast.error('فشل في حذف الفيديو');
   700→    }
   701→  };
   702→
   703→  const handlePlay = async (project: VideoProject) => {
   704→    try {
   705→      const res = await fetch(`/api/videos/${project.id}`);
   706→      if (res.ok) {
   707→        const data = await res.json();
   708→        setCurrentProject(data);
   709→        setActiveView('player');
   710→      }
   711→    } catch {
   712→      toast.error('فشل في تحميل الفيديو');
   713→    }
   714→  };
   715→
   716→  if (projects.length === 0) {
   717→    return (
   718→      <div className="text-center py-20">
   719→        <div className="w-20 h-20 rounded-2xl bg-muted/50 flex items-center justify-center mx-auto mb-4">
   720→          <Film className="w-10 h-10 text-muted-foreground" />
   721→        </div>
   722→        <h3 className="text-xl font-semibold mb-2">لا توجد فيديوهات بعد</h3>
   723→        <p className="text-muted-foreground mb-6">ابدأ بإنشاء أول فيديو لك بالذكاء الاصطناعي</p>
   724→        <Button onClick={() => setActiveView('create')} className="gap-2">
   725→          <Wand2 className="w-4 h-4" />
   726→          إنشاء فيديو جديد
   727→        </Button>
   728→      </div>
   729→    );
   730→  }
   731→
   732→  return (
   733→    <div className="space-y-6">
   734→      <div className="flex items-center justify-between">
   735→        <h2 className="text-2xl font-bold">مكتبة الفيديوهات</h2>
   736→        <Button onClick={() => setActiveView('create')} className="gap-2 bg-gradient-to-r from-purple-600 to-emerald-600 hover:from-purple-500 hover:to-emerald-500 text-white">
   737→          <Wand2 className="w-4 h-4" />
   738→          <span className="hidden sm:inline">إنشاء جديد</span>
   739→        </Button>
   740→      </div>
   741→
   742→      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
   743→        {projects.map((project) => (
   744→          <ProjectCard
   745→            key={project.id}
   746→            project={project}
   747→            onPlay={() => handlePlay(project)}
   748→            onDelete={() => handleDelete(project.id)}
   749→          />
   750→        ))}
   751→      </div>
   752→    </div>
   753→  );
   754→}
   755→
   756→/* ───────────────────── Project Card ───────────────────── */
   757→function ProjectCard({
   758→  project,
   759→  compact = false,
   760→  onPlay,
   761→  onDelete,
   762→}: {
   763→  project: VideoProject;
   764→  compact?: boolean;
   765→  onPlay?: () => void;
   766→  onDelete?: () => void;
   767→}) {
   768→  const { setActiveView, setCurrentProject } = useVideoStore();
   769→
   770→  const handleClick = async () => {
   771→    if (onPlay) {
   772→      onPlay();
   773→    } else {
   774→      try {
   775→        const res = await fetch(`/api/videos/${project.id}`);
   776→        if (res.ok) {
   777→          const data = await res.json();
   778→          setCurrentProject(data);
   779→          setActiveView('player');
   780→        }
   781→      } catch {
   782→        toast.error('فشل في تحميل الفيديو');
   783→      }
   784→    }
   785→  };
   786→
   787→  const handleDeleteClick = (e: React.MouseEvent) => {
   788→    e.stopPropagation();
   789→    if (onDelete) onDelete();
   790→  };
   791→
   792→  const statusLabel = project.status === 'completed' ? 'مكتمل' : project.status === 'generating' ? 'قيد الإنشاء' : 'فشل';
   793→  const statusColor = project.status === 'completed' ? 'bg-emerald-500/20 text-emerald-400' : project.status === 'generating' ? 'bg-amber-500/20 text-amber-400' : 'bg-red-500/20 text-red-400';
   794→
   795→  return (
   796→    <motion.div
   797→      whileHover={{ scale: 1.02 }}
   798→      whileTap={{ scale: 0.98 }}
   799→    >
   800→      <Card
   801→        className="cursor-pointer group overflow-hidden hover:border-purple-500/30 transition-all duration-300"
   802→        onClick={handleClick}
   803→      >
   804→        {/* Thumbnail */}
   805→        <div className="relative aspect-video bg-muted overflow-hidden">
   806→          {project.thumbnail ? (
   807→            <img src={project.thumbnail} alt={project.title} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
   808→          ) : (
   809→            <Skeleton className="w-full h-full" />
   810→          )}
   811→          {/* Overlay */}
   812→          <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-300 flex items-center justify-center">
   813→            <div className="w-12 h-12 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300 border border-white/30">
   814→              <Play className="w-5 h-5 text-white mr-[-2px]" />
   815→            </div>
   816→          </div>
   817→          {/* Status badge */}
   818→          <div className="absolute top-2 left-2">
   819→            <span className={`text-[10px] px-2 py-0.5 rounded-full font-medium ${statusColor}`}>
   820→              {statusLabel}
   821→            </span>
   822→          </div>
   823→          {/* Scene count */}
   824→          <div className="absolute bottom-2 right-2">
   825→            <span className="text-[10px] px-2 py-0.5 rounded-full bg-black/60 text-white/80">
   826→              {project.sceneCount} مشاهد
   827→            </span>
   828→          </div>
   829→        </div>
   830→
   831→        {/* Info */}
   832→        <CardContent className={`p-3 ${compact ? 'p-2' : ''}`}>
   833→          <h3 className="font-semibold text-sm truncate">{project.title}</h3>
   834→          {!compact && (
   835→            <p className="text-xs text-muted-foreground truncate mt-1">{project.prompt}</p>
   836→          )}
   837→          <div className="flex items-center justify-between mt-2">
   838→            <span className="text-[10px] text-muted-foreground">
   839→              {new Date(project.createdAt).toLocaleDateString('ar-EG')}
   840→            </span>
   841→            <div className="flex items-center gap-1">
   842→              <Badge variant="outline" className="text-[10px] h-5 px-1.5">
   843→                {STYLES.find(s => s.id === project.style)?.label || project.style}
   844→              </Badge>
   845→              {onDelete && (
   846→                <Button
   847→                  variant="ghost"
   848→                  size="icon"
   849→                  className="w-7 h-7 text-muted-foreground hover:text-destructive"
   850→                  onClick={handleDeleteClick}
   851→                >
   852→                  <Trash2 className="w-3.5 h-3.5" />
   853→                </Button>
   854→              )}
   855→            </div>
   856→          </div>
   857→        </CardContent>
   858→      </Card>
   859→    </motion.div>
   860→  );
   861→}
   862→
   863→/* ───────────────────── Footer ───────────────────── */
   864→function Footer() {
   865→  return (
   866→    <footer className="glass border-t border-border/50 mt-auto">
   867→      <div className="max-w-7xl mx-auto px-4 sm:px-6 py-4">
   868→        <div className="flex flex-col sm:flex-row items-center justify-between gap-2 text-sm text-muted-foreground">
   869→          <div className="flex items-center gap-2">
   870→            <div className="w-5 h-5 rounded bg-gradient-to-br from-purple-500 to-emerald-500 flex items-center justify-center">
   871→              <Clapperboard className="w-3 h-3 text-white" />
   872→            </div>
   873→            <span>مبدع الفيديو بالذكاء الاصطناعي</span>
   874→          </div>
   875→          <p>مدعوم بتقنيات الذكاء الاصطناعي المتقدمة</p>
   876→        </div>
   877→      </div>
   878→    </footer>
   879→  );
   880→}