import { useState, useRef, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Camera, Type, Check, Palette, Smile, Brush, Filter, RotateCcw, Eye, MoreVertical, Globe, Users, Lock, ChevronLeft, ChevronRight, Trash2, Scissors, Music, Eraser, Minus, Plus, Maximize, Trash, SlidersHorizontal, Sun, Contrast, Droplets, Wind, Pipette, Type as FontIcon, AlignCenter } from 'lucide-react';
import { useLang } from '../../../../core/infrastructure/i18n';
import { ChatApi } from '../../../chats/infrastructure/chatApi';
import { StoryApi } from '../../infrastructure/storyApi';
import Cropper from 'react-easy-crop';
import { getMediaUrl } from '../../../../core/utils/utils';
import { useAuthStore } from '../../../auth/application/authStore';
import Avatar from '../../../../core/presentation/components/ui/Avatar';
import Picker from '@emoji-mart/react';
import data from '@emoji-mart/data';

const FONTS = [
  { id: 'inter', name: 'Standard', family: 'Inter, sans-serif' },
  { id: 'serif', name: 'Playfair', family: '"Playfair Display", serif' },
  { id: 'mono', name: 'Retro', family: '"Fira Code", monospace' },
  { id: 'script', name: 'Elegant', family: '"Dancing Script", cursive' },
  { id: 'black', name: 'Impact', family: '"Archivo Black", sans-serif' },
];

interface TextObject {
  id: number;
  text: string;
  x: number;
  y: number;
  color: string;
  font: string;
  size: number;
  scale: number;
}

interface CreateStoryModalProps {
  onClose: () => void;
  onCreated: () => void;
}

