"use client";

import { ReactNode, useEffect } from "react";
import { X } from "lucide-react";

type ModalProps = {
  open: boolean;
  onClose: () => void;
  title: ReactNode;
  /** Body content. Can include <b>...</b> for emphasis. */
  children: ReactNode;
  /** Footer slot. Pass v5-btn nodes. */
  footer?: ReactNode;
  /** Visual width (default 420px). */
  maxWidth?: number;
  /** Disable backdrop click to close. */
  hardClose?: boolean;
};

export function Modal({ open, onClose, title, children, footer, maxWidth = 420, hardClose = false }: ModalProps) {
  // Close on Escape
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape" && !hardClose) onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose, hardClose]);

  if (!open) return null;

  return (
    <div
      className="v5-overlay"
      onClick={() => {
        if (!hardClose) onClose();
      }}
    >
      <div
        className="v5-modal"
        style={{ maxWidth }}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
      >
        <div className="v5-modal-head">
          <div className="v5-modal-title">{title}</div>
          <button
            className="v5-btn ghost sm"
            onClick={onClose}
            aria-label="닫기"
            style={{ width: 28, height: 28, padding: 0 }}
          >
            <X />
          </button>
        </div>
        <div className="v5-modal-body">{children}</div>
        {footer && <div className="v5-modal-foot">{footer}</div>}
      </div>
    </div>
  );
}
