"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { createPortal } from "react-dom";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "../../primitives/icon-button.js";
import { cn } from "@open-mercato/shared/lib/utils";
import { Loader2, X } from "lucide-react";
function ConfirmDialog({
  open: controlledOpen,
  onOpenChange,
  onConfirm,
  onCancel,
  title,
  text,
  confirmText,
  cancelText,
  variant = "default",
  loading = false,
  trigger
}) {
  const t = useT();
  const dialogRef = React.useRef(null);
  const [internalOpen, setInternalOpen] = React.useState(false);
  const cancelButtonRef = React.useRef(null);
  const confirmButtonRef = React.useRef(null);
  const [portalTarget, setPortalTarget] = React.useState(null);
  const reactId = React.useId();
  const titleId = `confirm-dialog-title-${reactId}`;
  const descriptionId = `confirm-dialog-description-${reactId}`;
  const isControlled = controlledOpen !== void 0;
  const open = isControlled ? controlledOpen : internalOpen;
  const setOpen = isControlled ? onOpenChange || (() => {
  }) : setInternalOpen;
  const handleCancelCallback = React.useCallback(() => {
    if (!isControlled) {
      onCancel?.();
    }
  }, [isControlled, onCancel]);
  const resolvedTitle = title ?? t("ui.dialogs.confirm.defaultTitle", "Are you sure?");
  const resolvedConfirmText = confirmText === false ? false : confirmText ?? t("ui.dialogs.confirm.confirmText", "Confirm");
  const resolvedCancelText = cancelText === false ? false : cancelText ?? t("ui.dialogs.confirm.cancelText", "Cancel");
  const closeAriaLabel = t("ui.dialog.close.ariaLabel", "Close");
  const requestClose = React.useCallback(() => {
    setOpen(false);
    handleCancelCallback();
  }, [setOpen, handleCancelCallback]);
  React.useLayoutEffect(() => {
    setPortalTarget(document.body);
  }, []);
  React.useLayoutEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;
    if (open) {
      if (!dialog.open) {
        dialog.showModal();
        setTimeout(() => {
          if (resolvedCancelText !== false && cancelButtonRef.current) {
            cancelButtonRef.current.focus();
          } else if (confirmButtonRef.current) {
            confirmButtonRef.current.focus();
          }
        }, 0);
      }
    } else {
      if (dialog.open) {
        dialog.close();
      }
    }
  }, [open, resolvedCancelText, portalTarget]);
  React.useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;
    const handleCancel2 = (e) => {
      if (loading) {
        e.preventDefault();
        return;
      }
      requestClose();
    };
    dialog.addEventListener("cancel", handleCancel2);
    return () => dialog.removeEventListener("cancel", handleCancel2);
  }, [loading, requestClose]);
  const handleBackdropClick = (e) => {
    if (e.target === dialogRef.current && !loading) {
      requestClose();
    }
  };
  React.useEffect(() => {
    if (!open) return;
    const handleKeyDown = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter" && !loading) {
        e.preventDefault();
        handleConfirm();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [open, loading]);
  const handleConfirm = async () => {
    await onConfirm();
    if (!loading) {
      setOpen(false);
    }
  };
  const handleCancel = () => {
    requestClose();
  };
  const handleTriggerClick = () => {
    if (trigger) {
      setOpen(true);
    }
  };
  const dialogElement = /* @__PURE__ */ jsx(
    "dialog",
    {
      ref: dialogRef,
      role: "alertdialog",
      "aria-labelledby": titleId,
      "aria-describedby": text ? descriptionId : void 0,
      onClick: handleBackdropClick,
      className: cn(
        // Reset dialog defaults
        "m-0 p-0 max-w-none bg-transparent border-none pointer-events-auto",
        // Backdrop styling
        "backdrop:bg-black/50 backdrop:backdrop-blur-sm backdrop:transition-opacity",
        // Mobile: bottom sheet
        "fixed inset-x-0 bottom-0 top-auto w-full",
        // Desktop: centered
        "sm:inset-auto sm:mx-auto sm:my-auto sm:max-w-md sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2",
        // Animation with reduced motion support
        "motion-safe:open:animate-in motion-safe:open:fade-in-0 motion-safe:open:slide-in-from-bottom-4",
        "sm:motion-safe:open:slide-in-from-bottom-0 sm:motion-safe:open:zoom-in-95",
        // Duration
        "motion-safe:open:duration-300"
      ),
      children: /* @__PURE__ */ jsxs(
        "div",
        {
          role: "document",
          className: cn(
            // Panel container
            "flex flex-col gap-4 rounded-t-2xl border-t bg-card p-6 text-foreground shadow-lg",
            "sm:rounded-xl sm:border",
            // Relative positioning for close button
            "relative"
          ),
          children: [
            /* @__PURE__ */ jsx(
              IconButton,
              {
                type: "button",
                variant: "ghost",
                size: "sm",
                onClick: handleCancel,
                disabled: loading,
                "aria-label": closeAriaLabel,
                className: "absolute right-4 top-4 opacity-70 hover:opacity-100",
                children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
              }
            ),
            /* @__PURE__ */ jsx(
              "h2",
              {
                id: titleId,
                className: cn(
                  "text-sm font-medium leading-snug tracking-tight pr-6",
                  // Mobile: centered, Desktop: left-aligned
                  "text-center sm:text-left"
                ),
                children: resolvedTitle
              }
            ),
            text && /* @__PURE__ */ jsx(
              "p",
              {
                id: descriptionId,
                className: "text-sm font-medium leading-snug text-muted-foreground",
                children: text
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", children: [
              resolvedCancelText !== false && /* @__PURE__ */ jsx(
                Button,
                {
                  ref: cancelButtonRef,
                  variant: "outline",
                  onClick: handleCancel,
                  disabled: loading,
                  className: "w-full sm:w-auto",
                  children: resolvedCancelText
                }
              ),
              resolvedConfirmText !== false && /* @__PURE__ */ jsxs(
                Button,
                {
                  ref: confirmButtonRef,
                  variant: variant === "destructive" ? "destructive" : "default",
                  onClick: handleConfirm,
                  disabled: loading,
                  className: "w-full sm:w-auto",
                  children: [
                    loading && /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
                    resolvedConfirmText
                  ]
                }
              )
            ] })
          ]
        }
      )
    }
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    trigger && /* @__PURE__ */ jsx("div", { onClick: handleTriggerClick, className: "inline-block", role: "presentation", children: trigger }),
    portalTarget ? createPortal(dialogElement, portalTarget) : null
  ] });
}
export {
  ConfirmDialog
};
//# sourceMappingURL=ConfirmDialog.js.map
