"use client";
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { Dialog } from "@base-ui-components/react/dialog";
import { forwardRef, useRef, createContext, useContext, useState, useLayoutEffect } from "react";
import { ExperimentalButton } from "./Button.js";
import { ExperimentalButtonGroup } from "./ButtonGroup.js";
import { ExperimentalDivider } from "./Divider.js";
import { ExperimentalStepper } from "./Stepper.js";
import { ExperimentalTransition } from "./Transition.js";
import { ArrowLeft } from "../icons/ArrowLeft.js";
import { genericForwardRef } from "../utils/genericForwardRef.js";
import { useCSSPropsPolyfill } from "./tailwind/useCSSPropsPolyfill.js";
import { useControlled } from "./hooks/useControlled.js";
import { classNames } from "../utils/classNames.js";
import { getCSSPropsAttributes } from "./tailwind/cssProps.js";
import { useI18n } from "../i18n/useI18n.js";
import { X } from "../icons/X.js";
const ExperimentalModalContext = createContext(null);
const ExperimentalModalRoot = genericForwardRef(
  ({
    variant,
    size,
    open: controlledOpen,
    defaultOpen,
    onOpenChange,
    trigger,
    dismissible: passedDismissible,
    role,
    steps: passedSteps = 1,
    currentStep: controlledCurrentStep,
    onCurrentStepChange,
    className,
    style,
    children,
    ...props
  }, forwardedRef) => {
    const [propsPolyfillRef, propsPolyfillAttributes] = useCSSPropsPolyfill("modal", { variant, size });
    const [open, setOpen] = useControlled(controlledOpen, defaultOpen ?? !trigger, onOpenChange);
    const dismissible = passedDismissible ?? Boolean(onOpenChange || trigger);
    const steps = typeof passedSteps === "number" ? Array.from({ length: Math.max(1, passedSteps) }, (_, i) => i) : passedSteps.length === 0 ? [0] : passedSteps;
    const [currentStep, setCurrentStep] = useControlled(controlledCurrentStep, steps[0], onCurrentStepChange);
    let currentStepIndex = steps.indexOf(currentStep);
    currentStepIndex = currentStepIndex === -1 ? null : currentStepIndex;
    const previousStepIndex = useRef(currentStepIndex);
    const currentStepDirection = useRef("left");
    if (currentStepIndex !== previousStepIndex.current) {
      currentStepDirection.current = (currentStepIndex ?? steps.length) > (previousStepIndex.current ?? steps.length) ? "left" : "right";
      previousStepIndex.current = currentStepIndex;
    }
    const defaultVariantClasses = classNames(`
      -:default-size-medium
      -:default-variant-drawer
      -:max-2xs:prop-size-small
      -:xs:default-variant-dialog
    `);
    const cssPropsAttributes = getCSSPropsAttributes("modal", { variant, size }, style);
    return /* @__PURE__ */ jsx(
      ExperimentalModalContext.Provider,
      {
        value: {
          open,
          setOpen,
          dismissible,
          steps,
          currentStep,
          setCurrentStep: (step) => {
            if (typeof step === "number" && steps[step]) {
              setCurrentStep(steps[step]);
            } else if (steps.includes(step)) {
              setCurrentStep(step);
            }
          },
          currentStepIndex,
          currentStepDirection: currentStepDirection.current
        },
        children: /* @__PURE__ */ jsxs(
          Dialog.Root,
          {
            open,
            onOpenChange: (newOpen) => {
              if (!newOpen && !dismissible) return;
              setOpen(newOpen);
            },
            dismissible,
            children: [
              trigger ? /* @__PURE__ */ jsx(
                Dialog.Trigger,
                {
                  render: typeof trigger === "function" ? (props2) => {
                    const filteredProps = Object.fromEntries(
                      Object.entries(props2).filter(
                        ([prop]) => prop === "ref" || prop === "id" || prop.startsWith("aria-") || prop.startsWith("data-")
                      )
                    );
                    return trigger({
                      props: filteredProps,
                      open,
                      setOpen,
                      openModal: () => setOpen(true),
                      currentStep,
                      setCurrentStep
                    });
                  } : trigger
                }
              ) : null,
              /* @__PURE__ */ jsx(Dialog.Portal, { keepMounted: true, children: /* @__PURE__ */ jsx(
                "div",
                {
                  ref: propsPolyfillRef,
                  className: classNames(["gds-modal", defaultVariantClasses, className]),
                  ...cssPropsAttributes,
                  ...propsPolyfillAttributes,
                  ...props
                }
              ) }),
              /* @__PURE__ */ jsx(Dialog.Portal, { children: /* @__PURE__ */ jsxs(
                "div",
                {
                  className: classNames([
                    `gds-modal absolute left-0 top-0 pointer-events-none @container-size
                [--gds-modal-margin-x-or-initial:var(--gds-modal-margin-x)]
                [--gds-modal-margin-y-or-initial:var(--gds-modal-margin-y)]
                [--gds-modal-padding-x-or-initial:var(--gds-modal-padding-x)]
                [--gds-modal-padding-y-or-initial:var(--gds-modal-padding-y)]
                [--gds-modal-radius-bottom-or-initial:var(--gds-modal-radius-bottom)]
                [--gds-modal-radius-top-or-initial:var(--gds-modal-radius-top)]
                -:text-p16
                -:text-space-500
                -:[--gds-modal-margin-x:initial]
                -:[--gds-modal-margin-y:initial]
                -:[--gds-modal-padding-x:initial]
                -:[--gds-modal-padding-y:initial]
                -:[--gds-modal-radius-bottom:initial]
                -:[--gds-modal-radius-top:initial]`,
                    defaultVariantClasses,
                    className
                  ]),
                  ...cssPropsAttributes,
                  ...propsPolyfillAttributes,
                  ...props,
                  children: [
                    /* @__PURE__ */ jsx(
                      Dialog.Backdrop,
                      {
                        className: `
                  fixed inset-0 bg-space-1800/50 transition
                  data-[ending-style]:opacity-0
                  data-[starting-style]:opacity-0
                  data-[open]:pointer-events-auto
                  @prop-variant-dialog/modal:duration-300
                  @prop-variant-drawer/modal:duration-500
                `
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Dialog.Popup,
                      {
                        ref: forwardedRef,
                        role: role ?? (dismissible ? "dialog" : "alertdialog"),
                        className: `
                  fixed inset-0 m-auto
                  h-max max-h-[min(max(100cqb,100vh-100cqb*9999),var(--strict-max-height))] min-h-[min(100cqb,var(--strict-max-height))]
                  min-w-[min(100cqi,var(--strict-max-width))] max-w-[min(max(100cqi,100vw-100cqi*9999),var(--strict-max-width))]
                  origin-bottom overflow-y-auto overflow-x-clip rounded-b-[var(--gds-modal-radius-bottom)] rounded-t-[var(--gds-modal-radius-top)]
                  border border-space-1300 bg-space-1600 px-[var(--gds-modal-padding-x)] py-[var(--gds-modal-padding-y)] transition outline-none
                  [--gds-modal-margin-x:var(--gds-modal-margin-x-or-initial,var(--gds-modal-margin-x-default))]
                  [--gds-modal-margin-y:var(--gds-modal-margin-y-or-initial,var(--gds-modal-margin-y-default))]
                  [--gds-modal-padding-x:var(--gds-modal-padding-x-or-initial,var(--gds-modal-padding-x-default))]
                  [--gds-modal-padding-y:var(--gds-modal-padding-y-or-initial,var(--gds-modal-padding-y-default))]
                  [--gds-modal-radius-bottom:var(--gds-modal-radius-bottom-or-initial,var(--gds-modal-radius-bottom-default))]
                  [--gds-modal-radius-top:var(--gds-modal-radius-top-or-initial,var(--gds-modal-radius-top-default))]
                  [--strict-max-height:max(100vh-2*var(--gds-modal-margin-y))]
                  [--strict-max-width:calc(100vw-2*var(--gds-modal-margin-x))]
                  data-[open]:pointer-events-auto
                  has-nested/modal-slot:flex
                  has-nested/modal-slot:flex-col
                  has-nested/modal-slot:overflow-y-clip
                  has-nested/modal-slot:p-0
                  @prop-size-small/modal:w-80
                  @prop-size-small/modal:[--gds-modal-padding-x-default:theme(spacing.6)]
                  @prop-size-small/modal:[--gds-modal-padding-y-default:theme(spacing.4)]
                  @prop-size-medium/modal:w-130
                  @prop-size-medium/modal:[--gds-modal-padding-x-default:theme(spacing.8)]
                  @prop-size-medium/modal:[--gds-modal-padding-y-default:theme(spacing.6)]
                  @prop-size-large/modal:w-160
                  @prop-size-large/modal:[--gds-modal-padding-x-default:theme(spacing.8)]
                  @prop-size-large/modal:[--gds-modal-padding-y-default:theme(spacing.6)]
                  @prop-variant-dialog/modal:duration-300
                  @prop-variant-dialog/modal:[--gds-modal-margin-x-default:theme(spacing.4)]
                  @prop-variant-dialog/modal:[--gds-modal-margin-y-default:theme(spacing.4)]
                  @prop-variant-dialog/modal:[--gds-modal-radius-bottom-default:theme(borderRadius.12)]
                  @prop-variant-dialog/modal:[--gds-modal-radius-top-default:theme(borderRadius.12)]
                  @prop-variant-dialog/modal:data-[ending-style]:scale-[97%]
                  @prop-variant-dialog/modal:data-[starting-style]:scale-[97%]
                  @prop-variant-dialog/modal:data-[ending-style]:opacity-0
                  @prop-variant-dialog/modal:data-[starting-style]:opacity-0
                  @prop-variant-drawer/modal:mb-0
                  @prop-variant-drawer/modal:border-b-0
                  @prop-variant-drawer/modal:duration-500
                  @prop-variant-drawer/modal:[--gds-modal-margin-x-default:theme(spacing.0)]
                  @prop-variant-drawer/modal:[--gds-modal-margin-y-default:theme(spacing.12)]
                  @prop-variant-drawer/modal:[--gds-modal-radius-bottom-default:theme(borderRadius.none)]
                  @prop-variant-drawer/modal:[--gds-modal-radius-top-default:theme(borderRadius.16)]
                  @prop-variant-drawer/modal:[--strict-max-height:max(100vh-var(--gds-modal-margin-y))]
                  @prop-variant-drawer/modal:data-[ending-style]:translate-y-full
                  @prop-variant-drawer/modal:data-[starting-style]:translate-y-full
                  @prop-variant-drawer/modal:max-xs:w-full
                `,
                        children: typeof children === "function" ? children({
                          open,
                          setOpen,
                          closeModal: () => setOpen(false),
                          currentStep,
                          setCurrentStep
                        }) : children
                      }
                    )
                  ]
                }
              ) })
            ]
          }
        )
      }
    );
  }
);
ExperimentalModalRoot.displayName = "ExperimentalModal";
const ExperimentalModalHeader = forwardRef(
  ({
    title,
    buttonBefore: passedButtonBefore,
    buttonAfter: passedButtonAfter,
    stepper: passedStepper,
    className,
    ...props
  }, forwardedRef) => {
    const { t } = useI18n();
    const modalContext = useContext(ExperimentalModalContext);
    const stepCount = (modalContext == null ? void 0 : modalContext.steps.length) ?? 0;
    const currentStep = (modalContext == null ? void 0 : modalContext.currentStep) ?? 0;
    const currentStepIndex = (modalContext == null ? void 0 : modalContext.currentStepIndex) ?? null;
    const currentStepDirection = (modalContext == null ? void 0 : modalContext.currentStepDirection) ?? "left";
    const stepper = passedStepper !== void 0 ? passedStepper && passedStepper.count >= 1 ? passedStepper : null : stepCount > 1 && currentStepIndex !== null ? { count: stepCount, currentIndex: currentStepIndex } : null;
    const buttonTransitionClasses = classNames(`
      min-w-5 shrink-0
      nested/transition-content:items-center
      nested/transition-content:justify-center
      nested-button:default-variant-naked
      @prop-size-small/modal:nested-button:default-size-small
      @prop-size-medium/modal:nested-button:default-size-medium
      @prop-size-large/modal:nested-button:default-size-medium
    `);
    const buttonBefore = passedButtonBefore !== void 0 ? passedButtonBefore : modalContext && currentStepIndex !== null && currentStepIndex > 0 ? /* @__PURE__ */ jsx(ExperimentalButton, { onClick: () => modalContext.setCurrentStep(currentStepIndex - 1), children: /* @__PURE__ */ jsx(ArrowLeft, { alt: t("components.modal.goBackToPreviousStep") }) }) : null;
    const buttonAfter = passedButtonAfter !== void 0 ? passedButtonAfter : modalContext && modalContext.dismissible ? /* @__PURE__ */ jsx(
      Dialog.Close,
      {
        render: /* @__PURE__ */ jsx(ExperimentalButton, { children: /* @__PURE__ */ jsx(X, { alt: t("components.modal.close") }) })
      }
    ) : null;
    return /* @__PURE__ */ jsxs("div", { ref: forwardedRef, className: classNames(["nested/modal-slot shrink-0", className]), ...props, children: [
      /* @__PURE__ */ jsxs(
        "div",
        {
          className: `
            flex items-center gap-4
            @prop-size-small/modal:h-12
            @prop-size-small/modal:px-4
            @prop-size-medium/modal:h-16
            @prop-size-medium/modal:px-6
            @prop-size-large/modal:h-16
            @prop-size-large/modal:px-6
          `,
          children: [
            /* @__PURE__ */ jsx(
              ExperimentalTransition,
              {
                layout: "flex-col",
                mode: "exit-enter",
                animateSize: false,
                className: buttonTransitionClasses,
                children: buttonBefore
              }
            ),
            /* @__PURE__ */ jsx(
              Dialog.Title,
              {
                className: `
              flex-1 text-center text-white
              @prop-size-small/modal:text-h14
              @prop-size-medium/modal:text-h16
              @prop-size-large/modal:text-h16
            `,
                children: /* @__PURE__ */ jsx(
                  ExperimentalTransition,
                  {
                    "data-direction": currentStepDirection,
                    className: `
                data-[direction=right]:[--gds-transition-enter-translate-x:-32px]
                data-[direction=left]:[--gds-transition-enter-translate-x:32px]
                data-[direction=left]:[--gds-transition-exit-translate-x:-32px]
                data-[direction=right]:[--gds-transition-exit-translate-x:32px]
                nested/transition-content:truncate
              `,
                    children: /* @__PURE__ */ jsx("span", { children: title || /* @__PURE__ */ jsx(Fragment, { children: " " }) }, currentStep)
                  }
                )
              }
            ),
            /* @__PURE__ */ jsx(
              ExperimentalTransition,
              {
                layout: "flex-col",
                mode: "exit-enter",
                animateSize: false,
                className: buttonTransitionClasses,
                children: buttonAfter
              }
            )
          ]
        }
      ),
      /* @__PURE__ */ jsx(ExperimentalTransition, { children: stepper ? /* @__PURE__ */ jsx(ExperimentalStepper, { ...stepper, className: "-mt-px" }) : /* @__PURE__ */ jsx(ExperimentalDivider, { variant: "subtle" }) })
    ] });
  }
);
ExperimentalModalHeader.displayName = "ExperimentalModal.Header";
const ExperimentalModalBody = forwardRef(
  ({ className, children, ...props }, forwardedRef) => {
    const modalContext = useContext(ExperimentalModalContext);
    const currentStep = (modalContext == null ? void 0 : modalContext.currentStep) ?? 0;
    return /* @__PURE__ */ jsx("div", { ref: forwardedRef, className: classNames(["nested/modal-slot flex grow flex-col", className]), ...props, children: /* @__PURE__ */ jsx(ExperimentalTransition, { layout: "flex-col", mode: "exit-enter", animateSize: "clip", children: /* @__PURE__ */ jsx("div", { className: "max-h-full overflow-y-auto overflow-x-clip", children: /* @__PURE__ */ jsx("div", { className: "px-[var(--gds-modal-padding-x)] py-[var(--gds-modal-padding-y)]", children }) }, currentStep) }) });
  }
);
ExperimentalModalBody.displayName = "ExperimentalModal.Body";
const ExperimentalModalFooter = forwardRef(
  ({ primaryButton, secondaryButton, className, children, ...props }, forwardedRef) => {
    const modalContext = useContext(ExperimentalModalContext);
    const currentStep = (modalContext == null ? void 0 : modalContext.currentStep) ?? 0;
    const isEmpty = !children && !primaryButton && !secondaryButton;
    return /* @__PURE__ */ jsxs("div", { ref: forwardedRef, className: classNames(["nested/modal-slot shrink-0", className]), ...props, children: [
      /* @__PURE__ */ jsx(ExperimentalTransition, { children: !isEmpty ? /* @__PURE__ */ jsx(ExperimentalDivider, { variant: "subtle" }) : null }),
      /* @__PURE__ */ jsx(ExperimentalTransition, { mode: "exit-enter", children: !isEmpty ? /* @__PURE__ */ jsxs(
        "div",
        {
          className: "flex flex-col gap-4 px-[var(--gds-modal-padding-x)] py-[var(--gds-modal-padding-y)]",
          children: [
            children ? /* @__PURE__ */ jsx("div", { className: "text-p14 text-space-500", children }) : null,
            primaryButton || secondaryButton ? /* @__PURE__ */ jsxs(
              ExperimentalButtonGroup,
              {
                fullWidth: true,
                "data-has-primary-button": primaryButton ? true : void 0,
                "data-has-secondary-button": secondaryButton ? true : void 0,
                className: `
                    *:data-[has-secondary-button]:default-variant-tertiary
                    last:*:data-[has-primary-button]:default-variant-primary
                    @prop-size-small/modal:prop-size-small
                    @prop-size-medium/modal:prop-size-medium
                    @prop-size-large/modal:prop-size-medium
                  `,
                children: [
                  secondaryButton,
                  primaryButton
                ]
              }
            ) : null
          ]
        },
        currentStep
      ) : null })
    ] });
  }
);
ExperimentalModalFooter.displayName = "ExperimentalModal.Footer";
const ExperimentalModalStepContext = createContext(null);
const ExperimentalModalStep = ({ children }) => {
  const stepContext = useContext(ExperimentalModalStepContext);
  const isConsumer = stepContext !== null;
  const version = useRef(0);
  const content = useRef(null);
  const [, setForceRerender] = useState({});
  useLayoutEffect(() => {
    if (isConsumer) {
      if (version.current === stepContext.version) {
        stepContext.forceRerender();
      } else {
        version.current = stepContext.version;
      }
    }
  });
  if (isConsumer) {
    stepContext.setContent(children);
    return null;
  } else {
    version.current++;
    const setContent = (updatedContent) => {
      content.current = updatedContent;
    };
    const forceRerender = () => setForceRerender({});
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(ExperimentalModalStepContext.Provider, { value: { version: version.current, setContent, forceRerender }, children }),
      /* @__PURE__ */ jsx(StableElement, { render: () => content.current })
    ] });
  }
};
ExperimentalModalStep.displayName = "ExperimentalModal.Step";
const StableElement = ({ render }) => render();
export {
  ExperimentalModalBody,
  ExperimentalModalFooter,
  ExperimentalModalHeader,
  ExperimentalModalRoot,
  ExperimentalModalStep
};
