import { ReactNode } from "react";
import Portal from "./Portal";
import { X } from "lucide-react";

interface ModalProps {
  open: boolean;
  onClose: () => void;
  title?: string;
  children: ReactNode;
  width?: string;
}

export default function Modal({ open, onClose, title, children, width = "w-[360px]" }: ModalProps) {
  if (!open) return null;

  return (
    <Portal>
      <div
        className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 animate-fade-in"
        onClick={onClose}
      >
        <div
          onClick={(e) => e.stopPropagation()}
          className={`bg-white rounded-2xl max-w-[90vw] ${width} max-h-[90vh] flex flex-col animate-scale-in`}
        >
          <header className="relative px-4 pt-4 pb-3 text-center shrink-0">
            {title && <h2 className="text-xl font-semibold">{title}</h2>}
            <button
              onClick={onClose}
              aria-label="Close"
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 cursor-pointer"
            >
              <X />
            </button>
            <div className="mt-4! border-b" />
          </header>

          <div className="overflow-y-auto flex-1">
            {children}
          </div>
        </div>
      </div>
    </Portal>
  );
}