'use client';

import * as React from 'react';
import { X } from 'lucide-react';

/**
 * Canonical modal shell. Native <dialog>: ESC closes, focus trapped,
 * backdrop click closes. Use the same class names everywhere for a
 * single consistent look.
 *
 * @param {{
 *   open: boolean,
 *   onClose: () => void,
 *   eyebrow?: string,
 *   title: string,
 *   tone?: 'default' | 'danger',
 *   size?: 'default' | 'wide',
 *   children: React.ReactNode,
 * }} props
 */
export default function AdminModal({ open, onClose, eyebrow, title, tone = 'default', size = 'default', children }) {
  const dialogRef = React.useRef(null);

  React.useEffect(() => {
    const node = dialogRef.current;
    if (!node) return;
    if (open && !node.open) {
      if (typeof node.showModal === 'function') node.showModal();
      else node.setAttribute('open', '');
    }
    if (!open && node.open) node.close();
  }, [open]);

  React.useEffect(() => {
    const node = dialogRef.current;
    if (!node) return undefined;
    const onCancel = (event) => {
      event.preventDefault();
      onClose();
    };
    node.addEventListener('cancel', onCancel);
    return () => node.removeEventListener('cancel', onCancel);
  }, [onClose]);

  const onBackdropClick = (event) => {
    if (event.target === dialogRef.current) onClose();
  };

  return (
    <dialog
      ref={dialogRef}
      className={`agents-modal${size === 'wide' ? ' agents-modal--wide' : ''}`}
      onClick={onBackdropClick}
    >
      {open ? (
        <div
          className={`agents-modal-card${tone === 'danger' ? ' agents-modal-card--danger' : ''}`}
          onClick={(e) => e.stopPropagation()}
        >
          <header className="agents-modal-head">
            <div>
              {eyebrow ? <span className="admin-kicker">{eyebrow}</span> : null}
              <h2>{title}</h2>
            </div>
            <button
              type="button"
              className="agents-modal-close"
              onClick={onClose}
              aria-label="Close"
            >
              <X size={14} />
            </button>
          </header>
          {children}
        </div>
      ) : null}
    </dialog>
  );
}
