/**
 * <Drawer> — painel de detalhe que entra pela direita.
 *
 * Regra de UI do MODULOS: header fixo, corpo com scroll, footer com acções.
 * Reutilizável em Campanhas, KB Produtos, KB FAQs e Lojas.
 *
 * Acessibilidade: role="dialog" modal, Escape fecha, o foco fica preso dentro
 * do painel enquanto está aberto e volta ao elemento que o abriu ao fechar.
 */

function Drawer({ aberto, onFechar, eyebrow, titulo, subtitulo, rodape, children }) {
  const painelRef = React.useRef(null);
  const tituloId = React.useId();

  // Escape, foco preso e devolução do foco: utils/dialogo.js
  useDialogo(painelRef, aberto, onFechar);

  if (!aberto) return null;

  // Portal para o body: dentro do ecrã, utilitários como space-y-* davam margem
  // ao contentor fixo e o painel descia do topo.
  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-50 flex justify-end">
      <div
        className="drawer-overlay absolute inset-0 bg-black/70"
        onClick={() => onFechar()}
        aria-hidden="true"
      />

      <div
        ref={painelRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={tituloId}
        tabIndex={-1}
        className="drawer-panel relative flex h-full w-full max-w-md flex-col border-l border-border bg-background outline-none"
      >
        <header className="flex shrink-0 items-start gap-4 border-b border-border p-5">
          <div className="min-w-0 flex-1">
            {eyebrow && <div className="mb-2">{eyebrow}</div>}
            <h2 id={tituloId} className="font-display text-3xl leading-none">
              {titulo}
            </h2>
            {subtitulo && <p className="mt-2 text-sm text-muted-foreground">{subtitulo}</p>}
          </div>
          <button
            type="button"
            onClick={() => onFechar()}
            className="-mr-1 p-1 text-muted-foreground hover:text-foreground"
            aria-label="Fechar"
          >
            <IconFechar size={18} />
          </button>
        </header>

        <div className="flex-1 overflow-y-auto p-5">{children}</div>

        {rodape && (
          <footer className="flex shrink-0 flex-wrap items-center gap-2 border-t border-border p-5">
            {rodape}
          </footer>
        )}
      </div>
    </div>,
    document.body
  );
}
