"use client";
import { motion, AnimatePresence } from "framer-motion";
import { ReactNode } from "react";
import {
  MODAL_OVERLAY_VARIANTS,
  MODAL_CONTENT_VARIANTS,
} from "./MotionConfig";
import { useMotionContext } from "./MotionProvider";

interface AnimatedModalProps {
  isOpen: boolean;
  onBackdropClick?: () => void;
  children: ReactNode;
  /** z-index for overlay/content pair */
  zIndex?: number;
  /** Extra classnames on the content wrapper */
  contentClassName?: string;
}

export function AnimatedModal({
  isOpen,
  onBackdropClick,
  children,
  zIndex = 400,
  contentClassName,
}: AnimatedModalProps) {
  const { reducedMotion } = useMotionContext();

  if (reducedMotion) {
    return isOpen ? (
      <>
        <div
          className="fixed inset-0"
          style={{ zIndex, background: "rgba(0,0,0,0.78)", backdropFilter: "blur(12px)" }}
          onClick={onBackdropClick}
        />
        <div className={`fixed inset-0 flex items-center justify-center`} style={{ zIndex: zIndex + 1 }}>
          <div className={contentClassName}>{children}</div>
        </div>
      </>
    ) : null;
  }

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Overlay */}
          <motion.div
            className="fixed inset-0"
            style={{ zIndex, background: "rgba(0,0,0,0.78)", backdropFilter: "blur(12px)" }}
            variants={MODAL_OVERLAY_VARIANTS}
            initial="hidden"
            animate="visible"
            exit="exit"
            onClick={onBackdropClick}
          />

          {/* Content */}
          <motion.div
            className="fixed inset-0 flex items-center justify-center pointer-events-none"
            style={{ zIndex: zIndex + 1 }}
            variants={MODAL_CONTENT_VARIANTS}
            initial="hidden"
            animate="visible"
            exit="exit"
          >
            <div className={`pointer-events-auto ${contentClassName ?? ""}`}>
              {children}
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
