"use client";
import { useState, useRef, useEffect } from "react";
import { Maximize, Lock, Crown, Play, Pause, Volume2, VolumeX, Settings, Loader2, Lightbulb, CheckCircle, AlertCircle, Clock, Share2, Camera } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Script from "next/script";
import Hls from "hls.js";
import { toast } from "@/components/ui/Toaster";

export function VideoPlayer({ 
  mediaUrl, 
  isLocked, 
  nextVideoId 
}: { 
  mediaUrl: string; 
  isLocked: boolean; 
  nextVideoId?: string;
}) {


  // ── Embed externe (Pornhub iframe) ──────────────────────────────────────────
  const isEmbed = mediaUrl && (
    mediaUrl.includes("pornhub.com/embed") ||
    mediaUrl.includes("xvideos.com/embedframe") ||
    mediaUrl.includes("xnxx.com/embedframe") ||
    mediaUrl.includes("xhamster.com/xembed")
  );



  if (isEmbed && !isLocked) {
    return (
      <div className="relative w-full bg-black rounded-2xl overflow-hidden shadow-2xl border border-white/10 select-none" style={{ paddingTop: "56.25%" }}>
        <iframe
          src={(() => {
            try {
              const u = new URL(mediaUrl);
              if (u.protocol === 'http:') u.protocol = 'https:';
              u.searchParams.set("rel", "0");       // désactive les suggestions
              return u.toString();
            } catch { return mediaUrl.replace('http://', 'https://'); }
          })()}
          className="absolute rounded-2xl"
          style={{ top: "-48px", left: "0", width: "100%", height: "calc(100% + 48px)" }}
          frameBorder="0"
          scrolling="no"
          allowFullScreen
          allow="autoplay; fullscreen"
        />
        {/* Top mask bar hiding Pornhub title completely */}
        <div className="absolute top-0 inset-x-0 h-12 bg-gradient-to-b from-[#090b10] via-[#090b10]/90 to-transparent z-10 pointer-events-none flex items-center justify-between px-4">
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-rose-500 animate-pulse" />
            <span className="text-xs font-black tracking-widest text-white uppercase drop-shadow">DOROHUB PLAYER</span>
            <span className="px-1.5 py-0.5 rounded text-[10px] font-bold bg-white/10 text-white/80 border border-white/10">1080p Ultra HD</span>
          </div>
          <span className="text-[11px] font-semibold text-white/50 tracking-wider">MTBR Sovereign Network</span>
        </div>
        {/* Bottom right mask badge hiding Pornhub logo */}
        <div className="absolute bottom-3 right-3 z-10 pointer-events-none flex items-center gap-1.5 px-3 py-1 rounded-lg bg-[#090b10]/95 backdrop-blur-md border border-white/10 shadow-xl">
          <span className="text-[10px] font-black tracking-widest text-rose-500 uppercase">DOROHUB</span>
          <span className="w-1 h-1 rounded-full bg-white/40" />
          <span className="text-[10px] font-bold text-white/80">HD</span>
        </div>
      </div>
    );
  }



  if (isEmbed && isLocked) {
    return (
      <div className="relative w-full aspect-video rounded-xl overflow-hidden bg-[#0a0a0f] flex flex-col items-center justify-center gap-4">
        <div className="absolute inset-0 blur-sm opacity-30 bg-gradient-to-br from-yellow-900 to-black" />
        <Lock size={40} className="text-[#f59e0b] relative z-10" />
        <p className="font-bold text-lg relative z-10">Contenu VIP</p>
        <Link href="/premium" className="btn btn-gold relative z-10">
          <Crown size={14} /> Devenir VIP — 0,99€
        </Link>
      </div>
    );
  }
  // ────────────────────────────────────────────────────────────────────────────
  const [theaterMode, setTheaterMode] = useState(false);
  const [ended, setEnded] = useState(false);
  const [countdown, setCountdown] = useState(5);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    setIsMobile(/iPhone|iPad|iPod|Android/i.test(navigator.userAgent));
  }, []);
  
  // Custom Controls State
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(1);
  const [isMuted, setIsMuted] = useState(false);
  const [showControls, setShowControls] = useState(true);
  const [showSettings, setShowSettings] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [quality, setQuality] = useState("1080p");
  const [hlsLevels, setHlsLevels] = useState<any[]>([]);
  const [speed, setSpeed] = useState(1);

  // Hydration safety for local storage
  useEffect(() => {
    const savedQuality = localStorage.getItem("mtbr_quality");
    if (savedQuality) setQuality(savedQuality);
    
    const savedSpeed = localStorage.getItem("mtbr_speed");
    if (savedSpeed) setSpeed(parseFloat(savedSpeed));
  }, []);
  const [isBuffering, setIsBuffering] = useState(false);
  const [isHovering, setIsHovering] = useState(false);
  const [lightsOut, setLightsOut] = useState(false);
  const hlsRef = useRef<Hls | null>(null);

  // Heatmap & Chapters State
  const [hoverX, setHoverX] = useState(0);
  const [hoverTime, setHoverTime] = useState(0);
  const [isHoveringProgress, setIsHoveringProgress] = useState(false);

  // Générer des chapitres déterministes basés sur la durée de la vidéo
  const getChapters = (dur: number) => {
    if (!dur) return [];
    return [
      { title: "Intro / Accroche", time: 0, percent: 0 },
      { title: "Préliminaires / Douceur", time: Math.floor(dur * 0.15), percent: 15 },
      { title: "Action Intense / Scène principale", time: Math.floor(dur * 0.45), percent: 45 },
      { title: "Climax / Finition", time: Math.floor(dur * 0.8), percent: 80 },
      { title: "Outro / Débrief", time: Math.floor(dur * 0.92), percent: 92 },
    ];
  };

  const chapters = getChapters(duration);

  // Générer un tracé de courbe SVG pour la heatmap basé sur l'URL
  const getHeatmapPath = (url: string) => {
    let hash = 0;
    const str = url || "default";
    for (let i = 0; i < str.length; i++) {
      hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    
    const points = [];
    for (let i = 0; i <= 10; i++) {
      const x = i * 10;
      const val = Math.abs(Math.sin(hash + i * 1.8) * 18) + 2;
      const weight = i > 3 && i < 8 ? 1.4 : 0.7;
      const height = Math.min(24, val * weight);
      points.push({ x, y: 28 - height });
    }

    let path = `M 0 28`;
    for (let i = 0; i < points.length - 1; i++) {
      const p1 = points[i];
      const p2 = points[i + 1];
      const cx = (p1.x + p2.x) / 2;
      path += ` C ${cx} ${p1.y}, ${cx} ${p2.y}, ${p2.x} ${p2.y}`;
    }
    path += ` L 100 28 L 0 28 Z`;
    return path;
  };

  const heatmapPath = getHeatmapPath(mediaUrl);

  const handleProgressMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const percent = Math.min(Math.max(0, x / rect.width), 1);
    setHoverX(percent * 100);
    setHoverTime(percent * duration);
    setIsHoveringProgress(true);
  };

  const getActiveChapterTitle = (time: number) => {
    if (!chapters.length) return "";
    const active = [...chapters].reverse().find(c => time >= c.time);
    return active ? active.title : chapters[0].title;
  };

  const jumpToChapter = (time: number) => {
    if (videoRef.current) {
      videoRef.current.currentTime = time;
      if (!isPlaying) togglePlay();
    }
  };

  const videoRef = useRef<HTMLVideoElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const controlsTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const router = useRouter();

  useEffect(() => {
    if (isEmbed || !videoRef.current || !mediaUrl) return;

    if (videoRef.current.canPlayType("application/vnd.apple.mpegurl")) {
      videoRef.current.src = mediaUrl;
    } else if (mediaUrl.includes(".m3u8") && Hls.isSupported()) {
      const hls = new Hls({ maxMaxBufferLength: 30 });
      hlsRef.current = hls;
      hls.loadSource(mediaUrl);
      hls.attachMedia(videoRef.current);
      hls.on(Hls.Events.MANIFEST_PARSED, (event, data) => {
        setHlsLevels(data.levels);
      });
      hls.on(Hls.Events.ERROR, (event, data) => {
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              hls.startLoad();
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              hls.recoverMediaError();
              break;
            default:
              hls.destroy();
              break;
          }
        }
      });
    }

    return () => {
      if (hlsRef.current) {
        hlsRef.current.destroy();
        hlsRef.current = null;
      }
    };
  }, [mediaUrl, isEmbed]);

  // Handle Video Ended for Next Video
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (ended && nextVideoId) {
      timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            router.push(`/video/${nextVideoId}`);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(timer);
  }, [ended, nextVideoId, router]);

  // Auto-hide controls
  useEffect(() => {
    const resetControlsTimeout = () => {
      setShowControls(true);
      if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current);
      
      if (isPlaying && !showSettings && isHovering) {
        controlsTimeoutRef.current = setTimeout(() => {
          setShowControls(false);
        }, 2500);
      }
    };

    resetControlsTimeout();
    return () => {
      if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current);
    };
  }, [isPlaying, isHovering, showSettings]);

  // Listen for seekTo event from VideoDescription
  useEffect(() => {
    const handleSeekTo = (e: any) => {
      if (videoRef.current && e.detail !== undefined) {
        videoRef.current.currentTime = e.detail;
        if (!isPlaying) togglePlay();
      }
    };
    window.addEventListener("seekTo", handleSeekTo);
    return () => window.removeEventListener("seekTo", handleSeekTo);
  }, [isPlaying]);

  // Keyboard Shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ignore if typing in an input
      if (document.activeElement?.tagName === "INPUT" || document.activeElement?.tagName === "TEXTAREA") return;
      
      if (!videoRef.current) return;

      switch(e.key.toLowerCase()) {
        case 'escape':
          e.preventDefault();
          window.location.href = "https://www.google.com"; // Boss Key / Quick Escape
          break;
        case ' ':
        case 'k':
          e.preventDefault();
          togglePlay();
          break;
        case 'f':
          e.preventDefault();
          toggleFullscreen();
          break;
        case 'm':
          e.preventDefault();
          toggleMute();
          break;
        case 'arrowright':
          e.preventDefault();
          videoRef.current.currentTime = Math.min(videoRef.current.duration, videoRef.current.currentTime + 10);
          break;
        case 'arrowleft':
          e.preventDefault();
          videoRef.current.currentTime = Math.max(0, videoRef.current.currentTime - 10);
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isPlaying, isMuted]);

  // Video Events
  const togglePlay = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
        setIsPlaying(false);
      } else {
        const playPromise = videoRef.current.play();
        if (playPromise !== undefined) {
          playPromise.then(() => {
            setIsPlaying(true);
          }).catch((err) => {
            console.error("Autoplay/Play prevented:", err);
            setIsPlaying(false);
          });
        } else {
          setIsPlaying(true);
        }
      }
    }
  };

  const handleTimeUpdate = () => {
    if (videoRef.current) {
      setCurrentTime(videoRef.current.currentTime);
    }
  };

  const handleLoadedMetadata = () => {
    if (videoRef.current) {
      setDuration(videoRef.current.duration);
    }
  };

  const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (videoRef.current) {
      const rect = e.currentTarget.getBoundingClientRect();
      const pos = (e.clientX - rect.left) / rect.width;
      videoRef.current.currentTime = pos * duration;
    }
  };

  const toggleMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = parseFloat(e.target.value);
    setVolume(val);
    if (videoRef.current) {
      videoRef.current.volume = val;
      if (val > 0 && isMuted) {
        setIsMuted(false);
        videoRef.current.muted = false;
      }
    }
  };

  const toggleFullscreen = async () => {
    if (!containerRef.current) return;
    
    if (!document.fullscreenElement) {
      await containerRef.current.requestFullscreen().catch(err => console.log(err));
      setIsFullscreen(true);
    } else {
      await document.exitFullscreen();
      setIsFullscreen(false);
    }
  };

  useEffect(() => {
    const handleFullscreenChange = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener("fullscreenchange", handleFullscreenChange);
    return () => document.removeEventListener("fullscreenchange", handleFullscreenChange);
  }, []);

  const changeQuality = (newQuality: string) => {
    setQuality(newQuality);
    setShowSettings(false);
    
    if (hlsRef.current && hlsLevels.length > 0) {
      const levelIndex = hlsLevels.findIndex(l => (l.height + "p") === newQuality);
      if (levelIndex !== -1) {
        hlsRef.current.currentLevel = levelIndex;
      } else {
        hlsRef.current.currentLevel = -1; // Auto
      }
    } else {
      // Fallback pseudo-buffering pour les mp4 simples
      setIsBuffering(true);
      if (videoRef.current) {
        const wasPlaying = !videoRef.current.paused;
        videoRef.current.pause();
        
        setTimeout(() => {
          setIsBuffering(false);
          if (wasPlaying) videoRef.current?.play();
        }, 800);
      }
    }
  };

  const changeSpeed = (newSpeed: number) => {
    setSpeed(newSpeed);
    if (videoRef.current) {
      videoRef.current.playbackRate = newSpeed;
    }
  };

  const formatTime = (time: number) => {
    const mins = Math.floor(time / 60);
    const secs = Math.floor(time % 60);
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
  };

  // Locked State
  if (isLocked) {
    return (
      <div className="relative rounded-sm overflow-hidden aspect-video bg-black flex flex-col items-center justify-center">
        <div className="absolute inset-0 flex flex-col items-center justify-center" style={{ background: "rgba(10,10,15,0.95)" }}>
          <div className="p-6 rounded-2xl text-center max-w-sm border border-[#e05a68] bg-black/50">
            <Lock size={40} className="mx-auto mb-4 text-[#e05a68]" />
            <h2 className="text-xl font-black mb-2 text-white">Contenu VIP</h2>
            <p className="text-sm mb-6 text-[#aaaaaa]">
              Cette vidéo est réservée aux membres Premium. Débloquez l'accès à vie pour <strong className="text-[#e05a68]">0,99€</strong>.
            </p>
            <Link href="/premium" className="px-6 py-3 bg-[#e05a68] text-black font-bold rounded-lg flex items-center justify-center gap-2 hover:bg-[#f08592] transition-colors">
              <Crown size={18} /> Débloquer pour 0,99€
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      {lightsOut && !isFullscreen && (
        <div className="fixed inset-0 bg-black/95 z-40 transition-opacity duration-500 pointer-events-none" />
      )}

      <div 
        ref={containerRef}
        className={`relative bg-black transition-all duration-300 ease-in-out group ${theaterMode ? "fixed inset-0 z-[100] flex flex-col justify-center" : isFullscreen ? "w-full h-full" : "rounded-sm aspect-video"} ${lightsOut ? "z-50 ring-1 ring-[#333333] shadow-[0_0_50px_rgba(0,0,0,0.8)]" : ""}`}
        onMouseEnter={() => setIsHovering(true)}
      onMouseLeave={() => setIsHovering(false)}
      onMouseMove={() => {
        setShowControls(true);
        if (isPlaying && controlsTimeoutRef.current) {
          clearTimeout(controlsTimeoutRef.current);
          controlsTimeoutRef.current = setTimeout(() => !showSettings && setShowControls(false), 2500);
        }
      }}
    >
      <div className="relative w-full h-full flex items-center justify-center bg-black overflow-hidden" onClick={isMobile ? undefined : togglePlay}>
        <video
          ref={videoRef}
          className="w-full h-full object-contain"
          onContextMenu={e => e.preventDefault()}
          preload="metadata"
          playsInline
          controls={isMobile}
          onTimeUpdate={handleTimeUpdate}
          onLoadedMetadata={handleLoadedMetadata}
          onEnded={() => { setEnded(true); setIsPlaying(false); }}
          onPlay={() => { setEnded(false); setIsPlaying(true); }}
          onPause={() => setIsPlaying(false)}
          onWaiting={() => setIsBuffering(true)}
          onPlaying={() => setIsBuffering(false)}
        >
          {!mediaUrl?.includes(".m3u8") && <source src={mediaUrl} />}
          Votre navigateur ne supporte pas la lecture vidéo.
        </video>

        {/* Buffering Overlay */}
        {isBuffering && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/20 z-10 pointer-events-none">
            <Loader2 className="w-12 h-12 text-[#e05a68] animate-spin" />
          </div>
        )}

        {/* Play/Pause Center Animation */}
        {!isMobile && !isPlaying && !isBuffering && !ended && (
          <div className="absolute inset-0 flex items-center justify-center z-10 pointer-events-none">
            <div className="w-20 h-20 bg-black/50 rounded-full flex items-center justify-center">
              <Play className="w-10 h-10 text-white fill-white ml-2" />
            </div>
          </div>
        )}


      </div>


      {/* Controls Overlay */}
      {!isMobile && (
        <div className={`absolute bottom-0 left-0 right-0 p-4 pt-16 bg-gradient-to-t from-black/90 via-black/40 to-transparent transition-opacity duration-300 z-30 ${showControls || !isPlaying ? 'opacity-100' : 'opacity-0'}`}>
        
        {/* Progress Bar with Heatmap & Chapters */}
        <div 
          className="w-full mb-4 cursor-pointer relative group/progress"
          onClick={handleProgressClick}
          onMouseMove={handleProgressMouseMove}
          onMouseLeave={() => setIsHoveringProgress(false)}
        >
          {/* Heatmap SVG Graphique */}
          <div className="absolute bottom-full left-0 right-0 h-7 pointer-events-none overflow-hidden select-none mb-1 opacity-0 group-hover/progress:opacity-75 transition-opacity duration-300">
            <svg 
              className="w-full h-full"
              viewBox="0 0 100 28" 
              preserveAspectRatio="none"
            >
              <defs>
                <linearGradient id="heatmapGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#e05a68" stopOpacity="0.8" />
                  <stop offset="100%" stopColor="#e05a68" stopOpacity="0.0" />
                </linearGradient>
              </defs>
              <path 
                d={heatmapPath} 
                fill="url(#heatmapGrad)"
                stroke="#e05a68"
                strokeWidth="0.4"
                strokeOpacity="0.6"
              />
            </svg>
          </div>

          {/* Chapter Tooltip */}
          {isHoveringProgress && duration > 0 && (
            <div 
              className="absolute bottom-full mb-9 transform -translate-x-1/2 bg-black/95 text-white text-xs font-semibold py-1.5 px-3 rounded-lg border border-[#e05a68]/30 shadow-2xl backdrop-blur-md pointer-events-none flex flex-col items-center gap-0.5 z-50 transition-all duration-75 ease-out"
              style={{ left: `${hoverX}%` }}
            >
              <span className="text-[#e05a68] font-bold text-[9px] tracking-wider uppercase">
                {getActiveChapterTitle(hoverTime)}
              </span>
              <span className="font-mono text-white/90">
                {formatTime(hoverTime)}
              </span>
            </div>
          )}

          {/* Progress track container */}
          <div className="w-full h-1.5 bg-white/20 rounded-full relative overflow-hidden flex items-center group-hover/progress:h-2 transition-all duration-200">
            {/* Background track */}
            <div className="absolute inset-0 bg-white/10" />
            
            {/* Live Progress */}
            <div 
              className="h-full bg-[#e05a68] relative"
              style={{ width: `${(currentTime / duration) * 100 || 0}%` }}
            />

            {/* Hover visual feedback */}
            {isHoveringProgress && (
              <div 
                className="absolute top-0 bottom-0 left-0 bg-white/10 pointer-events-none"
                style={{ width: `${hoverX}%` }}
              />
            )}

            {/* Fines séparations physiques pour délimiter les chapitres */}
            {chapters.map((c, i) => i > 0 && (
              <div 
                key={i}
                className="absolute top-0 bottom-0 w-0.5 bg-black z-20"
                style={{ left: `${c.percent}%` }}
              />
            ))}
          </div>
          
          {/* Progress handle (cercle) */}
          <div 
            className="absolute top-1/2 -translate-y-1/2 w-3.5 h-3.5 bg-[#e05a68] rounded-full border border-white shadow-md scale-0 group-hover/progress:scale-100 transition-transform pointer-events-none z-30"
            style={{ left: `calc(${(currentTime / duration) * 100 || 0}% - 7px)` }}
          />
        </div>

        {/* Bottom Bar */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <button onClick={togglePlay} className="text-white hover:text-[#e05a68] transition-colors">
              {isPlaying ? <Pause size={24} fill="currentColor" /> : <Play size={24} fill="currentColor" />}
            </button>
            
            <div className="flex items-center gap-2 group/volume">
              <button onClick={toggleMute} className="text-white hover:text-[#e05a68] transition-colors">
                {isMuted || volume === 0 ? <VolumeX size={20} /> : <Volume2 size={20} />}
              </button>
              <input 
                type="range" 
                min="0" max="1" step="0.05" 
                value={isMuted ? 0 : volume}
                onChange={handleVolumeChange}
                className="w-0 opacity-0 group-hover/volume:w-20 group-hover/volume:opacity-100 transition-all duration-300 accent-[#e05a68]"
              />
            </div>
            
            <div className="text-white text-sm font-medium tabular-nums opacity-90">
              {formatTime(currentTime)} <span className="opacity-50">/</span> {formatTime(duration)}
            </div>
          </div>

          <div className="flex items-center gap-4 relative">
            
            {/* Screenshot Capture */}
            <button 
              onClick={(e) => {
                e.stopPropagation();
                if (videoRef.current) {
                  try {
                    const canvas = document.createElement("canvas");
                    canvas.width = videoRef.current.videoWidth;
                    canvas.height = videoRef.current.videoHeight;
                    const ctx = canvas.getContext("2d");
                    if (ctx) {
                      ctx.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
                      const dataUrl = canvas.toDataURL("image/jpeg", 0.9);
                      const a = document.createElement("a");
                      a.href = dataUrl;
                      a.download = `mtbr_capture_${formatTime(currentTime).replace(/:/g, "-")}.jpg`;
                      a.click();
                      toast("Capture d'écran sauvegardée !", "success");
                    }
                  } catch (err) {
                    toast("Erreur : la vidéo est protégée (CORS)", "error");
                  }
                }
              }}
              className="text-white hover:text-[#e05a68] transition-colors hidden sm:block"
              title="Prendre une capture d'écran"
            >
              <Camera size={20} />
            </button>

            {/* Settings */}
            <div className="relative">
              <button onClick={() => setShowSettings(!showSettings)} className={`text-white hover:text-[#e05a68] transition-transform duration-500 ${showSettings ? 'rotate-90 text-[#e05a68]' : ''}`}>
                <Settings size={20} />
              </button>
              
              {/* Settings Menu */}
              {showSettings && (
                <div className="absolute bottom-10 right-0 w-48 bg-[#1a1a1a]/95 backdrop-blur-md rounded-xl border border-[#333333] shadow-2xl overflow-hidden animate-fade-in z-50">
                  <div className="px-4 py-2 text-xs font-bold text-[#aaaaaa] border-b border-[#333333]">QUALITÉ</div>
                  <div className="flex flex-col border-b border-[#333333]">
                    {["1080p", "720p", "480p"].map(q => (
                      <button 
                        key={q} 
                        onClick={() => changeQuality(q)}
                        className={`px-4 py-2 text-sm text-left hover:bg-[#262626] transition-colors flex items-center justify-between ${quality === q ? 'text-[#e05a68] font-bold' : 'text-white'}`}
                      >
                        {q} {q === "1080p" && <span className="text-[10px] bg-red-500 text-white px-1 rounded">HD</span>}
                      </button>
                    ))}
                  </div>
                  
                  <div className="px-4 py-2 text-xs font-bold text-[#aaaaaa] border-b border-[#333333] mt-1">VITESSE</div>
                  <div className="flex flex-col pb-1">
                    {[0.5, 1, 1.5, 2].map(s => (
                      <button 
                        key={s} 
                        onClick={() => changeSpeed(s)}
                        className={`px-4 py-2 text-sm text-left hover:bg-[#262626] transition-colors ${speed === s ? 'text-[#e05a68] font-bold' : 'text-white'}`}
                      >
                        {s === 1 ? 'Normale' : `${s}x`}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Lights Out */}
            {!isFullscreen && (
              <button 
                onClick={() => setLightsOut(!lightsOut)}
                className={`transition-colors hidden md:block ${lightsOut ? 'text-[#e05a68]' : 'text-white hover:text-[#e05a68]'}`}
                title="Mode Cinéma (Lumières)"
              >
                <Lightbulb size={20} />
              </button>
            )}

            {/* Theater Mode (Only show if not fullscreen) */}
            {!isFullscreen && (
              <button 
                onClick={() => setTheaterMode(!theaterMode)}
                className="text-white hover:text-[#e05a68] transition-colors hidden md:block"
                title={theaterMode ? "Quitter mode cinéma" : "Mode cinéma"}
              >
                <div className="w-5 h-4 border-2 border-current rounded-sm"></div>
              </button>
            )}

            {/* Fullscreen */}
            <button onClick={toggleFullscreen} className="text-white hover:text-[#e05a68] transition-colors">
              <Maximize size={20} />
            </button>
          </div>
        </div>
      </div>
      )}

      {/* Next Video Overlay */}
      {ended && nextVideoId && (
        <div className="absolute inset-0 bg-black/90 flex flex-col items-center justify-center z-40 animate-fade-in">
          <h3 className="text-2xl font-bold text-white mb-2">Prochaine vidéo dans...</h3>
          <div className="text-6xl font-black text-[#e05a68] mb-6">{countdown}</div>
          <div className="flex gap-4">
            <button onClick={() => { setEnded(false); setIsPlaying(false); }} className="px-6 py-2 border border-[#333333] rounded-lg hover:bg-[#262626] text-white transition-colors font-semibold">
              Annuler
            </button>
            <button onClick={() => router.push(`/video/${nextVideoId}`)} className="px-6 py-2 bg-[#e05a68] rounded-lg hover:bg-[#f08592] text-black font-bold transition-colors">
              Lancer maintenant
            </button>
          </div>
        </div>
      )}
    </div>

    {/* Cliquable Scenes / Chapters List Panel */}
    {!isFullscreen && duration > 0 && (
      <div className="mt-4 p-4 rounded-xl border border-[#22222a] bg-[#0c0c12]/60 backdrop-blur-md">
        <h4 className="text-xs font-black tracking-wider text-[#e05a68] mb-3 uppercase flex items-center gap-1.5">
          <span className="w-1.5 h-1.5 rounded-full bg-[#e05a68] animate-pulse" />
          Scènes & Marqueurs Temporels (Hotspots)
        </h4>
        <div className="grid grid-cols-2 sm:grid-cols-5 gap-2">
          {chapters.map((c, i) => {
            const isActiveScene = currentTime >= c.time && (i === chapters.length - 1 || currentTime < chapters[i + 1].time);
            return (
              <button
                key={i}
                onClick={() => jumpToChapter(c.time)}
                className={`px-3 py-2 text-xs font-semibold rounded-lg border text-left transition-all flex flex-col gap-0.5 ${
                  isActiveScene 
                    ? 'bg-[#e05a68]/15 border-[#e05a68] text-[#e05a68] shadow-[0_0_15px_rgba(224,90,104,0.25)]' 
                    : 'bg-black/35 border-[#1a1a24] hover:border-[#e05a68]/45 hover:bg-[#e05a68]/5 text-white/60 hover:text-white'
                }`}
              >
                <span className="truncate">{c.title}</span>
                <span className="text-[10px] font-mono opacity-50">{formatTime(c.time)}</span>
              </button>
            );
          })}
        </div>
      </div>
    )}

    </>
  );
}