export function CreateStoryModal({ onClose, onCreated }: CreateStoryModalProps) {
  const { t, lang } = useLang();
  const { user } = useAuthStore();
  
  const [mediaFile, setMediaFile] = useState<File | null>(null);
  const [mediaPreview, setMediaPreview] = useState<string | null>(null);
  const [croppedPreview, setCroppedPreview] = useState<string | null>(null);
  const [bgColor, setBgColor] = useState('#1e1e2e');
  const [isUploading, setIsUploading] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [privacy, setPrivacy] = useState<'all' | 'contacts' | 'selected'>('all');
  const [startTime, setStartTime] = useState(0);
  const [endTime, setEndTime] = useState(0);
  const [videoDuration, setVideoDuration] = useState(0);
  const [tool, setTool] = useState<'none' | 'crop' | 'brush' | 'stickers' | 'filters' | 'privacy' | 'text' | 'trim'>('none');
  const [paused, setPaused] = useState(false);
  const [thumbnails, setThumbnails] = useState<string[]>([]);
  const [zoom, setZoom] = useState(1);
  const editorVideoRef = useRef<HTMLVideoElement>(null);
  const trimVideoRef = useRef<HTMLVideoElement>(null);

  const [textObjects, setTextObjects] = useState<TextObject[]>([]);
  const [selectedTextId, setSelectedTextId] = useState<number | null>(null);
  const [stickers, setStickers] = useState<Array<{ id: number, emoji: string, x: number, y: number, scale: number }>>([]);
  const [selectedStickerId, setSelectedStickerId] = useState<number | null>(null);
  const [currentPlayTime, setCurrentPlayTime] = useState(0);
  
  const [brushColor, setBrushColor] = useState('#ffffff');
  const [brushSize, setBrushSize] = useState(8);
  
  const [crop, setCrop] = useState({ x: 0, y: 0 });
  const [rotation, setRotation] = useState(0);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<any>(null);
  const [adjustments, setAdjustments] = useState({ brightness: 100, contrast: 100, saturate: 100, sepia: 0, grayscale: 0 });
  
  const fileInputRef = useRef<HTMLInputElement>(null);
  const stageRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const timelineRef = useRef<HTMLDivElement>(null);
  const isDrawingRef = useRef(false);

  // Wheel Zoom Implementation
  useEffect(() => {
    const el = timelineRef.current;
    if (!el) return;

    const handleWheel = (e: WheelEvent) => {
        e.preventDefault();
        const delta = e.deltaY > 0 ? -0.1 : 0.1; // Smaller increments
        setZoom(prev => Math.max(1, Math.min(20, prev + delta)));
    };

    el.addEventListener('wheel', handleWheel, { passive: false });
    return () => el.removeEventListener('wheel', handleWheel);
  }, [tool]);

  // Scroll Lock implementation
  useEffect(() => {
    const originalStyle = window.getComputedStyle(document.body).overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = originalStyle;
    };
  }, []);

  // Smooth Playback Loop for Timeline
  useEffect(() => {
    let rafId: number;
    const update = () => {
      const v = trimVideoRef.current;
      if (v && !v.paused && tool === 'trim') {
        const cur = v.currentTime;
        setCurrentPlayTime(cur);
        
        // Correct boundary check: only pause at the end.
        if (cur >= endTime) {
            v.pause();
            v.currentTime = startTime;
            setPaused(true);
            setCurrentPlayTime(startTime);
        } else if (cur < startTime - 0.1) {
            v.currentTime = startTime;
            setCurrentPlayTime(startTime);
        }
      }
      rafId = requestAnimationFrame(update);
    };
    rafId = requestAnimationFrame(update);
    return () => cancelAnimationFrame(rafId);
  }, [tool, startTime, endTime]);

  const TARGET_W = 1080;
  const TARGET_H = 1920;
  const SCALE_FACTOR = TARGET_W / 400;

  const getFilterCss = () => `brightness(${adjustments.brightness}%) contrast(${adjustments.contrast}%) saturate(${adjustments.saturate}%) sepia(${adjustments.sepia}%) grayscale(${adjustments.grayscale}%)`;

  const handleMediaSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setMediaFile(file);
    const url = URL.createObjectURL(file);
    setMediaPreview(url);
    setCroppedPreview(null);
    
    if (file.type.startsWith('video/')) {
        const v = document.createElement('video');
        v.src = url;
        v.onloadedmetadata = async () => {
            setVideoDuration(v.duration);
            setStartTime(0);
            setEndTime(v.duration);
            setZoom(1);
            setCurrentPlayTime(0);
            setThumbnails([]);
            
            if (v.duration > 120) {
                setTool('trim');
            } else {
                setTool('none');
            }
            
            // Generate thumbnails for storyboard
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = 160;
            canvas.height = 90;
            const thumbs: string[] = [];
            const count = v.duration > 1800 ? 5 : (v.duration > 300 ? 8 : 10);
            for (let i = 0; i < count; i++) {
                v.currentTime = (v.duration / count) * i;
                await new Promise(r => {
                    const onSeek = () => {
                        v.removeEventListener('seeked', onSeek);
                        r(null);
                    };
                    v.addEventListener('seeked', onSeek);
                    setTimeout(() => {
                        v.removeEventListener('seeked', onSeek);
                        r(null);
                    }, 1200); // Increased timeout for long videos
                });
                ctx?.drawImage(v, 0, 0, 160, 90);
                thumbs.push(canvas.toDataURL('image/jpeg', 0.4)); // Lower JPEG quality to save memory
            }
            setThumbnails(thumbs);
            setPaused(true); // Don't auto-play
            setCurrentPlayTime(0);
            if (v.duration > 120) {
                if (editorVideoRef.current) editorVideoRef.current.currentTime = 0;
                if (trimVideoRef.current) trimVideoRef.current.currentTime = 0;
            }
        };
    } else {
        setTool('crop');
    }
  };

  const removeMedia = () => {
    setMediaFile(null);
    setMediaPreview(null);
    setCroppedPreview(null);
    setCroppedAreaPixels(null);
    setTool('none');
    setStartTime(0);
    setEndTime(0);
    setVideoDuration(0);
    setCurrentPlayTime(0);
    setZoom(1);
    setThumbnails([]);
  };

  const addText = () => {
    const id = Date.now();
    setTextObjects([...textObjects, { id, text: t('textStory'), x: 20, y: 40, color: '#ffffff', font: FONTS[0].family, size: 42, scale: 1 }]);
    setSelectedTextId(id);
    setTool('none');
    setTimeout(() => setTool('text'), 50);
  };

  const addSticker = (emoji: any) => {
    const id = Date.now();
    setStickers([...stickers, { id, emoji: emoji.native, x: 30, y: 50, scale: 1.5 }]);
    setSelectedStickerId(id);
  };

  const clearCanvas = () => {
    const canvas = canvasRef.current;
    if (canvas) {
        const ctx = canvas.getContext('2d');
        if (ctx) ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  };

  const loadImage = (src: string): Promise<HTMLImageElement> => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = async () => {
          try {
              if ('decode' in img) await img.decode();
              resolve(img);
          } catch(e) {
              resolve(img); // Fallback
          }
      };
      img.onerror = (e) => reject(e);
      img.src = src;
    });
  };

  const handleCropDone = async () => {
    if (croppedAreaPixels && mediaPreview) {
      try {
        const image = await loadImage(mediaPreview);
        const canvas = document.createElement('canvas');
        canvas.width = croppedAreaPixels.width;
        canvas.height = croppedAreaPixels.height;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;
        ctx.drawImage(image, croppedAreaPixels.x, croppedAreaPixels.y, croppedAreaPixels.width, croppedAreaPixels.height, 0, 0, croppedAreaPixels.width, croppedAreaPixels.height);
        canvas.toBlob(blob => {
          if (blob) {
            const url = URL.createObjectURL(blob);
            setCroppedPreview(url);
          }
        }, 'image/jpeg', 0.95);
      } catch (e) {
        console.error('Crop bake error', e);
      }
    }
    setTool('none');
  };

  const handlePublish = async () => {
    setIsUploading(true);
    try {
      const isVideo = mediaFile?.type.startsWith('video/');
      let url = '';
      let type = isVideo ? 'video' : 'image';
      let content = '';

      if (isVideo && mediaFile) {
        const res = await StoryApi.uploadVideoToStory(mediaFile);
        url = res.url;
        const meta = {
            stickers,
            textObjects,
            trim: startTime > 0 || endTime < videoDuration ? { start: startTime, end: endTime } : null
        };
        content = JSON.stringify(meta);
      } else {
        const canvas = document.createElement('canvas');
        canvas.width = TARGET_W;
        canvas.height = TARGET_H;
        const ctx = canvas.getContext('2d');
        if (!ctx) throw new Error('Canvas init failed');

        ctx.fillStyle = bgColor;
        ctx.fillRect(0, 0, TARGET_W, TARGET_H);

        const baseSrc = croppedPreview || mediaPreview;
        if (baseSrc && (mediaFile?.type.startsWith('image/') || !mediaFile)) {
          const img = await loadImage(baseSrc);
          ctx.save();
          ctx.filter = getFilterCss();
          
          if (!croppedPreview && croppedAreaPixels) {
              ctx.drawImage(img, croppedAreaPixels.x, croppedAreaPixels.y, croppedAreaPixels.width, croppedAreaPixels.height, 0, 0, TARGET_W, TARGET_H);
          } else {
              // Calculate "cover" manually to avoid squashing if image ratio != 9:16
              const targetRatio = TARGET_W / TARGET_H;
              const imgRatio = img.width / img.height;
              let sx, sy, sw, sh;
              if (imgRatio > targetRatio) {
                  sh = img.height;
                  sw = img.height * targetRatio;
                  sx = (img.width - sw) / 2;
                  sy = 0;
              } else {
                  sw = img.width;
                  sh = img.width / targetRatio;
                  sx = 0;
                  sy = (img.height - sh) / 2;
              }
              ctx.drawImage(img, sx, sy, sw, sh, 0, 0, TARGET_W, TARGET_H);
          }
          ctx.restore();
        }

        if (canvasRef.current) {
          ctx.drawImage(canvasRef.current, 0, 0, TARGET_W, TARGET_H);
        }

        ctx.textAlign = 'left';
        ctx.textBaseline = 'middle';
        
        stickers.forEach(s => {
          ctx.font = `${s.scale * 100}px "Apple Color Emoji", "Segoe UI Emoji", serif`;
          ctx.fillText(s.emoji, (s.x / 100) * TARGET_W, (s.y / 100) * TARGET_H);
        });

        textObjects.forEach(t => {
          const fontSize = t.size * SCALE_FACTOR * t.scale;
          ctx.font = `bold ${fontSize}px ${t.font}`;
          ctx.fillStyle = t.color;
          ctx.fillText(t.text, (t.x / 100) * TARGET_W, (t.y / 100) * TARGET_H);
        });

        const blob = await new Promise<Blob>((resolve, reject) => {
          canvas.toBlob(b => b ? resolve(b) : reject('Blob error'), 'image/jpeg', 0.95);
        });

        const fileToUpload = new File([blob], `story_${Date.now()}.jpg`, { type: 'image/jpeg' });
        const uploadRes = await ChatApi.uploadFile(fileToUpload);
        url = uploadRes.url;
      }

      if (!url) throw new Error('Upload failed');

      await StoryApi.createStory({
        type,
        mediaUrl: url,
        bgColor: bgColor,
        content: content,
        privacy: privacy,
        isMuted: isVideo ? isMuted : false,
      } as any);

      onCreated();
      onClose();
    } catch (e) {
      console.error('Publishing error:', e);
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-[200] bg-black/90 backdrop-blur-xl flex items-center justify-center lg:p-12">
      <motion.div initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="w-full h-full lg:max-h-[850px] lg:max-w-[1200px] bg-[#070707] lg:rounded-[3rem] shadow-[0_50px_100px_-30px_rgba(0,0,0,0.8)] lg:border lg:border-white/10 flex flex-col overflow-hidden relative">
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@700&family=Playfair+Display:ital,wght@1,900&family=Fira+Code:wght@700&family=Archivo+Black&display=swap');
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
      `}</style>
      
      <header className="h-16 lg:h-20 px-4 lg:px-8 flex items-center justify-between border-b border-white/5 bg-[#0a0a0a] z-50 shadow-2xl safe-area-top">
        <div className="flex items-center gap-3 lg:gap-6">
          <button onClick={onClose} className="w-10 h-10 rounded-full hover:bg-white/5 flex items-center justify-center text-zinc-400 hover:text-white transition-all">
            <X size={24} />
          </button>
          <h1 className="text-[10px] lg:text-sm font-black uppercase tracking-[0.1em] lg:tracking-[0.2em] italic text-zinc-400 truncate max-w-[120px] lg:max-w-none">{t('storiesEditor')}</h1>
        </div>
        <div className="flex items-center gap-2 lg:gap-4 overflow-x-auto no-scrollbar py-2">
          {mediaFile?.type.startsWith('video/') && (
            <div className="flex items-center gap-2">
              <button onClick={() => setTool('trim')} className={`p-2 lg:p-3 rounded-xl border transition-all ${tool === 'trim' ? 'bg-primary/10 border-primary/40 text-primary' : 'bg-white/5 border-white/10 text-zinc-400 hover:text-white'}`} title={t('trimVideo')}>
                <span className="material-symbols-outlined text-sm lg:text-base">content_cut</span>
                <span className="ml-1 lg:ml-2 text-[8px] lg:text-[10px] font-black uppercase tracking-widest hidden sm:inline">{t('trim')}</span>
              </button>
              <button onClick={() => setIsMuted(!isMuted)} className={`p-2 lg:p-3 rounded-xl border transition-all ${isMuted ? 'bg-red-500/10 border-red-500/40 text-red-500' : 'bg-white/5 border-white/10 text-zinc-400 hover:text-white'}`} title={isMuted ? t("unmuteVideo") : t("muteVideo")}>
                {isMuted ? <Wind size={16} /> : <Droplets size={16} />} 
                <span className="ml-1 lg:ml-2 text-[8px] lg:text-[10px] font-black uppercase tracking-widest hidden sm:inline">{isMuted ? t('muted') : t('unmuted')}</span>
              </button>
            </div>
          )}
          <button onClick={() => { setStickers([]); setTextObjects([]); setMediaPreview(null); setMediaFile(null); setCroppedPreview(null); clearCanvas(); setBgColor('#1e1e2e'); setIsMuted(false); }} className="px-3 lg:px-6 py-2 lg:py-3 text-[8px] lg:text-[10px] font-black uppercase tracking-widest text-zinc-500 hover:text-white border border-white/5 rounded-xl hover:bg-white/5 transition-all whitespace-nowrap">{t('reset')}</button>
          <button onClick={handlePublish} disabled={isUploading} className="px-4 lg:px-8 py-2 lg:py-3 bg-primary text-on-primary rounded-xl font-black text-[10px] lg:text-xs uppercase tracking-widest hover:scale-105 active:scale-95 disabled:opacity-50 transition-all shadow-xl shadow-primary/20 whitespace-nowrap">
            {isUploading ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : t('publishStory')}
          </button>
        </div>
      </header>

      <main className="flex-1 flex flex-col lg:flex-row overflow-hidden min-h-0">
        <section className="flex-1 flex items-center justify-center p-4 lg:p-12 relative bg-[#070707] min-h-0">
          <div ref={stageRef} className="relative w-auto h-full max-h-[500px] sm:max-h-[600px] lg:max-h-none aspect-[9/16] bg-black rounded-[2.5rem] lg:rounded-[3.5rem] border-[8px] lg:border-[12px] border-[#161616] overflow-hidden shadow-[0_50px_100px_-30px_rgba(0,0,0,0.9)] ring-1 ring-white/5">
            <div className="absolute inset-0 transition-colors duration-700" style={{ backgroundColor: bgColor }}>
                {(croppedPreview || mediaPreview) && (
                  <div className="absolute inset-0" style={{ filter: getFilterCss() }}>
                    {tool === 'crop' && mediaPreview && !mediaFile?.type.startsWith('video/') ? (
                      <Cropper
                        image={mediaPreview}
                        crop={crop}
                        rotation={rotation}
                        zoom={zoom}
                        aspect={9 / 16}
                        onCropChange={setCrop}
                        onRotationChange={setRotation}
                        onCropComplete={(_, croppedPixels) => setCroppedAreaPixels(croppedPixels)}
                        onZoomChange={setZoom}
                      />
                    ) : (
                      <>
                        {mediaFile?.type.startsWith('video/') ? (
                          <div className="w-full h-full flex items-center justify-center relative" style={{ background: bgColor }}>
                             <video 
                                 ref={editorVideoRef}
                                 src={mediaPreview!} 
                                 className="w-full h-full object-contain" 
                                 autoPlay={false} 
                                 muted={isMuted} 
                                 onTimeUpdate={() => {
                                      const cur = editorVideoRef.current?.currentTime || 0;
                                      setCurrentPlayTime(cur);
                                      if (editorVideoRef.current) {
                                          if (cur >= endTime) {
                                              editorVideoRef.current.pause();
                                              editorVideoRef.current.currentTime = startTime;
                                              setPaused(true);
                                              setCurrentPlayTime(startTime);
                                          } else if (cur < startTime - 0.1) {
                                              editorVideoRef.current.currentTime = startTime;
                                              setCurrentPlayTime(startTime);
                                          }
                                      }
                                  }}
                                 onPlay={() => setPaused(false)}
                                 onPause={() => setPaused(true)}
                             />
                             
                             <div 
                                onClick={() => {
                                      const v = editorVideoRef.current;
                                      if (v) {
                                          if (v.currentTime < startTime || v.currentTime > endTime) {
                                              v.currentTime = startTime;
                                          }
                                          if (v.paused) {
                                              v.play().catch(() => {});
                                          } else {
                                              v.pause();
                                          }
                                      }
                                  }}
                                className="absolute inset-0 z-20 flex items-center justify-center cursor-pointer group"
                             >
                                 {paused && (
                                    <motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="w-16 lg:w-20 h-16 lg:h-20 rounded-full bg-black/40 backdrop-blur-xl flex items-center justify-center border border-white/20 group-hover:bg-primary/20 group-hover:border-primary/40 transition-all">
                                        <span className="material-symbols-outlined text-3xl lg:text-4xl text-white">play_arrow</span>
                                    </motion.div>
                                 )}
                             </div>
    
                             <div className="absolute bottom-6 lg:bottom-10 left-0 right-0 z-30 px-6 lg:px-10 pointer-events-none">
                                 <div className="flex items-center gap-3 lg:gap-4 pointer-events-auto">
                                     <button 
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            const v = editorVideoRef.current;
                                            if (v) {
                                                v.pause();
                                                v.currentTime = startTime;
                                                setPaused(true);
                                                setCurrentPlayTime(startTime);
                                            }
                                        }}
                                        className="w-8 lg:w-10 h-8 lg:h-10 rounded-xl bg-black/60 backdrop-blur-md flex items-center justify-center text-white border border-white/10 hover:bg-red-500/20 hover:border-red-500/40 transition-all"
                                        title={t('stop')}
                                     >
                                         <span className="material-symbols-outlined text-sm lg:text-base">stop</span>
                                     </button>
                                     <div className="flex-1 h-1 bg-white/10 rounded-full overflow-hidden backdrop-blur-md border border-white/5 font-mono">
                                         <motion.div 
                                            className="h-full bg-primary"
                                            animate={{ width: `${(( (editorVideoRef.current?.currentTime || 0) - startTime) / (endTime - startTime)) * 100}%` }}
                                            transition={{ duration: 0.1, ease: 'linear' }}
                                         />
                                     </div>
                                 </div>
                             </div>
                          </div>
                        ) : (
                          <img src={croppedPreview || mediaPreview!} className="w-full h-full object-cover" alt="base" />
                        )}
                      </>
                    )}
                    <button onClick={e => { e.stopPropagation(); removeMedia(); }} className="absolute top-4 lg:top-8 right-4 lg:right-8 w-10 lg:w-12 h-10 lg:h-12 bg-black/60 text-white rounded-xl lg:rounded-2xl hover:bg-red-500 transition-all z-40 backdrop-blur-md flex items-center justify-center border border-white/10 group"><Trash2 size={18} className="group-hover:scale-110 transition-transform" /></button>
                  </div>
                )}
               
               <canvas ref={canvasRef} width={TARGET_W} height={TARGET_H} className={`absolute inset-0 z-10 w-full h-full ${tool === 'brush' ? 'cursor-crosshair' : 'pointer-events-none'}`} onMouseDown={e => { isDrawingRef.current = true; const canvas = canvasRef.current; if (!canvas) return; const ctx = canvas.getContext('2d'); if (!ctx) return; const rect = canvas.getBoundingClientRect(); const x = (e.clientX - rect.left) * (canvas.width / rect.width); const y = (e.clientY - rect.top) * (canvas.height / rect.height); ctx.beginPath(); ctx.moveTo(x, y); ctx.strokeStyle = brushColor; ctx.lineWidth = brushSize * SCALE_FACTOR; ctx.lineCap = 'round'; }} onMouseMove={e => { if (!isDrawingRef.current) return; const canvas = canvasRef.current; if (!canvas) return; const ctx = canvas.getContext('2d'); if (!ctx) return; const rect = canvas.getBoundingClientRect(); const x = (e.clientX - rect.left) * (canvas.width / rect.width); const y = (e.clientY - rect.top) * (canvas.height / rect.height); ctx.lineTo(x, y); ctx.stroke(); }} onMouseUp={() => isDrawingRef.current = false} />

               <AnimatePresence>
                 {stickers.map(s => (
                   <motion.div key={s.id} drag dragConstraints={stageRef} dragMomentum={false} initial={{ scale: 0 }} animate={{ scale: 1 }} exit={{ scale: 0 }} className={`absolute z-20 cursor-grab active:cursor-grabbing p-2 lg:p-4 ${selectedStickerId === s.id ? 'ring-2 ring-primary bg-white/5 rounded-[1.5rem] lg:rounded-[2rem] backdrop-blur-sm' : ''}`} style={{ left: `${s.x}%`, top: `${s.y}%`, fontSize: `${s.scale * 30}px` }} onClick={() => {setSelectedStickerId(s.id); setSelectedTextId(null); setTool('stickers');}}>
                     {s.emoji}
                     {selectedStickerId === s.id && <button onClick={(e) => { e.stopPropagation(); setStickers(prev => prev.filter(st => st.id !== s.id)); setSelectedStickerId(null); }} className="absolute -top-2 -right-2 w-6 lg:w-8 h-6 lg:h-8 bg-red-500 rounded-full flex items-center justify-center text-white shadow-xl border-2 border-[#161616]"><X size={12}/></button>}
                   </motion.div>
                 ))}

                 {textObjects.map(tobj => (
                   <motion.div key={tobj.id} drag dragConstraints={stageRef} dragMomentum={false} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className={`absolute z-30 cursor-grab active:cursor-grabbing p-3 lg:p-4 group ${selectedTextId === tobj.id ? 'ring-2 ring-primary bg-white/5 rounded-[1.5rem] lg:rounded-[2rem] backdrop-blur-md' : ''}`} style={{ left: `${tobj.x}%`, top: `${tobj.y}%`, color: tobj.color, fontFamily: tobj.font, fontSize: `${tobj.size / 1.5}px`, transform: `scale(${tobj.scale})` }} onClick={() => {setSelectedTextId(tobj.id); setSelectedStickerId(null); setTool('text');}}>
                     {tobj.text}
                     {selectedTextId === tobj.id && <button onClick={(e) => { e.stopPropagation(); setTextObjects(prev => prev.filter(to => to.id !== tobj.id)); setSelectedTextId(null); }} className="absolute -top-2 -right-2 w-6 lg:w-8 h-6 lg:h-8 bg-red-500 rounded-full flex items-center justify-center text-white shadow-xl border-2 border-[#161616]"><X size={12}/></button>}
                   </motion.div>
                 ))}
               </AnimatePresence>
               
               {!mediaPreview && textObjects.length === 0 && stickers.length === 0 && (
                   <button onClick={() => fileInputRef.current?.click()} className="absolute inset-0 flex flex-col items-center justify-center gap-4 lg:gap-6 text-zinc-800 hover:text-white transition-all group">
                     <div className="w-16 lg:w-20 h-16 lg:h-20 rounded-full border-2 border-dashed border-zinc-800 flex items-center justify-center group-hover:border-primary group-hover:bg-primary/5 group-hover:scale-110 transition-all duration-500">
                        <Camera size={32} className="group-hover:rotate-12 transition-transform" />
                    </div>
                    <span className="text-[8px] lg:text-[9px] font-black uppercase tracking-[0.3em] lg:tracking-[0.4em]">{t('startCreation')}</span>
                  </button>
               )}
            </div>
          </div>
          <input ref={fileInputRef} type="file" accept="image/*,video/*" className="hidden" onChange={handleMediaSelect} />
        </section>

        <aside className="lg:w-[360px] w-full bg-[#0a0a0a] border-l border-white/5 flex flex-col overflow-y-auto max-h-[40vh] lg:max-h-none">
          <div className="p-4 lg:p-8 space-y-6 lg:space-y-10 pb-20 lg:pb-24">
            <div className="grid grid-cols-5 lg:grid-cols-2 gap-2 lg:gap-3">
              {[
                { id: 'text', icon: <Type size={18} />, label: t('textTool'), action: addText },
                { id: 'crop', icon: <Scissors size={18} />, label: t('cropTool'), active: tool === 'crop' },
                { id: 'stickers', icon: <Smile size={18} />, label: t('stickersTool'), active: tool === 'stickers' },
                { id: 'brush', icon: <Brush size={18} />, label: t('brushTool'), active: tool === 'brush' },
                { id: 'filters', icon: <SlidersHorizontal size={18} />, label: t('filtersTool'), active: tool === 'filters' },
              ].map(item => (
                <button key={item.id} onClick={() => { if(item.id === 'text') { if(item.action) item.action(); setTool('text'); } else { setTool(item.id as any); } }} className={`flex flex-col items-center lg:items-center justify-center h-20 lg:h-24 p-2 lg:p-4 rounded-xl lg:rounded-3xl border transition-all duration-500 ${tool === item.id ? 'bg-primary/10 border-primary/40 text-white shadow-[0_15px_40px_-10px_rgba(var(--primary-rgb),0.3)]' : 'bg-[#121212] border-white/5 text-zinc-500 hover:text-white hover:border-white/10'}`}>
                  <div className={tool === item.id ? 'text-primary' : 'text-zinc-700'}>{item.icon}</div>
                  <span className="text-[7px] lg:text-[10px] font-black uppercase tracking-widest mt-2">{item.label}</span>
                </button>
              ))}
            </div>

            <AnimatePresence mode="wait">
              {tool === 'crop' && (
                <motion.div key="crop-tool" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }} className="p-6 lg:p-8 rounded-3xl lg:rounded-[2.5rem] bg-[#121212] border border-white/5 space-y-6 lg:space-y-8 shadow-2xl">
                   <h4 className="text-[9px] lg:text-[10px] font-black uppercase tracking-widest text-primary">{t('cropTool')}</h4>
                   <div className="space-y-4">
                      <div className="flex justify-between text-[9px] lg:text-[10px] font-bold text-zinc-600 uppercase tracking-widest"><span>{t('zoom')}</span><span className="text-white">{zoom.toFixed(1)}x</span></div>
                      <input type="range" min="1" max="3" step="0.1" value={zoom} onChange={e => setZoom(parseFloat(e.target.value))} className="w-full accent-primary h-1 bg-white/5 rounded-full" />
                   </div>
                   <div className="space-y-4">
                      <div className="flex justify-between text-[9px] lg:text-[10px] font-bold text-zinc-600 uppercase tracking-widest"><span>{t('rotation')}</span><span className="text-white">{rotation}°</span></div>
                      <input type="range" min="0" max="360" value={rotation} onChange={e => setRotation(parseInt(e.target.value))} className="w-full accent-primary h-1 bg-white/5 rounded-full" />
                   </div>
                   <button onClick={handleCropDone} className="w-full py-4 lg:py-5 text-[9px] lg:text-[10px] font-black uppercase tracking-[0.1em] lg:tracking-[0.2em] bg-primary text-white rounded-2xl lg:rounded-3xl hover:scale-105 active:scale-95 transition-all shadow-xl shadow-primary/20">{t('apply')}</button>
                </motion.div>
              )}

              {tool === 'text' && selectedTextId && (
                <motion.div key="text-tool" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }} className="space-y-4 lg:space-y-8 bg-[#121212] p-6 lg:p-8 rounded-3xl lg:rounded-[2.5rem] border border-white/5 shadow-2xl">
                  <div className="flex flex-col gap-2 lg:gap-4">
                    <span className="text-[9px] lg:text-[10px] font-black uppercase text-primary tracking-widest">{t('textContent')}</span>
                    <input value={textObjects.find(tx => tx.id === selectedTextId)?.text} onChange={e => setTextObjects(prev => prev.map(tx => tx.id === selectedTextId ? { ...tx, text: e.target.value } : tx))} className="bg-transparent border-b border-white/10 w-full py-2 text-xl lg:text-2xl font-black outline-none italic" autoFocus />
                  </div>
                  <div className="space-y-3 lg:space-y-4">
                    <span className="text-[9px] lg:text-[10px] font-black uppercase text-zinc-600 tracking-widest">{t('typography')}</span>
                    <div className="flex flex-wrap gap-1.5 lg:gap-2">
                       {FONTS.map(f => (
                         <button key={f.id} onClick={() => setTextObjects(prev => prev.map(tx => tx.id === selectedTextId ? { ...tx, font: f.family } : tx))} className={`px-4 lg:px-5 py-1.5 lg:py-2 rounded-xl lg:rounded-2xl text-[8px] lg:text-[9px] font-black uppercase transition-all ${textObjects.find(tx => tx.id === selectedTextId)?.font === f.family ? 'bg-primary text-white shadow-lg' : 'bg-white/5 text-zinc-500 hover:text-white'}`} style={{ fontFamily: f.family }}>{f.name}</button>
                       ))}
                    </div>
                  </div>
                  <div className="space-y-3 lg:space-y-4">
                    <div className="flex justify-between text-[9px] lg:text-[10px] font-black uppercase text-zinc-600"><span>{t('textSize')}</span><span className="text-white">{textObjects.find(tx => tx.id === selectedTextId)?.size}px</span></div>
                    <input type="range" min="12" max="150" value={textObjects.find(tx => tx.id === selectedTextId)?.size} onChange={e => setTextObjects(prev => prev.map(tx => tx.id === selectedTextId ? { ...tx, size: parseInt(e.target.value) } : tx))} className="w-full accent-primary h-1 bg-white/5 rounded-full" />
                  </div>
                  <div className="flex items-center justify-between pt-4 lg:pt-6 border-t border-white/5">
                    <span className="text-[9px] lg:text-[10px] font-black uppercase text-zinc-600">{t('textColor')}</span>
                    <div className="w-10 lg:w-12 h-10 lg:h-12 rounded-full border-2 border-white/10 relative shadow-inner" style={{ backgroundColor: textObjects.find(tx => tx.id === selectedTextId)?.color }}>
                        <input type="color" value={textObjects.find(tx => tx.id === selectedTextId)?.color} onChange={e => setTextObjects(prev => prev.map(tx => tx.id === selectedTextId ? { ...tx, color: e.target.value } : tx))} className="absolute inset-0 opacity-0 w-full h-full cursor-pointer" />
                        <Pipette size={16} className="absolute inset-0 m-auto mix-blend-difference" />
                    </div>
                  </div>
                </motion.div>
              )}

              {tool === 'brush' && (
                <motion.div key="brush-tool" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }} className="p-6 lg:p-8 rounded-3xl lg:rounded-[2.5rem] bg-[#121212] border border-white/5 space-y-6 lg:space-y-10 text-center shadow-2xl">
                  <div className="w-16 lg:w-24 h-16 lg:h-24 rounded-full mx-auto border-4 border-white/10 relative shadow-inner cursor-pointer group" style={{ backgroundColor: brushColor }}>
                    <input type="color" value={brushColor} onChange={e => setBrushColor(e.target.value)} className="absolute inset-0 opacity-0 w-full h-full cursor-pointer" />
                    <Pipette size={24} className="absolute inset-0 m-auto mix-blend-difference group-hover:scale-125 transition-transform" />
                  </div>
                  <div className="space-y-4">
                    <div className="flex justify-between text-[9px] lg:text-[10px] font-bold text-zinc-600 uppercase tracking-widest"><span>{t('brushThickness')}</span><span className="text-white">{brushSize}px</span></div>
                    <input type="range" min="1" max="100" value={brushSize} onChange={e => setBrushSize(parseInt(e.target.value))} className="w-full accent-primary h-1 bg-white/5 rounded-full" />
                  </div>
                  <button onClick={clearCanvas} className="w-full py-4 lg:py-5 text-[9px] lg:text-[10px] font-black uppercase tracking-[0.1em] lg:tracking-[0.2em] text-red-500 bg-red-500/10 rounded-2xl lg:rounded-3xl hover:bg-red-500 hover:text-white transition-all border border-red-500/20">{t('clearCanvas')}</button>
                </motion.div>
              )}

              {tool === 'stickers' && (
                <motion.div key="sticker-tool" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }} className="bg-[#121212] rounded-3xl lg:rounded-[2.5rem] border border-white/5 overflow-hidden shadow-2xl">
                   <Picker data={data} onEmojiSelect={addSticker} theme="dark" set="native" locale="ru" previewPosition="none" skinTonePosition="none" />
                </motion.div>
              )}

              {tool === 'filters' && (
                <motion.div key="filters-tool" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }} className="p-6 lg:p-8 rounded-3xl lg:rounded-[2.5rem] bg-[#121212] border border-white/5 space-y-6 lg:space-y-8 shadow-2xl">
                   <h4 className="text-[9px] lg:text-[10px] font-black uppercase tracking-widest text-primary">{t('correctionMaster')}</h4>
                   <div className="space-y-4 lg:space-y-6">
                      {[
                        { id: 'brightness', icon: <Sun size={14}/>, label: t('brightness'), min: 40, max: 160 },
                        { id: 'contrast', icon: <Contrast size={14}/>, label: t('contrast'), min: 40, max: 160 },
                        { id: 'saturate', icon: <Droplets size={14}/>, label: t('saturation'), min: 0, max: 250 },
                        { id: 'sepia', icon: <Palette size={14}/>, label: t('sepia'), min: 0, max: 100 },
                      ].map(adj => (
                        <div key={adj.id} className="space-y-2">
                          <div className="flex items-center justify-between text-[8px] lg:text-[10px] font-bold text-zinc-700 uppercase">
                            <div className="flex items-center gap-2">{adj.icon} {adj.label}</div>
                            <span className="text-white">{adjustments[adj.id as keyof typeof adjustments]}%</span>
                          </div>
                          <input type="range" min={adj.min} max={adj.max} value={adjustments[adj.id as keyof typeof adjustments]} onChange={e => setAdjustments(prev => ({ ...prev, [adj.id]: parseInt(e.target.value) }))} className="w-full accent-primary h-1 bg-white/5 rounded-full" />
                        </div>
                      ))}
                   </div>
                </motion.div>
              )}

              {!mediaPreview && tool === 'none' && (
                <motion.div key="bg-tool" initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="p-6 lg:p-10 rounded-3xl lg:rounded-[2.5rem] bg-[#121212] flex flex-col items-center gap-6 lg:gap-8 border border-white/5 shadow-2xl">
                  <div className="flex flex-col items-center gap-2">
                    <Palette size={20} className="text-primary" />
                    <span className="text-[9px] lg:text-[10px] font-black uppercase text-zinc-500 tracking-widest">{t('bgColor')}</span>
                  </div>
                  <div className="w-20 lg:w-28 h-20 lg:h-28 rounded-full border-[6px] border-white/5 relative shadow-inner transition-transform hover:scale-105 active:scale-95 cursor-pointer" style={{ backgroundColor: bgColor }}>
                    <input type="color" value={bgColor} onChange={e => setBgColor(e.target.value)} className="absolute inset-0 opacity-0 w-full h-full cursor-pointer" />
                    <Pipette size={24} className="absolute inset-0 m-auto mix-blend-difference" />
                  </div>
                  <span className="text-[8px] lg:text-[9px] font-bold text-zinc-700 uppercase">{t('clickToChooseColor')}</span>
                </motion.div>
              )}
            </AnimatePresence>
            <div className="pt-6 lg:pt-10 border-t border-white/5" />
          </div>
        </aside>
      </main>

    <AnimatePresence>
      {tool === 'trim' && mediaPreview && (
        <motion.div 
          initial={{ opacity: 0, y: '100%' }} 
          animate={{ opacity: 1, y: 0 }} 
          exit={{ opacity: 0, y: '100%' }} 
          transition={{ type: 'spring', damping: 25, stiffness: 200 }}
          className="fixed inset-0 z-[300] bg-black flex flex-col items-center overflow-y-auto"
        >
          {/* Header */}
          <div className="w-full min-h-[80px] px-8 flex items-center justify-between border-b border-white/5 bg-[#0a0a0a] sticky top-0 z-50">
              <button onClick={() => {
                  setTool('none');
                  const v = trimVideoRef.current;
                  const ev = editorVideoRef.current;
                  if (v) v.pause();
                  if (ev) {
                      ev.pause();
                      ev.currentTime = startTime;
                      setPaused(true);
                      setCurrentPlayTime(startTime);
                  }
              }} className="w-12 h-12 rounded-full hover:bg-white/5 flex items-center justify-center text-zinc-400 transition-colors">
                  <ChevronLeft size={28} />
              </button>
              <h2 className="text-sm font-black uppercase tracking-[0.3em] text-zinc-200">{t('cropVideo')}</h2>
              <button 
                onClick={() => {
                   setTool('none');
                   const v = trimVideoRef.current;
                   const ev = editorVideoRef.current;
                   if (v) v.pause();
                   if (ev) {
                    ev.pause();
                    ev.currentTime = startTime;
                    setPaused(true);
                    setCurrentPlayTime(startTime);
                   }
                }}
                className="px-6 py-2 rounded-xl bg-primary text-on-primary text-[10px] font-black uppercase tracking-widest hover:scale-105 active:scale-95 transition-all"
              >
                  {t('done')}
              </button>
          </div>

          <div className="flex-1 w-full max-w-4xl flex flex-col items-center p-6 md:p-12 gap-10">
              {/* Floating Timer - Moved Above */}
              <div className="bg-black/40 backdrop-blur-3xl px-6 py-3 rounded-2xl border border-white/5 shadow-2xl mb-2">
                  <span className="text-sm font-mono font-black tracking-widest text-primary italic">
                      {new Date(currentPlayTime * 1000).toISOString().substr(14, 5)} / {new Date(videoDuration * 1000).toISOString().substr(14, 5)}
                  </span>
              </div>

              {/* Video Preview */}
              <div className="relative w-full max-w-[320px] aspect-[9/16] bg-[#070707] rounded-[3rem] overflow-hidden shadow-[0_40px_80px_rgba(0,0,0,0.8)] border-[6px] border-white/5 group">
                  <video 
                      ref={trimVideoRef}
                      src={mediaPreview!} 
                      className="w-full h-full object-contain" 
                      muted={isMuted} 
                      onTimeUpdate={() => {
                        const cur = trimVideoRef.current?.currentTime || 0;
                        setCurrentPlayTime(cur);
                        if (trimVideoRef.current) {
                            if (cur >= endTime) {
                                trimVideoRef.current.pause();
                                trimVideoRef.current.currentTime = startTime;
                                setPaused(true);
                                setCurrentPlayTime(startTime);
                            } else if (cur < startTime - 0.1) {
                                trimVideoRef.current.currentTime = startTime;
                                setCurrentPlayTime(startTime);
                            }
                        }
                      }}
                       onPlay={() => setPaused(false)}
                       onPause={() => setPaused(true)}
                  />
                  {/* Play/Pause Overlay on tap */}
                  <div onClick={() => { 
                       const v = trimVideoRef.current;
                       if(v) { 
                          if (v.currentTime < startTime || v.currentTime > endTime) {
                              v.currentTime = startTime;
                          }
                          if(v.paused) {
                              v.play().catch(() => {});
                          } else {
                              v.pause();
                          }
                      } 
                  }} className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/20 cursor-pointer">
                       <div className="w-20 h-20 rounded-full bg-white/10 backdrop-blur-md flex items-center justify-center border border-white/20">
                           <span className="material-symbols-outlined text-4xl">{paused ? 'play_arrow' : 'pause'}</span>
                       </div>
                  </div>
              </div>

              <div className="w-full space-y-4">
                  <div className="flex items-center justify-between px-2">
                      <div className="flex items-center gap-2">
                          <div className="w-2 h-2 rounded-full bg-primary animate-pulse" />
                          <span className="text-[10px] font-black uppercase text-zinc-500 tracking-widest">{t('zoomHint')} ({zoom.toFixed(1)}x)</span>
                      </div>
                      <div className="flex items-center gap-4">
                          <span className="text-[9px] font-black uppercase text-zinc-600 tracking-widest">{new Date(0 * 1000).toISOString().substr(14, 5)}</span>
                          <div className="px-4 py-1.5 rounded-lg bg-primary/10 border border-primary/20">
                              <span className="text-[10px] font-black italic text-primary uppercase">{(endTime - startTime).toFixed(1)} {t('secSelected')}</span>
                          </div>
                          <span className="text-[9px] font-black uppercase text-zinc-600 tracking-widest">{new Date(videoDuration * 1000).toISOString().substr(14, 5)}</span>
                      </div>
                  </div>

                  <div className="w-full space-y-3">
                      {/* Overview Track (Mini-map) */}
                      <div className="relative h-4 bg-white/5 rounded-full overflow-hidden border border-white/10 group/mini">
                          <div className="absolute inset-0 flex opacity-20 pointer-events-none">
                              {thumbnails.map((th, i) => (
                                  <img key={i} src={th} className="flex-1 h-full object-cover grayscale" alt="mini" />
                              ))}
                          </div>
                          {/* Selection UI on Mini-map */}
                          <div 
                              className="absolute top-0 bottom-0 bg-primary/30 border-x border-primary/50 cursor-grab active:cursor-grabbing"
                              onMouseDown={(e) => {
                                  e.stopPropagation();
                                  const rect = e.currentTarget.parentElement?.getBoundingClientRect();
                                  if (!rect) return;
                                  const x = (e.clientX - rect.left) / rect.width;
                                  const tval = x * videoDuration;
                                  (timelineRef.current as any)._dragging = 'range';
                                  (timelineRef.current as any)._offsetTime = tval - startTime;
                              }}
                              style={{ 
                                  left: `${(startTime / videoDuration) * 100}%`,
                                  width: `${((endTime - startTime) / videoDuration) * 100}%`
                              }}
                          />
                          {/* Mini Playhead */}
                          <div 
                              className="absolute top-0 bottom-0 w-0.5 bg-white z-10"
                              style={{ left: `${(currentPlayTime / videoDuration) * 100}%` }}
                          />
                          {/* Interaction Layer */}
                          <div 
                            className="absolute inset-0 cursor-pointer"
                            onClick={(e) => {
                                const rect = e.currentTarget.getBoundingClientRect();
                                const x = (e.clientX - rect.left) / rect.width;
                                const tval = x * videoDuration;
                                if (trimVideoRef.current) trimVideoRef.current.currentTime = tval;
                                setCurrentPlayTime(tval);
                            }}
                          />
                      </div>

                      {/* Time Ruler Placeholder */}
                      <div className="flex justify-between px-1 text-[8px] font-black font-mono text-zinc-600 uppercase tracking-tighter">
                          {[0, 0.25, 0.5, 0.75, 1].map(p => (
                             <span key={p}>{new Date(videoDuration * p * 1000).toISOString().substr(14, 5)}</span>
                          ))}
                      </div>

                      {/* Precision Track (Zoomable) */}
                      <div 
                        ref={timelineRef}
                        className="relative w-full overflow-x-auto overflow-y-hidden no-scrollbar bg-[#121212] rounded-[1.5rem] border border-white/5 h-24 group/timeline"
                      >
                        <div 
                            className="relative h-full"
                            style={{ width: `${zoom * 100}%`, minWidth: '100%' }}
                            onMouseDown={(e) => {
                                const rect = e.currentTarget.getBoundingClientRect();
                                const x = (e.clientX - rect.left) / rect.width;
                                const tval = x * videoDuration;
                                
                                const startX = (startTime / videoDuration) * rect.width;
                                const endX = (endTime / videoDuration) * rect.width;
                                const mouseX = e.clientX - rect.left;

                                if (Math.abs(mouseX - startX) < 20) {
                                    (e.currentTarget as any)._dragging = 'start';
                                } else if (Math.abs(mouseX - endX) < 20) {
                                    (e.currentTarget as any)._dragging = 'end';
                                } else if (mouseX > startX && mouseX < endX) {
                                    (e.currentTarget as any)._dragging = 'range';
                                    (e.currentTarget as any)._offsetTime = tval - startTime;
                                } else {
                                    (e.currentTarget as any)._dragging = 'scrub';
                                    if (trimVideoRef.current) {
                                        trimVideoRef.current.currentTime = tval;
                                        setCurrentPlayTime(tval);
                                    }
                                }
                            }}
                            onMouseMove={(e) => {
                                const dragging = (e.currentTarget as any)._dragging;
                                if (!dragging) return;

                                const rect = e.currentTarget.getBoundingClientRect();
                                const x = (e.clientX - rect.left) / rect.width;
                                const tval = Math.max(0, Math.min(videoDuration, x * videoDuration));

                                if (dragging === 'start') {
                                    if (tval < endTime - 0.2) {
                                        setStartTime(tval);
                                        if (trimVideoRef.current) {
                                            trimVideoRef.current.currentTime = tval;
                                            setCurrentPlayTime(tval);
                                        }
                                    }
                                } else if (dragging === 'end') {
                                    if (tval > startTime + 0.2) {
                                        setEndTime(tval);
                                        if (trimVideoRef.current) {
                                            trimVideoRef.current.currentTime = tval;
                                            setCurrentPlayTime(tval);
                                        }
                                    }
                                } else if (dragging === 'range') {
                                    const offset = (e.currentTarget as any)._offsetTime;
                                    const dr = endTime - startTime;
                                    let newStart = tval - offset;
                                    if (newStart < 0) newStart = 0;
                                    if (newStart + dr > videoDuration) newStart = videoDuration - dr;
                                    setStartTime(newStart);
                                    setEndTime(newStart + dr);
                                    if (trimVideoRef.current) {
                                        trimVideoRef.current.currentTime = newStart;
                                        setCurrentPlayTime(newStart);
                                    }
                                } else if (dragging === 'scrub') {
                                    if (trimVideoRef.current) {
                                        trimVideoRef.current.currentTime = tval;
                                        setCurrentPlayTime(tval);
                                    }
                                }
                            }}
                            onMouseUp={(e) => (e.currentTarget as any)._dragging = null}
                            onMouseLeave={(e) => (e.currentTarget as any)._dragging = null}
                        >
                            {/* Thumbnails Track */}
                            <div className="absolute inset-0 flex">
                                {thumbnails.map((th, i) => (
                                    <img key={i} src={th} className="flex-1 h-full object-cover opacity-20 filter grayscale" alt="frame" />
                                ))}
                            </div>

                            {/* Selection Window */}
                            <div 
                                className="absolute top-0 bottom-0 bg-primary/20 border-x-4 border-primary z-10 shadow-[0_0_40px_rgba(var(--primary-rgb),0.3)]"
                                style={{ 
                                    left: `${(startTime / videoDuration) * 100}%`,
                                    right: `${100 - (endTime / videoDuration) * 100}%`
                                }}
                            >
                                <div className="absolute -left-3 top-1/2 -translate-y-1/2 w-6 h-12 bg-primary rounded-full flex flex-col items-center justify-center gap-1 shadow-2xl cursor-ew-resize">
                                    <div className="w-0.5 h-4 bg-white/40 rounded-full" />
                                </div>
                                <div className="absolute -right-3 top-1/2 -translate-y-1/2 w-6 h-12 bg-primary rounded-full flex flex-col items-center justify-center gap-1 shadow-2xl cursor-ew-resize">
                                    <div className="w-0.5 h-4 bg-white/40 rounded-full" />
                                </div>
                            </div>

                            {/* Playback Cursor */}
                            <div 
                                className="absolute top-0 bottom-0 w-1 bg-white shadow-[0_0_20px_white] z-20 pointer-events-none"
                                style={{ left: `${(currentPlayTime / videoDuration) * 100}%` }}
                            />
                        </div>
                      </div>
                  </div>

                  {/* Main Player Controls */}
                  <div className="flex items-center justify-center pt-8">
                      <button 
                        onClick={() => {
                            const v = trimVideoRef.current;
                            if (v) {
                                if (v.currentTime < startTime || v.currentTime > endTime) v.currentTime = startTime;
                                if (v.paused) v.play().catch(() => {}); else v.pause();
                                setPaused(v.paused);
                            }
                        }}
                        className="w-24 h-24 rounded-[2rem] bg-primary flex items-center justify-center text-on-primary shadow-[0_0_50px_rgba(var(--primary-rgb),0.5)] hover:scale-105 active:scale-95 transition-all"
                      >
                          <span className="material-symbols-outlined text-5xl text-white">{paused ? 'play_arrow' : 'pause'}</span>
                      </button>
                  </div>

                  <div className="grid grid-cols-2 gap-8 max-w-2xl mx-auto w-full">
                       <div className="bg-[#121212] p-8 rounded-[2.5rem] border border-white/5 flex flex-col gap-2 shadow-xl">
                           <span className="text-[11px] font-black uppercase text-zinc-600 tracking-[0.2em]">{lang === 'ru' ? 'Начало' : 'Start'}</span>
                           <div className="flex items-center justify-between">
                               <span className="text-3xl font-black italic tracking-tighter text-white font-mono">
                                  {new Date(startTime * 1000).toISOString().substr(14, 5)}<span className="text-primary text-xl">.{(startTime % 1).toFixed(1).substr(2)}</span>
                               </span>
                               <ChevronLeft size={24} className="text-zinc-800 opacity-50" />
                           </div>
                       </div>
                       <div className="bg-[#121212] p-8 rounded-[2.5rem] border border-white/5 flex flex-col gap-2 shadow-xl">
                           <span className="text-[11px] font-black uppercase text-zinc-600 tracking-[0.2em]">{lang === 'ru' ? 'Конец' : 'End'}</span>
                           <div className="flex items-center justify-between">
                               <span className="text-3xl font-black italic tracking-tighter text-white font-mono">
                                  {new Date(endTime * 1000).toISOString().substr(14, 5)}<span className="text-primary text-xl">.{(endTime % 1).toFixed(1).substr(2)}</span>
                               </span>
                               <ChevronRight size={24} className="text-zinc-800 opacity-50" />
                           </div>
                       </div>
                  </div>

                  <div className="pt-8 flex justify-center pb-12">
                      <button 
                        onClick={() => {
                            if (videoDuration > 120 && (endTime - startTime) > 120) return;
                            setTool('none');
                            if (trimVideoRef.current) trimVideoRef.current.pause();
                            if (editorVideoRef.current) {
                                editorVideoRef.current.pause();
                                editorVideoRef.current.currentTime = startTime;
                                setPaused(true);
                                setCurrentPlayTime(startTime);
                            }
                        }}
                        disabled={videoDuration > 120 && (endTime - startTime) > 120}
                        className="px-24 py-7 bg-white text-black rounded-full font-black uppercase tracking-[0.2em] text-sm hover:scale-105 active:scale-95 disabled:opacity-30 transition-all shadow-2xl"
                      >
                          {videoDuration > 120 && (endTime - startTime) > 120 ? (lang === 'ru' ? 'Слишком длинное' : 'Too Long') : t('apply')}
                      </button>
                  </div>
              </div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
      </motion.div>
    </motion.div>
  );
}
