/**
 * Destructive-action confirmation for the web tickets/sprints surface (ticket
 * #86). Local to this feature, like `AppExitConfirmDialog` and
 * `features/devices/ConfirmDialog` are local to theirs — a shared dialog
 * primitive is a design-system decision outside this lot.
 *
 * `role="alertdialog"`, focus on `Annuler` by default, `Échap` cancels, no
 * dismiss-on-outside-click (a destructive confirmation should not be dismissed
 * ambiguously), per carnet #86's accessibility section.
 */

import { useEffect, useRef } from "react";

import { Button, zIndex } from "@/shared";

export interface WebConfirmDialogProps {
  title: string;
  body: string;
  confirmLabel: string;
  busy?: boolean;
  onConfirm: () => void | Promise<void>;
  onCancel: () => void;
}

export function WebConfirmDialog({
  title,
  body,
  confirmLabel,
  busy = false,
  onConfirm,
  onCancel,
}: WebConfirmDialogProps) {
  const cancelRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    cancelRef.current?.focus();
  }, []);

  useEffect(() => {
    function onKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape") onCancel();
    }
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [onCancel]);

  return (
    <div
      className="fixed inset-0 flex items-center justify-center bg-black/50 p-4"
      style={{ zIndex: zIndex.toast }}
    >
      <div
        role="alertdialog"
        aria-modal="true"
        aria-label={title}
        onClick={(e) => e.stopPropagation()}
        className="flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl"
      >
        <h3 className="text-sm font-semibold text-content">{title}</h3>
        <p className="text-sm text-muted">{body}</p>
        <div className="flex justify-end gap-2">
          <Button ref={cancelRef} size="sm" variant="ghost" disabled={busy} onClick={onCancel}>
            Annuler
          </Button>
          <Button
            size="sm"
            variant="danger"
            loading={busy}
            disabled={busy}
            onClick={() => void onConfirm()}
          >
            {confirmLabel}
          </Button>
        </div>
      </div>
    </div>
  );
}
