/**
 * <Modal> — diálogo centrado, para confirmações e formulários curtos.
 *
 * Cópia do NetScreen AI (public/js/components/modal.jsx). Fica acima do
 * <Drawer> (z-60 contra z-50) e pode abrir por cima dele. Um modal nunca
 * abre outro modal.
 */

function Modal({ aberto, onFechar, titulo, papel = 'dialog', acoes, children }) {
  const painelRef = React.useRef(null);
  const tituloId = React.useId();
  const descricaoId = React.useId();

  useDialogo(painelRef, aberto, onFechar);

  if (!aberto) return null;

  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
      <div
        className="drawer-overlay absolute inset-0 bg-black/70"
        onClick={() => onFechar()}
        aria-hidden="true"
      />

      <div
        ref={painelRef}
        role={papel}
        aria-modal="true"
        aria-labelledby={tituloId}
        aria-describedby={descricaoId}
        tabIndex={-1}
        className="modal-panel relative w-full max-w-md border border-border bg-background outline-none"
      >
        <div className="max-h-[calc(100vh-8rem)] overflow-y-auto p-6">
          <h2 id={tituloId} className="font-display text-3xl leading-none">
            {titulo}
          </h2>
          <div id={descricaoId} className="mt-3 text-sm text-muted-foreground">
            {children}
          </div>
        </div>

        {acoes && (
          <div className="flex flex-wrap justify-end gap-2 border-t border-border p-4">{acoes}</div>
        )}
      </div>
    </div>,
    document.body
  );
}
