"use client";

import { ReactNode, useEffect } from "react";

type Size = "sm" | "md" | "lg" | "xl";

interface Props {
  open: boolean;
  onClose: () => void;
  size?: Size;
  title?: string;
  children: ReactNode;
  footer?: ReactNode;
  hideCloseButton?: boolean;
}

const SIZE_CLASSES: Record<Size, string> = {
  sm: "w-[min(90vw,420px)] max-h-[80vh]",
  md: "w-[min(90vw,640px)] max-h-[85vh]",
  lg: "w-[min(95vw,900px)] max-h-[90vh]",
  xl: "w-[min(98vw,1200px)] max-h-[95vh]",
};

export default function PopModal({
  open,
  onClose,
  size = "md",
  title,
  children,
  footer,
  hideCloseButton = false,
}: Props) {
  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose]);

  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
      onClick={onClose}
    >
      <div
        className={`${SIZE_CLASSES[size]} bg-white rounded-2xl shadow-xl flex flex-col`}
        onClick={(e) => e.stopPropagation()}
      >
        {(title != null || !hideCloseButton) && (
          <header className="flex items-center justify-between px-5 py-4 border-b border-gray-200 shrink-0">
            {title != null && (
              <h2 className="text-lg font-semibold text-gray-900">{title}</h2>
            )}
            {!hideCloseButton && (
              <button
                type="button"
                onClick={onClose}
                className="ml-auto w-10 h-10 flex items-center justify-center rounded-xl text-gray-500 hover:bg-gray-100 text-xl font-medium"
                aria-label="닫기"
              >
                &times;
              </button>
            )}
          </header>
        )}
        <main className="flex-1 overflow-y-auto p-4">{children}</main>
        {footer && (
          <footer className="border-t border-gray-200 p-4 shrink-0">
            {footer}
          </footer>
        )}
      </div>
    </div>
  );
}
