"use client";

import { useEffect, useId, useRef } from "react";
import { createPortal } from "react-dom";
import { useI18n } from "@/components/i18n-provider";

export function MailComposeSendingOverlay({ complete, label }: { complete: boolean; label?: string }) {
  const { t } = useI18n();
  const titleId = useId();
  const dialogRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const previousFocus = document.activeElement;
    dialogRef.current?.focus();
    return () => {
      if (previousFocus instanceof HTMLElement && previousFocus.isConnected) {
        previousFocus.focus();
      }
    };
  }, []);

  return createPortal(
    <div className="fixed inset-0 z-[12200] flex items-center justify-center bg-[rgba(15,23,42,0.18)] px-4 py-6 backdrop-blur-[2px]">
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-busy={!complete}
        aria-labelledby={titleId}
        tabIndex={-1}
        onKeyDown={(event) => {
          if (event.key === "Tab") event.preventDefault();
        }}
        className="flex w-full max-w-[320px] flex-col items-center gap-5 rounded-[18px] border border-[#e1e7f0] bg-white px-6 py-8 text-center shadow-[0_24px_64px_rgba(15,23,42,0.18)] outline-none"
      >
        {complete ? (
          <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" className="h-10 w-10 text-[#2f6df6]">
            <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.8" />
            <path d="m7.5 12 3 3 6-6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        ) : (
          <span aria-hidden="true" className="h-10 w-10 animate-spin rounded-full border-[3px] border-[#e5edfc] border-t-[#2f6df6]" />
        )}
        <p id={titleId} role="status" aria-live="polite" className="text-[16px] font-semibold text-[#202d43]">
          {label ?? (complete ? t("compose.send.completeDescription") : t("compose.send.progress"))}
        </p>
      </div>
    </div>,
    document.body,
  );
}
