"use client";
import { useEffect, useRef, useState, useCallback } from "react";
import { 
  Heart, 
  MessageCircle, 
  Crown, 
  Lock, 
  Play, 
  Pause,
  Eye, 
  RefreshCw, 
  Share2, 
  Flag,
  Smartphone,
  Trash2,
  Loader2,
  Volume2,
  VolumeX,
  Plus,
  Repeat,
  ArrowDownCircle,
  Flame,
  ExternalLink
} from "lucide-react";
import Link from "next/link";
import { formatNumber } from "@/lib/utils";
import { motion, AnimatePresence } from "framer-motion";
import { toast } from "@/components/ui/Toaster";
import { ReportModal } from "@/components/ReportModal";
import { useSession } from "next-auth/react";

function getActressName(tags: string): string {
  try {
    let list: string[] = [];
    if (tags.startsWith("[")) list = JSON.parse(tags);
    else if (tags.includes(",")) list = tags.split(",").map(t => t.trim());
    else if (tags.trim()) list = [tags.trim()];
    return list.find(t => {
      const c = t.trim();
      return c.length > 2 && c.length < 40 && /^[A-Z]/.test(c) && !/^\d/.test(c) &&
        !/^(HD|4K|1080|720|amateur|teen|milf|anal|oral|big|small|black|white|latina|asian|POV|MILF|Teen|BBW|BDSM)/i.test(c);
    }) || "";
  } catch { return ""; }
}

function getBestMoment(duration: number | null): number {
  if (!duration || duration < 30) return 0;
  if (duration >= 480) return Math.floor(duration * 0.38);
  if (duration >= 180) return Math.floor(duration * 0.4);
  return Math.floor(duration * 0.2);
}

const SHORT_DURATION = 25;

const RANDOM_CREATORS = [
  { name: "Emma Laurent", handle: "@emma_laurent", img: "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150&auto=format&fit=crop&q=80" },
  { name: "Chloé Moreau", handle: "@chloe_vibes", img: "https://images.unsplash.com/photo-1517841905240-472988babdf9?w=150&auto=format&fit=crop&q=80" },
  { name: "Sarah Fit", handle: "@sarah_fitgirl", img: "https://images.unsplash.com/photo-1524504388940-b1c1722653e1?w=150&auto=format&fit=crop&q=80" },
  { name: "Lola Cherry", handle: "@lola_cherry", img: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=150&auto=format&fit=crop&q=80" },
  { name: "Elena V", handle: "@elena_model", img: "https://images.unsplash.com/photo-1508214751196-bcfd4ca60f91?w=150&auto=format&fit=crop&q=80" },
  { name: "Maya Rose", handle: "@maya_rose", img: "https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=150&auto=format&fit=crop&q=80" },
  { name: "Zoé Wild", handle: "@zoe_wild", img: "https://images.unsplash.com/photo-1531746020798-e6953c6e8e04?w=150&auto=format&fit=crop&q=80" },
  { name: "Clara Glam", handle: "@clara_glam", img: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&auto=format&fit=crop&q=80" },
  { name: "Jade Sweet", handle: "@jade_sweet", img: "https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e?w=150&auto=format&fit=crop&q=80" },
  { name: "Luna Star", handle: "@luna_star", img: "https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?w=150&auto=format&fit=crop&q=80" },
  { name: "Eva Blossom", handle: "@eva_blossom", img: "https://images.unsplash.com/photo-1509967419530-da38b4704bc6?w=150&auto=format&fit=crop&q=80" },
  { name: "Inès Peach", handle: "@ines_peach", img: "https://images.unsplash.com/photo-1514315384763-ba401779410f?w=150&auto=format&fit=crop&q=80" },
  { name: "Alicia Moon", handle: "@alicia_moon", img: "https://images.unsplash.com/photo-1519085360753-af0119f7cbe7?w=150&auto=format&fit=crop&q=80" },
  { name: "Julia Secret", handle: "@julia_secret", img: "https://images.unsplash.com/photo-1520813792240-56fc4a3765a7?w=150&auto=format&fit=crop&q=80" },
  { name: "Camille Sensual", handle: "@camille_sensual", img: "https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=150&auto=format&fit=crop&q=80" },
  { name: "Léa Paradise", handle: "@lea_paradise", img: "https://images.unsplash.com/photo-1502823403499-6ccfcf4fb453?w=150&auto=format&fit=crop&q=80" },
  { name: "Manon Cute", handle: "@manon_cute", img: "https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?w=150&auto=format&fit=crop&q=80" },
  { name: "Lucie Blondie", handle: "@lucie_blondie", img: "https://images.unsplash.com/photo-1534751516642-a171edd26cb0?w=150&auto=format&fit=crop&q=80" },
  { name: "Océane Mist", handle: "@oceane_mist", img: "https://images.unsplash.com/photo-1548142813-c348350df52b?w=150&auto=format&fit=crop&q=80" },
  { name: "Cléa Lust", handle: "@clea_lust", img: "https://images.unsplash.com/photo-1522075469751-3a6694fb2f61?w=150&auto=format&fit=crop&q=80" }
];

function getCreatorInfo(media: any, actressName?: string): { name: string; handle: string; image: string | null } {
  if (actressName) {
    const clean = actressName.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9_]/g, '');
    return { name: actressName, handle: `@${clean}`, image: null };
  }
  if (media.uploader?.name && !media.uploader.name.includes("DoroHub") && !media.uploader.name.includes("MTBR")) {
    const clean = media.uploader.name.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9_]/g, '_');
    return { name: media.uploader.name, handle: `@${clean}`, image: media.uploader.image || null };
  }
  let hash = 0;
  const str = String(media.id || media.title || "creator");
  for (let i = 0; i < str.length; i++) hash = (hash << 5) - hash + str.charCodeAt(i);
  const picked = RANDOM_CREATORS[Math.abs(hash) % RANDOM_CREATORS.length];
  return { name: picked.name, handle: picked.handle, image: picked.img };
}

