"use client";

import { useEffect } from "react";
import { AnimatePresence, motion } from "motion/react";

export function VideoModal({
  open,
  src,
  poster,
  title,
  onClose,
}: {
  open: boolean;
  src: string;
  poster?: string;
  title: string;
  onClose: () => void;
}) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          className="video-modal"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          role="dialog"
          aria-modal="true"
          aria-label={`${title} video`}
          onClick={onClose}
        >
          <button className="video-modal__close" onClick={onClose} aria-label="Close video">CLOSE ×</button>
          <motion.div
            className="video-modal__frame"
            initial={{ scale: 0.94, y: 24 }}
            animate={{ scale: 1, y: 0 }}
            exit={{ scale: 0.96, y: 12 }}
            onClick={(e) => e.stopPropagation()}
          >
            <video src={src} poster={poster} controls autoPlay playsInline />
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
