"use client";
import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { Portal, Dialog, DialogBackdrop, DialogPanel, DialogTitle } from "@headlessui/react";
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 { genericForwardRef } from "../utils/genericForwardRef.js";
import { X } from "../icons/X.js";
import { ArrowLeft } from "../icons/ArrowLeft.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";
const ExperimentalModalContext = createContext(null);
const ExperimentalModalRoot = genericForwardRef(
  ({
    variant,
    size,
    open: controlledOpen,
    onClose,
    trigger,
    persistent: passedPersistent,
    role,
    steps: passedSteps = 1,
    currentStep: controlledCurrentStep,
    onCurrentStepChange,
    className,
    style,
    children,
    ...props
  }, ref) => {
    const { polyfillAttributes, polyfillElement } = useCSSPropsPolyfill("modal", { variant, size });
    const [open, setOpen] = useControlled(controlledOpen, trigger ? false : true, (newOpen) => {
      if (!newOpen) {
        onClose == null ? void 0 : onClose(false);
      }
    });
    const openModal = () => setOpen(true);
    const closeModal = () => setOpen(false);
    const persistent = passedPersistent ?? (!onClose && !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__ */ jsxs(
      ExperimentalModalContext.Provider,
      {
        value: {
          open,
          setOpen,
          persistent,
          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: [
          trigger ? trigger({ openModal, currentStep, setCurrentStep }) : null,
          /* @__PURE__ */ jsx(Portal, { children: /* @__PURE__ */ jsx(
            "div",
            {
              className: classNames(["gds-modal", defaultVariantClasses, className]),
              ...cssPropsAttributes,
              ...polyfillAttributes,
              children: polyfillElement
            }
          ) }),
          /* @__PURE__ */ jsxs(
            Dialog,
            {
              ref,
              open,
              onClose: persistent ? () => {
              } : closeModal,
              role: role ?? (persistent ? "alertdialog" : "dialog"),
              className: classNames([
                `gds-modal fixed inset-0 z-50
            [--gds-modal-max-height-or-initial:var(--gds-modal-max-height)]
            [--gds-modal-max-width-or-initial:var(--gds-modal-max-width)]
            [--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)]
            -:[--gds-modal-max-height:initial]
            -:[--gds-modal-max-width:initial]
            -:[--gds-modal-padding-x:initial]
            -:[--gds-modal-padding-y:initial]
            -:[--gds-modal-radius-bottom:initial]
            -:[--gds-modal-radius-top:initial]`,
                defaultVariantClasses,
                className
              ]),
              ...cssPropsAttributes,
              ...polyfillAttributes,
              ...props,
              children: [
                /* @__PURE__ */ jsx(
                  DialogBackdrop,
                  {
                    transition: true,
                    className: `
              absolute inset-0 bg-space-1800/50 transition data-[closed]:opacity-0
              @prop-variant-dialog/modal:duration-300
              @prop-variant-drawer/modal:duration-500
            `
                  }
                ),
                /* @__PURE__ */ jsx(
                  "div",
                  {
                    className: `
              absolute inset-0 flex justify-center
              [--gds-modal-max-height:var(--gds-modal-max-height-or-initial,var(--gds-modal-max-height-default))]
              [--gds-modal-max-width:var(--gds-modal-max-width-or-initial,var(--gds-modal-max-width-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))]
              @prop-size-small/modal:[--gds-modal-max-width-default:theme(spacing.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:[--gds-modal-max-width-default:theme(spacing.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:[--gds-modal-max-width-default:theme(spacing.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:[--gds-modal-max-height-default:max(100vh_-_theme(spacing.8),theme(spacing.56))]
              @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:[align-items:safe_center]
              @prop-variant-drawer/modal:items-end
              @prop-variant-drawer/modal:[--gds-modal-max-height-default:max(100vh_-_theme(spacing.16),theme(spacing.56))]
              @prop-variant-drawer/modal:[--gds-modal-radius-bottom-default:0px]
              @prop-variant-drawer/modal:[--gds-modal-radius-top-default:theme(borderRadius.16)]
            `,
                    children: /* @__PURE__ */ jsx(
                      DialogPanel,
                      {
                        transition: true,
                        className: `
                origin-bottom overflow-clip
                rounded-b-[var(--gds-modal-radius-bottom)]
                rounded-t-[var(--gds-modal-radius-top)]
                border border-space-1300 bg-space-1600 transition
                @prop-variant-dialog/modal:w-[min(var(--gds-modal-max-width),100vw-theme(spacing.8))]
                @prop-variant-dialog/modal:duration-300
                @prop-variant-dialog/modal:data-[closed]:scale-[97%]
                @prop-variant-dialog/modal:data-[closed]:opacity-0
                @prop-variant-drawer/modal:w-full
                @prop-variant-drawer/modal:border-b-0
                @prop-variant-drawer/modal:duration-500
                @prop-variant-drawer/modal:data-[closed]:translate-y-full
                @prop-variant-drawer/modal:xs:w-[min(var(--gds-modal-max-width),100vw)]
              `,
                        children: /* @__PURE__ */ jsx(
                          "div",
                          {
                            className: `
                  text-p16 max-h-[var(--gds-modal-max-height)] overflow-y-auto overflow-x-clip
                  px-[var(--gds-modal-padding-x)]
                  py-[var(--gds-modal-padding-y)]
                  text-space-500
                  has-nested/modal-slot:flex
                  has-nested/modal-slot:flex-col
                  has-nested/modal-slot:overflow-y-clip
                  has-nested/modal-slot:p-0
                `,
                            children: typeof children === "function" ? children({ closeModal, currentStep, setCurrentStep }) : children
                          }
                        )
                      }
                    )
                  }
                )
              ]
            }
          )
        ]
      }
    );
  }
);
ExperimentalModalRoot.displayName = "ExperimentalModal";
const ExperimentalModalHeader = forwardRef(
  ({
    title,
    buttonBefore: passedButtonBefore,
    buttonAfter: passedButtonAfter,
    stepper: passedStepper,
    className,
    ...props
  }, ref) => {
    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: "Go back to previous step" }) }) : null;
    const buttonAfter = passedButtonAfter !== void 0 ? passedButtonAfter : modalContext && !modalContext.persistent ? /* @__PURE__ */ jsx(ExperimentalButton, { onClick: () => modalContext.setOpen(false), children: /* @__PURE__ */ jsx(X, { alt: "Close this dialog" }) }) : null;
    return /* @__PURE__ */ jsxs("div", { ref, 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(
              DialogTitle,
              {
                className: `
              flex-1 text-center leading-none 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:-16px]
                data-[direction=left]:[--gds-transition-enter-translate-x:16px]
                data-[direction=left]:[--gds-transition-exit-translate-x:-16px]
                data-[direction=right]:[--gds-transition-exit-translate-x:16px]
                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 }, ref) => {
    const modalContext = useContext(ExperimentalModalContext);
    const currentStep = (modalContext == null ? void 0 : modalContext.currentStep) ?? 0;
    return /* @__PURE__ */ jsx("div", { ref, className: classNames(["nested/modal-slot flex 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
              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 }, ref) => {
    const modalContext = useContext(ExperimentalModalContext);
    const currentStep = (modalContext == null ? void 0 : modalContext.currentStep) ?? 0;
    const isEmpty = !children && !primaryButton && !secondaryButton;
    return /* @__PURE__ */ jsxs("div", { ref, 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(Render, { render: () => content.current })
    ] });
  }
};
ExperimentalModalStep.displayName = "ExperimentalModal.Step";
const Render = ({ render }) => render();
export {
  ExperimentalModalBody,
  ExperimentalModalFooter,
  ExperimentalModalHeader,
  ExperimentalModalRoot,
  ExperimentalModalStep
};
