// src/components/storage/ModalShell.jsx
import React, { useEffect } from "react";
import { createPortal } from "react-dom";

export default function ModalShell({ open, title, onClose, children, maxWidth = "max-w-md" }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose?.();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return createPortal(
    <div
      className="fixed inset-0 z-[999998] flex items-center justify-center p-4"
      onPointerDown={(e) => {
        if (e.target === e.currentTarget) onClose?.();
      }}
    >
      <div className="absolute inset-0 bg-black/40 backdrop-blur-[2px]" />
      <div
        className={`relative w-full ${maxWidth} rounded-2xl bg-white dark:bg-[#001F3F] border border-black/10 dark:border-white/10 shadow-2xl p-4`}
        onPointerDown={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between mb-3 gap-3">
          <h3 className="font-extrabold text-black dark:text-white truncate">{title}</h3>
          <button
            type="button"
            className="px-3 py-1.5 rounded-xl shadow dark:bg-[#A1E3F919] dark:text-white border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
            onClick={onClose}
          >
            بستن
          </button>
        </div>
        {children}
      </div>
    </div>,
    document.body
  );
}
