import React, { useEffect, useMemo, useRef } from "react";
import { createPortal } from "react-dom";

export default function Modal({
  open,
  onClose,
  title,
  children,
  footer,
  size = "md",
  closeOnBackdrop = true,
  showClose = true,
}) {
  const onCloseRef = useRef(onClose);
  useEffect(() => {
    onCloseRef.current = onClose;
  }, [onClose]);

  const el = useMemo(() => {
    const div = document.createElement("div");
    div.setAttribute("data-modal-root", "true");
    return div;
  }, []);

  useEffect(() => {
    if (!open) return;

    document.body.appendChild(el);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const onKeyDown = (e) => {
      if (e.key === "Escape") onCloseRef.current?.();
    };

    window.addEventListener("keydown", onKeyDown);

    return () => {
      window.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = prevOverflow;
      if (el.parentNode) el.parentNode.removeChild(el);
    };
  }, [open, el]); // ✅ IMPORTANT: remove onClose from deps

  if (!open) return null;

  const maxW =
    size === "sm"
      ? "520px"
      : size === "lg"
      ? "920px"
      : size === "xl"
      ? "1120px"
      : "720px";

  const ui = (
    <div style={{ position: "fixed", inset: 0, zIndex: 9999, display: "flex", alignItems: "center", justifyContent: "center", padding: 18 }}>
      <div
        onClick={() => (closeOnBackdrop ? onCloseRef.current?.() : null)}
        style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.55)", backdropFilter: "blur(2px)" }}
      />

      <div role="dialog" aria-modal="true" style={{ position: "relative", width: "100%", maxWidth: maxW, borderRadius: 16, background: "#fff", boxShadow: "0 18px 60px rgba(0,0,0,.25)", overflow: "hidden" }}>
        {(title || showClose) && (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "14px 16px", borderBottom: "1px solid #e5e7eb" }}>
            <div style={{ fontWeight: 800, color: "#0f172a" }}>{title}</div>
            {showClose && (
              <button
                onClick={() => onCloseRef.current?.()}
                style={{ border: "1px solid #e5e7eb", background: "#fff", borderRadius: 10, padding: "6px 10px", cursor: "pointer", fontWeight: 700 }}
              >
                ✕
              </button>
            )}
          </div>
        )}

        <div style={{ padding: 16 }}>{children}</div>

        {footer && <div style={{ padding: 16, borderTop: "1px solid #e5e7eb", background: "#fafafa" }}>{footer}</div>}
      </div>
    </div>
  );

  return createPortal(ui, el);
}
