"use client";
import { useState, useRef, useCallback } from "react";
import Link from "next/link";
import { Play, BadgeCheck } from "lucide-react";
import { motion } from "framer-motion";
import { formatNumber, formatDuration, translateTitleFr, resolveModelProfile } from "@/lib/utils";
import { useTranslation } from "@/components/TranslationProvider";

function buildFrameGetter(url: string | null): ((frame: number) => string) | null {
  if (!url) return null;
  const match = url.match(/^(.*?)(\d+)(\.jpg)$/i);
  if (!match) return null;
  const [, base, , ext] = match;
  return (frame: number) => `${base}${frame}${ext}`;
}

function randomFrameSequence(): number[] {
  return Array.from({ length: 20 }, () => Math.floor(Math.random() * 16) + 1);
}

function getCountryCode(title: string, tags?: string | null): string {
  const text = `${title} ${tags || ""}`.toLowerCase();
  if (/french|francais|francaise|français|france|paris|vostfr|vf|beurette|jacquie|michel|salope|lesbienne/.test(text)) return "fr";
  if (/japanese|japan|jav|hentai|tokyo|asian/.test(text)) return "jp";
  if (/german|deutsch|deutschland|berlin/.test(text)) return "de";
  if (/spanish|espanol|español|latina|mexican|spain|madrid/.test(text)) return "es";
  if (/italian|italiano|italiana|italy|roma/.test(text)) return "it";
  if (/russian|russia|moscow/.test(text)) return "ru";
  return "us";
}

interface VideoCardProps {
  media: {
    id: string;
    title: string;
    titleFr?: string | null;
    thumbnailUrl: string | null;
    duration: number | null;
    views: number;
    tags?: string | null;
    category?: { name: string; slug: string } | null;
    uploader?: { name: string | null; image: string | null; isVerified?: boolean } | null;
  };
}