/* ── ShortItem ── */
function ShortItem({ 
  media, 
  isPremium, 
  isActive, 
  isPreload, 
  globalMuted,
  setGlobalMuted,
  autoScroll,
  onNext,
  onWatched,
  onReport, 
  onDelete 
}: {
  media: any; 
  isPremium: boolean; 
  isActive: boolean; 
  isPreload: boolean;
  globalMuted: boolean;
  setGlobalMuted: (val: boolean) => void;
  autoScroll: boolean;
  onNext?: () => void;
  onWatched?: (id: string) => void;
  onReport: (media: any) => void;
  onDelete?: (id: string) => void;
}) {
  const { data: session } = useSession();
  const isAdmin = ["ADMIN", "SUPERADMIN"].includes((session?.user as any)?.role);
  const [isDeleting, setIsDeleting] = useState(false);

  const videoRef = useRef<HTMLVideoElement>(null);
  const isDirectFile = Boolean(
    media.url && (
      media.url.startsWith("/uploads/") || 
      (media.url.startsWith("http") && (media.url.includes(".mp4") || media.url.includes(".webm") || media.url.includes(".mov")))
    )
  );
  
  const videoSrc = isDirectFile ? media.url : `/api/proxy/video/${media.id}`;
  const [currentSrc, setCurrentSrc] = useState(videoSrc);

  useEffect(() => {
    setCurrentSrc(videoSrc);
    setVideoLoaded(false);
    setError(false);
  }, [videoSrc]);

  const handleVideoError = () => {
    if (currentSrc && currentSrc.includes("media.redgifs.com") && !currentSrc.includes("api/stream.php")) {
      const fallbackUrl = `https://madetobreakrules.fr/api/stream.php?url=${encodeURIComponent(currentSrc)}`;
      setCurrentSrc(fallbackUrl);
    } else {
      setError(true);
    }
  };

  const bestMoment = isDirectFile ? 0 : getBestMoment(media.duration);
  const maxDuration = isDirectFile 
    ? (media.duration && media.duration > 0 ? Math.min(media.duration, 180) : 180) 
    : SHORT_DURATION;

  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState<number>(media._count?.likes || 0);
  const [viewsCount, setViewsCount] = useState<number>(Number(media.views) || 0);
  const [videoLoaded, setVideoLoaded] = useState(false);
  const [isPlaying, setIsPlaying] = useState(true);
  const [showPlayIcon, setShowPlayIcon] = useState(false);
  const [timeLeft, setTimeLeft] = useState(maxDuration);
  const [progressPercent, setProgressPercent] = useState(0);
  const [isEnded, setIsEnded] = useState(false);
  const [error, setError] = useState(false);

  // Animation Double-Tap Like
  const [showHeartPop, setShowHeartPop] = useState(false);
  const lastTapRef = useRef<number>(0);
  const clickTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Vrai système de vue (détection temps réel 2s de visionnage)
  const hasCountedView = useRef(false);
  const viewTimerRef = useRef<NodeJS.Timeout | null>(null);

  const isLocked = media.isPremium && !isPremium;
  const actressName = getActressName(media.tags || "");
  const creatorInfo = getCreatorInfo(media, actressName);

  // Initialiser like state
  useEffect(() => {
    if (session?.user) {
      fetch(`/api/media/${media.id}/like`)
        .then(r => r.json())
        .then(d => { if (d.liked) setLiked(true); })
        .catch(() => {});
    }
  }, [media.id, session?.user]);

  // Synchronisation Mute global
  useEffect(() => {
    const video = videoRef.current;
    if (video) {
      video.muted = globalMuted;
    }
  }, [globalMuted]);

  // Vrai comptage des vues (après 2s de visionnage effectif)
  useEffect(() => {
    if (!isActive || !isPlaying || isEnded || isLocked || hasCountedView.current) {
      if (viewTimerRef.current) {
        clearTimeout(viewTimerRef.current);
        viewTimerRef.current = null;
      }
      return;
    }

    viewTimerRef.current = setTimeout(() => {
      if (!hasCountedView.current) {
        hasCountedView.current = true;
        setViewsCount((prev: number) => prev + 1);
        fetch(`/api/media/${media.id}/view`, { method: "POST" })
          .then(res => res.json())
          .then(data => {
            if (data?.views) setViewsCount(data.views);
          })
          .catch(() => {});
      }
    }, 2000);

    return () => {
      if (viewTimerRef.current) {
        clearTimeout(viewTimerRef.current);
        viewTimerRef.current = null;
      }
    };
  }, [isActive, isPlaying, isEnded, isLocked, media.id]);

  // Lecture instantanée au focus
  useEffect(() => {
    const video = videoRef.current;
    if (!video || isLocked) return;

    if (!isActive) {
      video.pause();
      setIsPlaying(false);
      return;
    }

    if (isActive) {
      setIsEnded(false);
      setTimeLeft(maxDuration);
      setProgressPercent(0);
      setError(false);

      if (bestMoment > 0 && Math.abs(video.currentTime - bestMoment) > 2) {
        video.currentTime = bestMoment;
      }

      video.muted = globalMuted;
      const playPromise = video.play();
      if (playPromise !== undefined) {
        playPromise
          .then(() => {
            setVideoLoaded(true);
            setIsPlaying(true);
          })
          .catch(() => {
            // Si autoplay sonore bloqué par le navigateur -> fallback muet
            video.muted = true;
            setGlobalMuted(true);
            video.play().then(() => {
              setVideoLoaded(true);
              setIsPlaying(true);
            }).catch(() => {});
          });
      }
    }
  }, [isActive, isLocked, bestMoment, maxDuration, globalMuted, setGlobalMuted]);

  // Suivi de progression et fin de lecture
  useEffect(() => {
    if (!isActive || !isPlaying || isEnded || isLocked) return;
    const interval = setInterval(() => {
      const video = videoRef.current;
      if (!video) return;

      if (!isDirectFile) {
        const played = Math.max(0, video.currentTime - bestMoment);
        const remaining = Math.max(0, Math.ceil(maxDuration - played));
        const pct = Math.min(100, Math.max(0, (played / maxDuration) * 100));
        setTimeLeft(remaining);
        setProgressPercent(pct);

        if (played >= 2 || pct >= 15) {
          onWatched?.(media.id);
        }

        if (played >= maxDuration) {
          if (autoScroll && onNext) {
            onNext();
          } else {
            video.pause();
            setIsPlaying(false);
            setIsEnded(true);
          }
        }
      } else {
        const duration = video.duration || maxDuration;
        const remaining = Math.max(0, Math.ceil(duration - video.currentTime));
        const pct = Math.min(100, Math.max(0, (video.currentTime / duration) * 100));
        setTimeLeft(remaining || maxDuration);
        setProgressPercent(pct);

        if (video.currentTime >= 2 || pct >= 15) {
          onWatched?.(media.id);
        }

        if (video.ended || (video.currentTime >= duration && duration > 0)) {
          if (autoScroll && onNext) {
            onNext();
          }
        }
      }
    }, 200);

    return () => clearInterval(interval);
  }, [isActive, isPlaying, isEnded, isLocked, bestMoment, maxDuration, isDirectFile, autoScroll, onNext, onWatched, media.id]);

  // Gestion du clic / double-clic (Double-tap to like)
  const handleContainerClick = (e: React.MouseEvent) => {
    const now = Date.now();
    const timeDiff = now - lastTapRef.current;
    lastTapRef.current = now;

    if (timeDiff < 280) {
      // Double tap détecté !
      if (clickTimeoutRef.current) {
        clearTimeout(clickTimeoutRef.current);
        clickTimeoutRef.current = null;
      }
      setShowHeartPop(true);
      setTimeout(() => setShowHeartPop(false), 900);
      if (!liked) {
        handleLike(e);
      }
    } else {
      // Clic simple avec délai pour ne pas entrer en conflit avec le double-tap
      clickTimeoutRef.current = setTimeout(() => {
        togglePlay();
      }, 250);
    }
  };

  const togglePlay = () => {
    const video = videoRef.current;
    if (!video || isLocked || isEnded) return;

    if (isPlaying) {
      video.pause();
      setIsPlaying(false);
    } else {
      video.play().catch(() => {});
      setIsPlaying(true);
    }
    setShowPlayIcon(true);
    setTimeout(() => setShowPlayIcon(false), 700);
  };

  const toggleMute = (e: React.MouseEvent) => {
    e.stopPropagation();
    const nextMuted = !globalMuted;
    setGlobalMuted(nextMuted);
    try {
      localStorage.setItem("shorts_muted", nextMuted ? "true" : "false");
    } catch {}
    const video = videoRef.current;
    if (video) {
      video.muted = nextMuted;
      if (!nextMuted && !isPlaying) {
        video.play().catch(() => {});
        setIsPlaying(true);
      }
    }
  };

  const handleLike = async (e?: React.MouseEvent) => {
    if (e) e.stopPropagation();
    const newLiked = !liked;
    setLiked(newLiked);
    setLikeCount((prev: number) => newLiked ? prev + 1 : Math.max(0, prev - 1));
    try {
      await fetch(`/api/media/${media.id}/like`, { method: "POST" });
    } catch {}
  };

  const handleShare = (e: React.MouseEvent) => {
    e.stopPropagation();
    const url = `${window.location.origin}/shorts#${media.id}`;
    if (typeof navigator !== "undefined" && navigator.share) {
      navigator.share({ 
        title: media.title, 
        text: `Regarde ce short sur DoroHub: ${media.title}`,
        url 
      }).catch(() => {});
    } else {
      navigator.clipboard.writeText(url);
      toast("Lien copié dans le presse-papier !", "success");
    }
  };

  const handleDeleteShort = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!confirm(`Supprimer définitivement ce Short ("${media.title}") ? Cette action est irréversible.`)) {
      return;
    }
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/admin/media/${media.id}`, { method: "DELETE" });
      const data = await res.json();
      if (res.ok && data.success) {
        toast("Short supprimé avec succès", "success");
        if (onDelete) onDelete(media.id);
      } else {
        toast(data.error || "Erreur lors de la suppression", "error");
      }
    } catch (err: any) {
      toast("Erreur réseau: " + err.message, "error");
    } finally {
      setIsDeleting(false);
    }
  };

  const handleReplay = (e: React.MouseEvent) => {
    e.stopPropagation();
    const video = videoRef.current;
    if (!video) return;
    video.currentTime = bestMoment;
    video.play().then(() => {
      setIsEnded(false);
      setIsPlaying(true);
      setTimeLeft(maxDuration);
      setProgressPercent(0);
    });
  };

  // Clic sur barre de progression
  const handleScrubberClick = (e: React.MouseEvent<HTMLDivElement>) => {
    e.stopPropagation();
    const video = videoRef.current;
    if (!video || !video.duration) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const ratio = Math.max(0, Math.min(1, clickX / rect.width));
    video.currentTime = ratio * video.duration;
  };

  return (
    <div 
      onClick={handleContainerClick}
      className="relative w-full h-[100dvh] md:h-[calc(100vh-96px)] md:max-w-[440px] mx-auto bg-black overflow-hidden select-none touch-manipulation cursor-pointer md:rounded-3xl md:border md:border-[#2a1a45] md:shadow-2xl flex items-center justify-center"
    >
      
      {/* 🔒 Contenu Verrouillé VIP */}
      {isLocked ? (
        <div className="absolute inset-0 bg-[#0e0a17] flex flex-col items-center justify-center p-6 text-center space-y-4 z-30">
          <div className="w-16 h-16 rounded-full bg-amber-500/20 border border-amber-500/50 flex items-center justify-center text-amber-400">
            <Lock size={32} />
          </div>
          <h3 className="text-lg font-black text-white">Vidéo Exclusive VIP</h3>
          <p className="text-xs text-[#c4b5d4] max-w-xs">
            Cette vidéo courte est réservée aux membres VIP. Débloque l'accès illimité en 1 clic.
          </p>
          <Link href="/premium" onClick={e => e.stopPropagation()} className="btn btn-gold text-xs px-6 py-2.5 shadow-[0_0_20px_rgba(255,179,0,0.4)]">
            <Crown size={14} /> Devenir VIP — 0,99€
          </Link>
        </div>
      ) : (
        <>
          {/* Lecteur Vidéo Direct HTML5 */}
          <video
            ref={videoRef}
            src={currentSrc}
            poster={media.thumbnailUrl || undefined}
            preload={isActive || isPreload ? "auto" : "none"}
            playsInline
            loop={!autoScroll}
            muted={globalMuted}
            {...({ referrerPolicy: "no-referrer" } as any)}
            onLoadedData={() => setVideoLoaded(true)}
            onPlaying={() => {
              setVideoLoaded(true);
              setIsPlaying(true);
            }}
            onPause={() => setIsPlaying(false)}
            onError={handleVideoError}
            className="w-full h-full object-cover"
          />

          {/* Image poster de fond si vidéo pas encore prête */}
          {!videoLoaded && media.thumbnailUrl && (
            <img
              src={media.thumbnailUrl}
              alt={media.title}
              referrerPolicy="no-referrer"
              className="absolute inset-0 w-full h-full object-cover pointer-events-none z-10"
            />
          )}

          {/* Spinner animé élégant pendant le chargement initial */}
          {!videoLoaded && !error && (
            <div className="absolute inset-0 flex items-center justify-center pointer-events-none z-20">
              <div className="w-10 h-10 border-3 border-purple-500/30 border-t-purple-500 rounded-full animate-spin" />
            </div>
          )}

          {/* Animation Cœur Pop-up (Double-Tap) */}
          <AnimatePresence>
            {showHeartPop && (
              <motion.div
                initial={{ scale: 0, opacity: 0 }}
                animate={{ scale: [0, 1.4, 1.2], opacity: [0, 1, 0.9] }}
                exit={{ scale: 1.6, opacity: 0 }}
                transition={{ duration: 0.6, ease: "easeOut" }}
                className="absolute inset-0 m-auto w-32 h-32 flex items-center justify-center z-50 pointer-events-none drop-shadow-[0_0_35px_rgba(239,68,68,0.9)]"
              >
                <Heart size={110} className="text-red-500 fill-red-500 stroke-white stroke-[1.5]" />
              </motion.div>
            )}
          </AnimatePresence>

          {/* Central Animated Play/Pause Feedback */}
          <AnimatePresence>
            {showPlayIcon && (
              <motion.div
                initial={{ opacity: 0, scale: 0.5 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.8 }}
                className="absolute inset-0 m-auto w-20 h-20 rounded-full bg-black/60 backdrop-blur-md flex items-center justify-center text-white z-40 pointer-events-none"
              >
                {isPlaying ? <Play size={36} className="fill-white ml-1" /> : <Pause size={36} className="fill-white" />}
              </motion.div>
            )}
          </AnimatePresence>

          {/* Overlay Extrait Terminé -> Regarder Vidéo Intégrale */}
          <AnimatePresence>
            {isEnded && (
              <motion.div 
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="absolute inset-0 z-40 bg-black/85 backdrop-blur-md flex flex-col items-center justify-center p-6 text-center"
              >
                <div className="space-y-4 max-w-xs" onClick={e => e.stopPropagation()}>
                  <div className="w-16 h-16 rounded-full bg-[#9d4edd]/20 border border-[#9d4edd]/50 flex items-center justify-center mx-auto text-[#b57bee]">
                    <Play size={28} className="fill-current ml-1" />
                  </div>
                  <h3 className="text-base font-black text-white">Extrait terminé</h3>
                  <p className="text-xs text-[#c4b5d4]">
                    Regarde la vidéo complète en HD ou rejoue l'extrait.
                  </p>
                  <Link 
                    href={`/video/${media.id}`}
                    className="w-full py-3.5 rounded-2xl bg-gradient-to-r from-pink-600 to-[#7b2cbf] hover:from-pink-500 hover:to-[#8d35db] text-white font-black text-xs flex items-center justify-center gap-2 shadow-[0_0_20px_rgba(236,72,153,0.5)] transition-all"
                  >
                    <Play size={14} className="fill-current" />
                    <span>Regarder la vidéo intégrale</span>
                  </Link>
                  <button
                    onClick={handleReplay}
                    className="w-full py-2.5 rounded-xl bg-white/10 hover:bg-white/20 text-xs font-bold text-white flex items-center justify-center gap-1.5 transition-all cursor-pointer"
                  >
                    <RefreshCw size={12} />
                    <span>Revoir l'extrait</span>
                  </button>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Dégradés d'ombrage pour lisibilité */}
          <div className="absolute inset-0 pointer-events-none z-20">
            <div className="absolute bottom-0 left-0 right-0 h-64 bg-gradient-to-t from-black/95 via-black/45 to-transparent" />
            <div className="absolute top-0 left-0 right-0 h-28 bg-gradient-to-b from-black/70 to-transparent" />
          </div>
        </>
      )}

      {/* 🔊 Contrôles Audio & Timer & Mode Auto (Haut Gauche) */}
      <div className="absolute top-16 md:top-4 left-4 z-30 flex items-center gap-2">
        <button
          type="button"
          onClick={toggleMute}
          className="p-2.5 rounded-full bg-black/60 backdrop-blur-md border border-white/20 text-white shadow-lg active:scale-90 transition-transform cursor-pointer"
          title={globalMuted ? "Activer le son (M)" : "Couper le son (M)"}
        >
          {globalMuted ? <VolumeX size={16} className="text-red-400" /> : <Volume2 size={16} className="text-white" />}
        </button>

        {isActive && videoLoaded && !isEnded && (
          <div className="bg-black/60 backdrop-blur px-3 py-1.5 rounded-full border border-white/15 flex items-center gap-1.5 shadow-lg">
            <span className="w-2 h-2 rounded-full bg-[#b57bee] animate-pulse" />
            <span className="text-white text-[10px] font-black tracking-wide">{timeLeft}s</span>
          </div>
        )}
      </div>

      {/* 📱 Bouton Publier un Short (Haut Droite) */}
      <div className="absolute top-16 md:top-4 right-4 z-30 flex items-center gap-2 pointer-events-auto">
        <Link
          href="/shorts/upload"
          onClick={e => e.stopPropagation()}
          className="px-3.5 py-1.5 rounded-full bg-gradient-to-r from-pink-600 to-[#7b2cbf] hover:from-pink-500 hover:to-[#8d35db] text-white text-[11px] font-black shadow-[0_0_15px_rgba(181,123,238,0.5)] flex items-center gap-1 active:scale-90 transition-transform border border-white/20 cursor-pointer"
        >
          <Plus size={14} />
          <span>Publier</span>
        </Link>
      </div>

      {/* 🚀 SIDEBAR DROITE : Actions TikTok-Style */}
      <div 
        onClick={e => e.stopPropagation()}
        className="absolute right-3 bottom-20 md:bottom-8 flex flex-col items-center gap-3 z-30 pointer-events-auto"
      >
        {/* Avatar Uploadeur */}
        <Link 
          href={`/channel/${media.uploaderId || ''}`} 
          className="w-11 h-11 rounded-full border-2 border-[#b57bee] overflow-hidden bg-[#222] shadow-[0_0_15px_rgba(181,123,238,0.5)] hover:scale-105 transition-transform"
        >
          {creatorInfo.image ? (
            <img src={creatorInfo.image} alt={creatorInfo.name} referrerPolicy="no-referrer" className="w-full h-full object-cover" />
          ) : (
            <div className="w-full h-full flex items-center justify-center font-black text-white text-sm bg-gradient-to-br from-pink-600 to-[#7b2cbf]">
              {(creatorInfo.name || "C")[0].toUpperCase()}
            </div>
          )}
        </Link>

        {/* Bouton Like */}
        <button onClick={handleLike} className="flex flex-col items-center gap-0.5 cursor-pointer group active:scale-90 transition-transform">
          <div className="w-11 h-11 rounded-full bg-black/60 backdrop-blur-md flex items-center justify-center border border-white/20 shadow-lg">
            <Heart size={20} className={liked ? "text-red-500 fill-red-500" : "text-white"} />
          </div>
          <span className="text-white font-black text-[10px] drop-shadow-md">{formatNumber(likeCount)}</span>
        </button>

        {/* Bouton Commentaires */}
        <Link href={`/video/${media.id}`} className="flex flex-col items-center gap-0.5 group active:scale-90 transition-transform">
          <div className="w-11 h-11 rounded-full bg-black/60 backdrop-blur-md flex items-center justify-center border border-white/20 shadow-lg">
            <MessageCircle size={20} className="text-white" />
          </div>
          <span className="text-white font-black text-[10px] drop-shadow-md">{formatNumber(media._count?.comments || 0)}</span>
        </Link>

        {/* Bouton Partager */}
        <button onClick={handleShare} className="flex flex-col items-center gap-0.5 cursor-pointer group active:scale-90 transition-transform" title="Partager (S)">
          <div className="w-11 h-11 rounded-full bg-black/60 backdrop-blur-md flex items-center justify-center border border-white/20 shadow-lg">
            <Share2 size={18} className="text-white" />
          </div>
          <span className="text-white font-bold text-[9px] drop-shadow-md">Partager</span>
        </button>

        {/* 🚩 BOUTON SIGNALER */}
        <button 
          onClick={(e) => {
            e.stopPropagation();
            onReport(media);
          }}
          className="flex flex-col items-center gap-0.5 cursor-pointer group active:scale-90 transition-transform"
          title="Signaler ce contenu"
        >
          <div className="w-11 h-11 rounded-full bg-black/60 backdrop-blur-md flex items-center justify-center border border-red-500/40 shadow-lg">
            <Flag size={17} className="text-red-400" />
          </div>
          <span className="text-red-400 font-black text-[8.5px] uppercase tracking-wider drop-shadow-md">
            Signaler
          </span>
        </button>

        {/* 🗑️ BOUTON SUPPRIMER SHORT (ADMIN UNIQUEMENT) */}
        {isAdmin && (
          <button 
            onClick={handleDeleteShort}
            disabled={isDeleting}
            className="flex flex-col items-center gap-0.5 cursor-pointer group active:scale-90 transition-transform"
            title="Supprimer ce short (Admin)"
          >
            <div className="w-11 h-11 rounded-full bg-red-600/40 backdrop-blur-md flex items-center justify-center border border-red-500 shadow-[0_0_15px_rgba(239,68,68,0.5)]">
              {isDeleting ? (
                <Loader2 size={16} className="text-white animate-spin" />
              ) : (
                <Trash2 size={16} className="text-white" />
              )}
            </div>
            <span className="text-red-400 font-black text-[8.5px] uppercase tracking-wider drop-shadow-md">
              Supprimer
            </span>
          </button>
        )}

        {/* Bouton Regarder Intégrale */}
        <Link href={`/video/${media.id}`} className="flex flex-col items-center gap-0.5 group mt-0.5 active:scale-90 transition-transform">
          <div className="w-11 h-11 rounded-full bg-gradient-to-r from-pink-600 to-[#7b2cbf] flex items-center justify-center shadow-[0_0_20px_rgba(181,123,238,0.6)]">
            <Play size={18} className="text-white fill-white ml-0.5" />
          </div>
          <span className="text-white font-black text-[9px] drop-shadow-md">Voir HD</span>
        </Link>
      </div>

      {/* 📌 Informations du Short (Bas Gauche) */}
      <div 
        onClick={e => e.stopPropagation()}
        className="absolute left-3.5 bottom-20 md:bottom-8 right-16 z-30 pointer-events-auto space-y-2"
      >
        {/* Encart Partenaire / CrakRevenue / Profil Exclusif */}
        <div className="flex items-center gap-2 flex-wrap">
          <Link
            href="/premium"
            className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-gradient-to-r from-amber-500/20 to-purple-500/20 border border-amber-500/50 text-amber-300 text-[10px] font-black backdrop-blur-md hover:scale-105 active:scale-95 transition-all shadow-lg"
          >
            <Flame size={12} className="text-amber-400 fill-amber-400 animate-pulse" />
            <span>Offre VIP & Exclusivités</span>
            <ExternalLink size={10} className="text-amber-400/80" />
          </Link>
        </div>

        <div className="font-black text-sm flex items-center gap-2">
          <span className="text-[#b57bee] drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] font-black">
            {creatorInfo.handle}
          </span>
          {media.isPremium && <Crown size={13} className="text-amber-400" />}
        </div>

        <h2 className="text-white text-xs sm:text-sm font-bold line-clamp-2 leading-snug drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] max-w-[90%]">
          {media.title}
        </h2>

        {/* Badges Catégorie + Vrai compteur de vues dynamique */}
        <div className="flex items-center gap-2 pt-0.5 flex-wrap">
          {media.category && (
            <span className="text-[10px] font-black text-purple-300 bg-black/80 border border-[#b57bee]/40 px-2.5 py-0.5 rounded-full backdrop-blur shadow">
              {media.category.name}
            </span>
          )}
          <span className="flex items-center gap-1 text-[10px] font-bold text-white/90 drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] bg-black/60 px-2.5 py-0.5 rounded-full border border-white/10 backdrop-blur">
            <Eye size={12} className="text-[#b57bee]" /> 
            <span>{formatNumber(viewsCount)} vues</span>
          </span>
        </div>
      </div>

      {/* ⏱️ Barre de progression interactive Scrubber (Bas de vidéo) */}
      <div 
        onClick={handleScrubberClick}
        className="absolute bottom-0 left-0 right-0 h-1.5 md:h-2 bg-white/20 hover:bg-white/30 z-30 cursor-pointer transition-all"
        title="Progression"
      >
        <div 
          className="h-full bg-gradient-to-r from-pink-500 to-[#b57bee] relative transition-all duration-150 ease-linear shadow-[0_0_10px_rgba(181,123,238,0.8)]"
          style={{ width: `${progressPercent}%` }}
        >
          <div className="absolute right-0 top-1/2 -translate-y-1/2 w-2.5 h-2.5 rounded-full bg-white shadow" />
        </div>
      </div>

    </div>
  );
}

const WATCHED_KEY = "shorts_watched_ids";

export function ShortsFeed({ videos, isPremium }: { videos: any[]; isPremium: boolean }) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const [reportingMedia, setReportingMedia] = useState<any | null>(null);
  const isLoadingMore = useRef(false);

  // Mémoire son globale persistante
  const [globalMuted, setGlobalMuted] = useState(true);

  // Mode Auto-Scroll (Passer au short suivant automatiquement)
  const [autoScroll, setAutoScroll] = useState(false);

  // Initialisation ordonnée : les vidéos non vues en tête
  const [videoList, setVideoList] = useState<any[]>(() => {
    if (typeof window !== "undefined") {
      try {
        const raw = localStorage.getItem(WATCHED_KEY);
        if (raw) {
          const watched = new Set<string>(JSON.parse(raw));
          if (watched.size > 0) {
            const unseen = videos.filter((v: any) => !watched.has(v.id));
            if (unseen.length > 0) {
              const seen = videos.filter((v: any) => watched.has(v.id));
              return [...unseen, ...seen];
            }
          }
        }
      } catch {}
    }
    return videos;
  });

  useEffect(() => {
    try {
      const savedMute = localStorage.getItem("shorts_muted");
      if (savedMute !== null) {
        setGlobalMuted(savedMute === "true");
      }
      const savedAuto = localStorage.getItem("shorts_auto_scroll");
      if (savedAuto !== null) {
        setAutoScroll(savedAuto === "true");
      }
    } catch {}
  }, []);

  const toggleAutoScroll = () => {
    const next = !autoScroll;
    setAutoScroll(next);
    try {
      localStorage.setItem("shorts_auto_scroll", next ? "true" : "false");
    } catch {}
    toast(next ? "Lecture auto activée : passe au short suivant à la fin" : "Mode boucle activé", "info");
  };

  // Enregistrement d'un short vu dans le localStorage
  const markAsWatched = useCallback((id: string) => {
    if (!id || typeof window === "undefined") return;
    try {
      const raw = localStorage.getItem(WATCHED_KEY);
      const list: string[] = raw ? JSON.parse(raw) : [];
      if (!list.includes(id)) {
        list.push(id);
        if (list.length > 3000) list.shift();
        localStorage.setItem(WATCHED_KEY, JSON.stringify(list));
      }
    } catch {}
  }, []);

  // Chargement des Shorts non encore vus depuis l'API
  const fetchMoreShorts = useCallback(async (isResetCheck: boolean = false) => {
    if (isLoadingMore.current || typeof window === "undefined") return;
    isLoadingMore.current = true;
    try {
      const raw = localStorage.getItem(WATCHED_KEY);
      const watchedList: string[] = raw ? JSON.parse(raw) : [];
      const excludeParam = encodeURIComponent(watchedList.join(","));

      const res = await fetch(`/api/shorts?limit=40&exclude=${excludeParam}`);
      if (!res.ok) return;
      const data = await res.json();

      if (data?.videos && data.videos.length > 0) {
        if (data.allSeen) {
          // Tous les shorts du catalogue ont été vus ! Réinitialiser la boucle
          try {
            localStorage.removeItem(WATCHED_KEY);
          } catch {}
          toast("Tu as vu tous les Shorts ! Relecture depuis le début 🎬", "info");
          if (isResetCheck) {
            setVideoList(data.videos);
            setActiveIndex(0);
          } else {
            setVideoList((prev) => [...prev, ...data.videos]);
          }
        } else {
          setVideoList((prev) => {
            const existingIds = new Set(prev.map((v: any) => v.id));
            const fresh = data.videos.filter((v: any) => !existingIds.has(v.id));
            return fresh.length > 0 ? [...prev, ...fresh] : prev;
          });
        }
      }
    } catch (err) {
      console.error("fetchMoreShorts error:", err);
    } finally {
      isLoadingMore.current = false;
    }
  }, []);

  // Détection au montage si tout le premier lot a déjà été vu
  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const raw = localStorage.getItem(WATCHED_KEY);
      if (raw) {
        const watched = new Set<string>(JSON.parse(raw));
        const unseen = videos.filter((v) => !watched.has(v.id));
        if (unseen.length < 5) {
          fetchMoreShorts(unseen.length === 0);
        }
      }
    } catch {}
  }, [videos, fetchMoreShorts]);

  // Si on approche de la fin de liste -> précharger le lot suivant
  useEffect(() => {
    if (activeIndex >= videoList.length - 4 && videoList.length > 0) {
      fetchMoreShorts(false);
    }
  }, [activeIndex, videoList.length, fetchMoreShorts]);

  const scrollToIndex = useCallback((index: number) => {
    if (!containerRef.current || index < 0 || index >= videoList.length) return;
    const itemHeight = containerRef.current.clientHeight;
    containerRef.current.scrollTo({
      top: index * itemHeight,
      behavior: "smooth",
    });
    setActiveIndex(index);
  }, [videoList.length]);

  const handleNext = useCallback(() => {
    if (activeIndex < videoList.length - 1) {
      const current = videoList[activeIndex];
      if (current) markAsWatched(current.id);
      scrollToIndex(activeIndex + 1);
    }
  }, [activeIndex, videoList, markAsWatched, scrollToIndex]);

  // Raccourcis clavier complets Desktop (Flèches, Espace, M, L)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Éviter si l'utilisateur tape dans un input
      if (["INPUT", "TEXTAREA"].includes((e.target as HTMLElement)?.tagName)) return;

      if (e.key === "ArrowDown" || e.key.toLowerCase() === "j") {
        e.preventDefault();
        scrollToIndex(activeIndex + 1);
      } else if (e.key === "ArrowUp" || e.key.toLowerCase() === "k") {
        e.preventDefault();
        scrollToIndex(activeIndex - 1);
      } else if (e.key.toLowerCase() === "m") {
        e.preventDefault();
        const next = !globalMuted;
        setGlobalMuted(next);
        try { localStorage.setItem("shorts_muted", next ? "true" : "false"); } catch {}
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [activeIndex, videoList.length, globalMuted, scrollToIndex]);

  // Détection du Short Actif via IntersectionObserver
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const items = container.querySelectorAll("[data-index]");
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && entry.intersectionRatio >= 0.6) {
            const index = Number(entry.target.getAttribute("data-index"));
            setActiveIndex(index);
          }
        });
      },
      { root: container, threshold: 0.45 }
    );

    items.forEach((item) => observer.observe(item));
    return () => observer.disconnect();
  }, [videoList, activeIndex]);

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const container = e.currentTarget;
    const scrollPos = container.scrollTop;
    const itemHeight = container.clientHeight;
    const index = Math.round(scrollPos / itemHeight);
    if (index !== activeIndex && index >= 0 && index < videoList.length) {
      setActiveIndex(index);
    }
  };

  if (!videoList.length) {
    return (
      <div className="h-[100dvh] md:h-[calc(100vh-96px)] w-full flex items-center justify-center bg-black text-white p-6">
        <div className="max-w-md w-full text-center space-y-5 bg-[#12080b] border border-[#2e1217] rounded-3xl p-8 shadow-2xl animate-fade-in">
          <div className="w-20 h-20 rounded-3xl bg-gradient-to-br from-pink-600/20 to-[#7b2cbf]/30 border border-[#b57bee]/40 flex items-center justify-center mx-auto text-[#b57bee] shadow-[0_0_25px_rgba(181,123,238,0.3)]">
            <Smartphone size={36} />
          </div>
          <div>
            <h2 className="text-xl font-black text-white">Le Feed Shorts est Ouvert !</h2>
            <p className="text-xs text-[#c4b5d4] mt-2 leading-relaxed">
              Cet espace est 100% dédié aux vidéos courtes verticales (TikTok-style) publiées par les membres et modèles. Sois le premier à publier un Short !
            </p>
          </div>
          <div className="flex flex-col gap-2.5 pt-2">
            <Link
              href="/shorts/upload"
              className="w-full py-3.5 rounded-2xl bg-gradient-to-r from-pink-600 to-[#7b2cbf] hover:from-pink-500 hover:to-[#8d35db] text-white font-black text-xs shadow-[0_0_25px_rgba(181,123,238,0.4)] hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center justify-center gap-2"
            >
              <Smartphone size={16} />
              <span>Publier le 1er Short 📱</span>
            </Link>
            <Link
              href="/"
              className="w-full py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-xs font-bold text-[#aaaaaa] hover:text-white transition-all"
            >
              ← Retour au catalogue principal
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="relative w-full h-[100dvh] md:h-[calc(100vh-96px)] bg-black overflow-hidden">
      
      {/* 🎛️ Barre supérieure d'options globales (Desktop / Tablette) */}
      <div className="hidden sm:flex items-center gap-3 fixed top-24 right-4 sm:right-8 z-40">
        {/* Toggle Auto-Scroll vs Loop */}
        <button
          onClick={toggleAutoScroll}
          className={`flex items-center gap-1.5 px-3.5 py-2 rounded-full border text-xs font-bold transition-all backdrop-blur-md shadow-lg ${
            autoScroll 
              ? "bg-[#7b2cbf] border-[#b57bee] text-white shadow-[0_0_20px_rgba(181,123,238,0.5)]" 
              : "bg-black/60 border-white/20 text-white/80 hover:text-white hover:bg-black/80"
          }`}
          title={autoScroll ? "Désactiver le défilement auto" : "Activer le défilement auto (passe au short suivant)"}
        >
          {autoScroll ? <ArrowDownCircle size={14} /> : <Repeat size={14} />}
          <span>{autoScroll ? "Auto-Next : ON" : "Boucle"}</span>
        </button>

        <Link
          href="/shorts/upload"
          className="flex items-center gap-1.5 px-4 py-2 rounded-full bg-gradient-to-r from-pink-600 to-[#7b2cbf] hover:from-pink-500 hover:to-[#8d35db] text-white text-xs font-black shadow-[0_0_25px_rgba(181,123,238,0.6)] border border-white/20 hover:scale-105 transition-all"
        >
          <Plus size={15} />
          <span>Créer un Short</span>
        </Link>
      </div>

      {/* 📱 Container Défilant Vertical Snap (TikTok style) */}
      <div
        ref={containerRef}
        onScroll={handleScroll}
        className="w-full h-full overflow-y-scroll snap-y snap-mandatory scrollbar-hide bg-black relative touch-pan-y"
        style={{
          scrollSnapType: "y mandatory",
          WebkitOverflowScrolling: "touch",
          overscrollBehaviorY: "contain",
        }}
      >
        {videoList.map((media, index) => (
          <div
            key={media.id}
            data-index={index}
            className="w-full h-[100dvh] md:h-[calc(100vh-96px)] snap-start snap-always relative flex items-center justify-center"
          >
            <ShortItem
              media={media}
              isPremium={isPremium}
              isActive={activeIndex === index}
              isPreload={Math.abs(activeIndex - index) <= 2}
              globalMuted={globalMuted}
              setGlobalMuted={setGlobalMuted}
              autoScroll={autoScroll}
              onNext={handleNext}
              onWatched={markAsWatched}
              onReport={(m) => setReportingMedia(m)}
              onDelete={(id) => setVideoList(prev => prev.filter(v => v.id !== id))}
            />
          </div>
        ))}
      </div>

      {/* Universal Report Modal */}
      {reportingMedia && (
        <ReportModal
          mediaId={reportingMedia.id}
          videoTitle={reportingMedia.title}
          isOpen={!!reportingMedia}
          onClose={() => setReportingMedia(null)}
        />
      )}
    </div>
  );
}
