/**
 * <Toast> — aviso curto no fundo do ecrã, com uma acção opcional (ex.: Anular).
 *
 * O contentor com role="status" está sempre montado, para que os leitores de
 * ecrã anunciem cada aviso novo. Desaparece sozinho ao fim de 8 segundos.
 *
 *   toast = { id, mensagem, erro?: true, accao?: { rotulo, onClick } }
 *
 * Um erro (`erro: true`) leva a cor do perigo e o símbolo, para não se ler como
 * um "feito" (cliente simulado, 5 Out).
 *
 * O id tem de mudar a cada aviso — é ele que reinicia o temporizador.
 */

const DURACAO_TOAST_MS = 8000;

function Toast({ toast, onFechar }) {
  const onFecharRef = React.useRef(onFechar);
  onFecharRef.current = onFechar;

  React.useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => onFecharRef.current(), DURACAO_TOAST_MS);
    return () => clearTimeout(t);
  }, [toast && toast.id]);

  return ReactDOM.createPortal(
    <div
      className="pointer-events-none fixed inset-x-0 bottom-0 z-[70] flex justify-center p-4"
      role="status"
      aria-live="polite"
    >
      {toast && (
        <div
          key={toast.id}
          className={`toast pointer-events-auto flex w-full max-w-lg items-center gap-4 border bg-secondary px-4 py-3 text-sm shadow-lg shadow-black/40 ${toast.erro ? 'border-[hsl(var(--offline))]' : 'border-border'}`}
        >
          {toast.erro && <span className="shrink-0 text-perigo-texto">Erro:</span>}
          <span className="flex-1">{toast.mensagem}</span>
          {toast.accao && (
            <button
              type="button"
              onClick={toast.accao.onClick}
              className="shrink-0 text-sm text-primary hover:underline"
            >
              {toast.accao.rotulo}
            </button>
          )}
          <button
            type="button"
            onClick={() => onFechar()}
            className="shrink-0 text-muted-foreground hover:text-foreground"
            aria-label="Fechar aviso"
          >
            <IconFechar size={14} />
          </button>
        </div>
      )}
    </div>,
    document.body
  );
}
