"use client";

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

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

const SIZE_CLASS: Record<string, string> = {
  sm: "sizeSm",
  md: "sizeMd",
  lg: "sizeLg",
  xl: "sizeXl",
};

export default function Drawer({ open, title, subtitle, size = "lg", onClose, children }: DrawerProps) {
  if (!open || typeof document === "undefined") return null;

  return createPortal(
    <>
      <div className={styles.overlay} onClick={onClose} />
      <div className={`${styles.panel} ${styles[SIZE_CLASS[size]] ?? ""}`} role="dialog" aria-modal="true">
        <div className={styles.header}>
          <div>
            <h2 className={styles.title}>{title}</h2>
            {subtitle && <p className={styles.subtitle}>{subtitle}</p>}
          </div>
          <button type="button" className={styles.closeBtn} onClick={onClose} aria-label="Fermer">
            <X size={18} />
          </button>
        </div>
        <div className={styles.body}>{children}</div>
      </div>
    </>,
    document.body,
  );
}
