"use client";

import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { prefetchVideoUrl } from "@/lib/videoPreload";

type ExploreVideoThumbProps = {
  src: string;
  poster?: string;
  className?: string;
};

/**
 * پیش‌نمایش زنده ویدیو در اکسپلور (مثل قبل):
 * وقتی در ویوپورت است پخش بی‌صدا می‌شود.
 */
export default function ExploreVideoThumb({
  src,
  poster,
  className,
}: ExploreVideoThumbProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  const [mounted, setMounted] = useState(false);
  const [frameReady, setFrameReady] = useState(!!poster);
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    setFrameReady(!!poster);
  }, [poster, src]);

  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        setMounted(entry?.isIntersecting ?? false);
      },
      { rootMargin: "80px 0px", threshold: 0.35 }
    );

    observer.observe(root);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    if (!mounted) return;
    prefetchVideoUrl(src, "low");
  }, [mounted, src]);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const markReady = () => {
      try {
        if (video.currentTime < 0.01) video.currentTime = 0.05;
      } catch {
        /* ignore seek errors */
      }
      setFrameReady(true);
    };

    video.addEventListener("loadeddata", markReady);
    video.addEventListener("canplay", markReady);

    return () => {
      video.removeEventListener("loadeddata", markReady);
      video.removeEventListener("canplay", markReady);
    };
  }, [src, mounted]);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    if (mounted) {
      video
        .play()
        .then(() => setPlaying(true))
        .catch(() => setPlaying(false));
    } else {
      video.pause();
      setPlaying(false);
    }
  }, [mounted, src]);

  return (
    <div ref={rootRef} className="absolute inset-0 bg-neutral-900">
      {poster && !frameReady ? (
        <Image
          src={poster}
          alt=""
          fill
          className="object-cover"
          sizes="50vw"
          unoptimized
        />
      ) : !frameReady ? (
        <div className="absolute inset-0 animate-pulse bg-neutral-800" />
      ) : null}

      {mounted ? (
        <video
          ref={videoRef}
          src={src}
          poster={poster}
          preload="auto"
          muted
          loop
          playsInline
          autoPlay
          className={cn(
            "absolute inset-0 h-full w-full object-cover transition-opacity duration-300",
            frameReady ? "opacity-100" : "opacity-0",
            className
          )}
        />
      ) : null}

      {!playing && mounted && frameReady ? (
        <div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-black/15">
          <span className="flex h-8 w-8 items-center justify-center rounded-full bg-black/45 text-[10px] text-white">
            ▶
          </span>
        </div>
      ) : null}
    </div>
  );
}
