"use client";

import { createPortal } from "react-dom";
import { X } from "lucide-react";
import styles from "./Modal.module.css";

interface ModalProps {
  open: boolean;
  title: string;
  onClose: () => void;
  children: React.ReactNode;
  footer?: React.ReactNode;
  size?: "sm" | "md" | "lg" | "xl";
}

const SIZE_TO_MAX_WIDTH: Record<string, number> = { sm: 400, md: 560, lg: 720, xl: 900 };

export default function Modal({ open, title, onClose, children, footer, size = "md" }: ModalProps) {
  if (!open || typeof document === "undefined") return null;

  return createPortal(
    <>
      <div className={styles.overlay} onClick={onClose} />
      <div className={styles.wrapper}>
        <div
          className={styles.modal}
          onClick={(e) => e.stopPropagation()}
          style={{ maxWidth: SIZE_TO_MAX_WIDTH[size] }}
        >
          <div className={styles.header}>
            <span className={styles.title}>{title}</span>
            <button type="button" className={styles.closeBtn} onClick={onClose} aria-label="Fermer">
              <X size={18} />
            </button>
          </div>
          <div className={styles.body}>{children}</div>
          {footer && <div className={styles.footer}>{footer}</div>}
        </div>
      </div>
    </>,
    document.body,
  );
}