export function VideoCard({ media }: VideoCardProps) {
  if (!media || !media.id) return null;
  const { lang } = useTranslation();
  const displayTitle = translateTitleFr(media.title, media.titleFr);
  const modelProfile = resolveModelProfile(media.title, media.uploader, media.id);
  const [currentSrc, setCurrentSrc] = useState(media.thumbnailUrl || "");
  const [isHovered, setIsHovered] = useState(false);
  const [frameIndex, setFrameIndex] = useState(0);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const frameGetterRef = useRef(buildFrameGetter(media.thumbnailUrl));
  const sequenceRef = useRef<number[]>([]);
  const indexRef = useRef(0);
  const pressTimer = useRef<NodeJS.Timeout | null>(null);
  const isLongPress = useRef(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const hoverTimeout = useRef<NodeJS.Timeout | null>(null);

  // 3D tilt
  const cardRef = useRef<HTMLDivElement>(null);
  const [tilt, setTilt] = useState({ x: 0, y: 0 });

  const handleTiltMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    const rect = cardRef.current?.getBoundingClientRect();
    if (!rect) return;
    const cx = (e.clientX - rect.left) / rect.width - 0.5;
    const cy = (e.clientY - rect.top) / rect.height - 0.5;
    setTilt({ x: cy * -7, y: cx * 7 });
  }, []);

  const handleTiltLeave = useCallback(() => setTilt({ x: 0, y: 0 }), []);

  const startPreview = useCallback(() => {
    setIsHovered(true);
    const getter = frameGetterRef.current;
    if (!getter) return;
    sequenceRef.current = randomFrameSequence();
    indexRef.current = 0;
    const tick = () => {
      const idx = indexRef.current % sequenceRef.current.length;
      setCurrentSrc(getter(sequenceRef.current[idx]));
      setFrameIndex(idx);
      indexRef.current++;
    };
    tick();
    intervalRef.current = setInterval(tick, 1000);
  }, []);

  const stopPreview = useCallback(() => {
    setIsHovered(false);
    if (intervalRef.current) clearInterval(intervalRef.current);
    setCurrentSrc(media.thumbnailUrl || "");
    setFrameIndex(0);
  }, [media.thumbnailUrl]);

  const handleMouseEnter = () => {
    hoverTimeout.current = setTimeout(() => { setIsExpanded(true); startPreview(); }, 400);
  };

  const handleMouseLeave = () => {
    if (hoverTimeout.current) clearTimeout(hoverTimeout.current);
    setIsExpanded(false);
    stopPreview();
    handleTiltLeave();
  };

  const handleTouchStart = () => {
    isLongPress.current = false;
    pressTimer.current = setTimeout(() => {
      isLongPress.current = true;
      setIsExpanded(true);
      startPreview();
      if (typeof window !== "undefined" && window.navigator?.vibrate) window.navigator.vibrate(50);
    }, 400);
  };

  const handleTouchEnd = () => {
    if (pressTimer.current) clearTimeout(pressTimer.current);
    if (isLongPress.current) { setIsExpanded(false); stopPreview(); }
  };

  const handleClick = (e: React.MouseEvent) => {
    if (isLongPress.current) { e.preventDefault(); isLongPress.current = false; }
  };

  const hasPreview = !!frameGetterRef.current;

  return (
    <motion.div
      ref={cardRef}
      className="relative w-full group"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      onMouseMove={handleTiltMove}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
      onTouchMove={handleTouchEnd}
      onClick={handleClick}
      onContextMenu={(e) => e.preventDefault()}
      style={{
        transform: `perspective(800px) rotateX(${tilt.x}deg) rotateY(${tilt.y}deg)`,
        transition: isHovered ? "transform 0.08s ease-out" : "transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94)",
        transformStyle: "preserve-3d",
      }}
      whileHover={{ scale: 1.02 }}
      transition={{ duration: 0.2, ease: "easeOut" }}
    >
      <Link href={`/video/${media.id}`} className="block select-none relative" style={{ WebkitTouchCallout: "none" }}>

        {/* Thumbnail */}
        <div 
          style={{ borderRadius: "var(--custom-video-radius, 18px)" }}
          className="relative aspect-video overflow-hidden mb-2.5 border border-white/5 group-hover:border-[#e05a68]/60 transition-all duration-300 shadow-md group-hover:shadow-[0_0_20px_rgba(224,90,104,0.25)]"
        >
          <img
            src={isHovered && hasPreview ? currentSrc : (media.thumbnailUrl || "https://images.unsplash.com/photo-1616423640778-28d1b53229bd?w=800&q=80")}
            alt={media.title}
            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 ease-out"
            draggable={false}
          />

          {/* Dark overlay on hover */}
          <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />

          {/* Play button */}
          <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300">
            <div className="w-11 h-11 rounded-full flex items-center justify-center"
              style={{ background: "rgba(224,90,104,0.9)", boxShadow: "0 0 24px rgba(224,90,104,0.7), 0 0 48px rgba(224,90,104,0.3)" }}>
              <Play size={18} className="text-white fill-white ml-0.5" />
            </div>
          </div>

          {/* NOUVEAU badge */}
          <div className="absolute top-2 left-2 bg-gradient-to-r from-rose-500 to-[#c93f52] text-white text-[8px] md:text-[9px] font-black px-2 py-0.5 rounded-full tracking-wider uppercase"
            style={{ boxShadow: "0 0 8px rgba(224,90,104,0.5)" }}>
            Nouveau
          </div>

          {/* Flag */}
          <div className="absolute top-2 right-2 flex items-center justify-center w-5 h-3.5 bg-black/60 backdrop-blur-md rounded overflow-hidden border border-white/20">
            <img src={`https://flagcdn.com/w40/${getCountryCode(media.title, media.tags)}.png`} alt="flag" className="w-full h-full object-cover" />
          </div>

          {/* Duration / Short Badge */}
          {media.duration ? (
            <span className={`absolute bottom-2 right-2 backdrop-blur-md text-white text-[10px] font-bold px-2 py-0.5 rounded-md z-10 border ${
              media.duration <= 60 
                ? "bg-[#e05a68]/90 border-[#e05a68] shadow-[0_0_10px_#e05a68] flex items-center gap-1" 
                : "bg-black/80 border-white/10"
            }`}>
              {media.duration <= 60 ? `⚡ ${formatDuration(media.duration)}` : formatDuration(media.duration)}
            </span>
          ) : null}

          {/* Preview progress — neon gradient */}
          {isHovered && hasPreview && (
            <div className="absolute bottom-0 left-0 w-full h-[3px] bg-black/40">
              <div className="h-full rounded-full transition-all duration-300 ease-linear"
                style={{
                  width: `${((frameIndex + 1) / 20) * 100}%`,
                  background: "linear-gradient(90deg, #c93f52, #e05a68)",
                  boxShadow: "0 0 6px rgba(224,90,104,0.9)",
                }} />
            </div>
          )}
        </div>

        {/* Info */}
        <div className="flex gap-2 px-0.5">
          <div className="relative flex-shrink-0 mt-0.5">
            <div className="w-6 h-6 md:w-8 md:h-8 rounded-full border border-[#c93f52]/50 group-hover:border-[#e05a68] group-hover:shadow-[0_0_8px_rgba(224,90,104,0.5)] transition-all duration-300 overflow-hidden"
              style={{ background: "rgba(14,8,10,0.9)" }}>
              <img src={modelProfile.avatar} alt={modelProfile.name} className="w-full h-full object-cover" />
            </div>
            <div className="hidden md:block absolute -bottom-1.5 -right-1 bg-[#c93f52] text-white text-[7px] font-black px-1 rounded border border-black shadow">
              #{(media.id.split('').reduce((a, c) => a + c.charCodeAt(0), 0) % 499) + 1}
            </div>
          </div>

          <div className="flex-1 min-w-0">
            <h3 
              style={{ fontSize: "var(--custom-video-title-size, 13px)" }}
              className="font-bold leading-snug line-clamp-2 text-white/90 group-hover:text-white transition-colors duration-200"
            >
              {media.title}
            </h3>
            <div 
              style={{ fontSize: "var(--custom-video-meta-size, 11px)" }}
              className="flex items-center gap-1.5 font-medium mt-0.5 leading-none"
            >
              <span className="text-[#e2c0c5] truncate max-w-[100px] md:max-w-[120px] font-bold group-hover:text-[#e05a68] transition-colors">{modelProfile.name}</span>
              <BadgeCheck size={11} className="text-[#e05a68] flex-shrink-0" fill="currentColor" />
              <span className="text-[#333344]">·</span>
              <span className="text-[#9e737a]">{formatNumber(media.views)} vues</span>
            </div>
          </div>

          <button className="flex-shrink-0 text-[#9e737a] hover:text-[#e05a68] p-0.5 h-fit transition-colors duration-200" onClick={(e) => e.preventDefault()}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
            </svg>
          </button>
        </div>
      </Link>
    </motion.div>
  );
}
