'use client';

/**
 * The 6 Nov design's modal frame (`modal.css`, `import-details.php` dialogs): Escape, the
 * backdrop and × close it (`import-details.js:450-479`). Import details' bulk dialogs (IDB4b) and
 * segment dialog (IDB4c).
 */
import { useEffect } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { cn } from '@/lib/utils/cn';

/** The design's modal frame (`modal.css`): Escape, the backdrop and × close it (js:450-479). */
export function DesignModal({
  id,
  title,
  large,
  footerClass,
  footer,
  onClose,
  children,
}: {
  id: string;
  title: React.ReactNode;
  large?: boolean;
  footerClass: string;
  footer: React.ReactNode;
  onClose: () => void;
  children: React.ReactNode;
}) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div
      className="modal-backdrop is-open"
      id={id}
      aria-hidden="false"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className={cn('modal', large && 'modal--lg')}
        role="dialog"
        aria-modal="true"
        aria-labelledby={`${id}Title`}
      >
        <div className="modal__header">
          <h2 className="modal__title" id={`${id}Title`}>
            {title}
          </h2>
          <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-18" />
          </button>
        </div>
        <div className="modal__body">{children}</div>
        <div className={cn('modal__footer', footerClass)}>{footer}</div>
      </div>
    </div>
  );
}
