import React, { useEffect } from "react";
import { createPortal } from "react-dom";
import { cn } from "./cn";

export default function Modal({
  open,
  onClose,
  children,
  className,
  overlayClassName,
  closeOnOverlay = true,
  closeOnEsc = true,
  zIndex = 9999,
}) {
  useEffect(() => {
    if (!open || !closeOnEsc) return;

    const onKeyDown = (e) => {
      if (e.key === "Escape") onClose?.();
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [open, closeOnEsc, onClose]);

  if (!open) return null;

  return createPortal(
    <div className="fixed inset-0 flex items-center justify-center p-4" style={{ zIndex }}>
      <div
        className={cn("absolute inset-0 bg-black/40", overlayClassName)}
        onClick={() => {
          if (closeOnOverlay) onClose?.();
        }}
      />
      <div className={cn("relative w-full", className)} onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>,
    document.body
  );
}
