import { ReactNode, useEffect } from "react";

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

const Modal = ({ open, title, onClose, children, footer }: ModalProps) => {
  useEffect(() => {
    if (!open) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-lg rounded-lg bg-white shadow-xl"
        onClick={(event) => event.stopPropagation()}
      >
        {title ? (
          <div className="border-b border-gray-200 px-4 py-3 text-base font-semibold text-gray-900">
            {title}
          </div>
        ) : null}
        <div className="px-4 py-4 text-sm text-gray-700">{children}</div>
        {footer ? (
          <div className="flex justify-end gap-2 border-t border-gray-200 px-4 py-3">
            {footer}
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default Modal;
