"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import type { NordenFilm, SupportedLocale } from "@/lib/media-library";

interface MediaFilmPlayerProps {
  film: NordenFilm;
  active?: boolean;
  controls?: boolean;
  autoplay?: boolean;
  loop?: boolean;
  className?: string;
  onEnded?: () => void;
  locale?: SupportedLocale;
  showPoster?: boolean;
}

export default function MediaFilmPlayer({
  film,
  active = true,
  controls = false,
  autoplay = false,
  loop = false,
  className = "",
  onEnded,
  locale = "tr",
  showPoster = true,
}: MediaFilmPlayerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [visible, setVisible] = useState(true);
  const [reducedMotion, setReducedMotion] = useState(false);
  const [motionPreferenceReady, setMotionPreferenceReady] = useState(false);
  const [manuallyStarted, setManuallyStarted] = useState(false);
  const [posterSrc, setPosterSrc] = useState(film.poster);
  const [mediaError, setMediaError] = useState(false);

  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const sync = () => {
      setReducedMotion(query.matches);
      setMotionPreferenceReady(true);
    };
    sync();
    query.addEventListener("change", sync);
    return () => query.removeEventListener("change", sync);
  }, []);

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

    const observer = new IntersectionObserver(
      ([entry]) => setVisible(entry.isIntersecting),
      { threshold: 0.15 },
    );
    observer.observe(video);
    return () => observer.disconnect();
  }, []);

  const shouldAttachSource = active && motionPreferenceReady && (!reducedMotion || manuallyStarted || controls);
  const source = shouldAttachSource
    ? film.mobileSrc
      ? undefined
      : film.desktopSrc
    : undefined;

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

    if (!active || !visible || reducedMotion || !autoplay || !motionPreferenceReady) {
      video.pause();
      return;
    }

    void video.play().catch(() => {
      // Browser autoplay policies may reject playback; the poster remains visible.
    });
  }, [active, autoplay, reducedMotion, visible, film.id, motionPreferenceReady]);

  return (
    <div className={`relative overflow-hidden ${className}`} aria-label={film.title[locale]}>
      {showPoster ? (
        <Image
          src={posterSrc}
          alt=""
          fill
          sizes="100vw"
          className="object-cover"
          onError={() => {
            if (film.posterFallback && posterSrc !== film.posterFallback) setPosterSrc(film.posterFallback);
          }}
        />
      ) : null}
      {!mediaError ? (
        <video
          key={film.id}
          ref={videoRef}
          className="absolute inset-0 h-full w-full object-cover"
          muted={autoplay}
          loop={loop}
          playsInline
          controls={controls}
          preload={active ? "metadata" : "none"}
          src={source}
          onPlay={() => setManuallyStarted(true)}
          onCanPlay={() => setMediaError(false)}
          onError={() => setMediaError(true)}
          onEnded={onEnded}
          aria-label={film.title[locale]}
        >
          {shouldAttachSource && film.mobileSrc ? (
            <>
              <source src={film.mobileSrc} media="(max-width: 767px)" type="video/mp4" />
              <source src={film.desktopSrc} type="video/mp4" />
            </>
          ) : null}
        </video>
      ) : null}
    </div>
  );
}
