/**
 * A small modal confirmation, local to the devices feature (ticket #77, lot F2).
 *
 * Not `FloatingWindow`: that is a draggable desktop window, and this surface is
 * mobile-first. Not a shared primitive either — adding a dialog to the kit is a
 * design-system decision for UX/Architect, not a side effect of this ticket.
 */

import { useEffect, useRef } from "react";

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

interface ConfirmDialogProps {
  title: string;
  body: string;
  confirmLabel: string;
  /** Paints the confirm action as destructive (revoke-all). */
  danger?: boolean;
  busy?: boolean;
  onConfirm: () => void | Promise<void>;
  onCancel: () => void;
}

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

  // Mount-only: a confirmation opens focused on the safe choice. Depending on
  // `onCancel` here would re-steal focus whenever the parent re-renders (#17).
  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.floatingWindow }}
      onClick={onCancel}
    >
      <div
        role="dialog"
        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" onClick={onCancel}>
            Annuler
          </Button>
          <Button
            size="sm"
            variant={danger ? "danger" : "primary"}
            loading={busy}
            onClick={() => void onConfirm()}
          >
            {confirmLabel}
          </Button>
        </div>
      </div>
    </div>
  );
}
