"use client";

import { useEffect, useRef, ReactNode } from "react";
import { motion, AnimatePresence } from "framer-motion";

type ModalProps = {
  isOpen: boolean;
  onClose: () => void;
  children: ReactNode;
};

export default function FullscreenModal({
  isOpen,
  onClose,
  children,
}: ModalProps) {
  const wrapperRef = useRef<HTMLDivElement>(null);

  // Blokuje scroll tła
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }

    return () => {
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  // ESC close
  useEffect(() => {
    const handleEsc = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };

    if (isOpen) {
      document.addEventListener("keydown", handleEsc);
    }

    return () => {
      document.removeEventListener("keydown", handleEsc);
    };
  }, [isOpen, onClose]);

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          tabIndex={-1}
          className="fixed inset-0 z-[9999] bg-black/40 backdrop-blur-sm flex items-center justify-center px-4"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
        >
          <motion.div
            ref={wrapperRef}
            onClick={(e) => e.stopPropagation()}
            className="relative w-full max-w-[100%] sm:max-w-5xl max-h-[90vh] overflow-y-auto will-change-scroll lenis lenis-smooth scrollbar-none"
            initial={{ scale: 0.95, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.95, opacity: 0 }}
            transition={{ duration: 0.3 }}
          >
            {children}
          </motion.div>

          <button
            onClick={onClose}
            className="absolute top-4 right-4 text-white text-4xl z-[10000] hover:text-gray-300 transition"
            aria-label="Zamknij modal"
          >
            &times;
          </button>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
