import React, { useEffect } from "react";

const SIZE_CLASS = {
  default: "",
  wide: "ptw-modal--wide",
  xwide: "ptw-modal--xwide"
};

export default function EntityModal({
  open,
  title,
  subtitle,
  children,
  onClose,
  size = "default",
  variant = "default",
  footer = null
}) {
  useEffect(() => {
    if (!open) return undefined;
    const onKeyDown = (e) => {
      if (e.key === "Escape") onClose?.();
    };
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [open, onClose]);

  if (!open) return null;

  const sizeClass = SIZE_CLASS[size] || SIZE_CLASS.wide;

  return (
    <div
      className="swi-modal-backdrop ptw-modal-backdrop"
      role="dialog"
      aria-modal="true"
      aria-labelledby="ptw-entity-modal-title"
      onClick={onClose}
    >
      <div
        className={`swi-modal ptw-entity-modal ${sizeClass}${variant === "detail" ? " ptw-entity-modal--detail" : ""}`}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="ptw-entity-modal__accent" aria-hidden="true" />
        <header className="ptw-entity-modal__header">
          <div className="ptw-entity-modal__header-text">
            {subtitle ? (
              <span className="ptw-entity-modal__eyebrow">{subtitle}</span>
            ) : null}
            <h3 id="ptw-entity-modal-title" className="ptw-entity-modal__title">
              {title}
            </h3>
          </div>
          <button
            type="button"
            className="ptw-entity-modal__close"
            onClick={onClose}
            aria-label="Close dialog"
          >
            ×
          </button>
        </header>
        <div className="ptw-entity-modal__body">{children}</div>
        {footer ? <footer className="ptw-entity-modal__footer">{footer}</footer> : null}
      </div>
    </div>
  );
}
