import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { createContext, forwardRef, useContext, useRef, useState, useEffect, useMemo } from 'react';
import { c as cx } from './index-De1g9FRV.js';
import { S as SvgCheck } from './check-Cf67OWrZ.js';
import { I as Icon } from './Icon-B4uCvMU9.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { e as DurationSlow } from './primitive-BXgYQTTw.js';
import { Overflow } from './Overflow.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-DjqeAJZ9.js';
import { m as motion } from './proxy-DEehATlA.js';
import { B as Button } from './Button-BNzCI47m.js';
import { useTrackingId } from './useTrackingId.js';

import './Stepper.css';const StepperContext = createContext({
  current: 0,
  currentId: "",
  focus: 0,
  setFocus: () => void 0,
  setCurrent: () => void 0,
  setCurrentId: () => void 0
});

const label$1 = "_label_tnvkm_28";
const styles$3 = {
	"stepper-list": "_stepper-list_tnvkm_1",
	"stepper-steps": "_stepper-steps_tnvkm_19",
	label: label$1
};

const StepperList = forwardRef(
  (props, ref) => {
    const { className, children, onKeyDown, ...rest } = props;
    const { current, items } = useContext(StepperContext);
    const tabListClassNames = cx(styles$3["stepper-list"], className);
    const currentLabel = items?.[current].querySelectorAll("span")[1].textContent;
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ...rest,
        className: tabListClassNames,
        "data-anv": "stepper-list",
        ref,
        role: "tablist",
        children: [
          /* @__PURE__ */ jsx("div", { className: styles$3["stepper-steps"], children }),
          /* @__PURE__ */ jsx("span", { className: styles$3.label, children: currentLabel })
        ]
      }
    );
  }
);
StepperList.displayName = "StepperList";

const bar = "_bar_1l4p4_30";
const label = "_label_1l4p4_49";
const circle = "_circle_1l4p4_62";
const styles$2 = {
	"stepper-step": "_stepper-step_1l4p4_1",
	bar: bar,
	label: label,
	circle: circle,
	"all-completed": "_all-completed_1l4p4_87",
	"can-navigate": "_can-navigate_1l4p4_91"
};

const StepperStep = forwardRef(
  (props, ref) => {
    const stepRef = useRef(null);
    const {
      current,
      items,
      setCurrent,
      focus,
      setFocus,
      allCompleted,
      allowNavigateToPrevStep
    } = useContext(StepperContext);
    const {
      onClick,
      children,
      onFocus,
      onKeyDown,
      controls,
      className,
      "aria-label": ariaLabel,
      ...rest
    } = props;
    const index = useRef();
    const [selected, setSelected] = useState(false);
    const [completed, setCompleted] = useState(
      // Below is to be used for custom overriding
      // completed state for a step
      // Check Stepper.stories.tsx#103 for the use case
      stepRef.current?.getAttribute("data-completed") === "true" ? true : void 0
    );
    useEffect(() => {
      if (!items) return;
      index.current = Array.prototype.indexOf.call(items, stepRef.current);
      setCompleted(index.current < current);
      setSelected(index.current === current);
    }, [current, items]);
    const stepClassNames = cx(styles$2["stepper-step"], className, {
      [styles$2["can-navigate"]]: allowNavigateToPrevStep,
      [styles$2["all-completed"]]: allCompleted
    });
    const onClickHandler = (e) => {
      onClick?.(e, index.current);
      if (!allowNavigateToPrevStep || selected || index.current === void 0 || !items || index.current > current) {
        return;
      }
      setCurrent(index.current ?? 0);
      setFocus(index.current);
      items[index.current].focus();
    };
    const onKeyDownHandler = (e) => {
      onKeyDown?.(e);
      const focusableItems = Array.prototype.filter.call(
        items,
        (item) => item.getAttribute("data-completed") === "true" || item.getAttribute("aria-selected") === "true"
      );
      const prevFocus = focus - 1;
      const nextFocus = focus + 1;
      switch (e.code) {
        case "Enter":
        case "Space":
          e.preventDefault();
          setCurrent(focus);
          break;
        case "ArrowRight":
          e.preventDefault();
          if (nextFocus === focusableItems.length) {
            setFocus(0);
            focusableItems[0].focus();
            focusableItems[0].setAttribute("tabindex", "0");
            stepRef.current?.setAttribute("tabindex", "-1");
            return;
          }
          stepRef.current?.setAttribute("tabindex", "-1");
          setFocus(nextFocus);
          focusableItems[nextFocus].focus();
          focusableItems[nextFocus].setAttribute("tabindex", "0");
          break;
        case "ArrowLeft":
          e.preventDefault();
          if (focus === 0) {
            const lastItemIndex = focusableItems.length - 1;
            setFocus(lastItemIndex);
            focusableItems[lastItemIndex].focus();
            focusableItems[lastItemIndex].setAttribute("tabindex", "0");
            stepRef.current?.setAttribute("tabindex", "-1");
            return;
          }
          stepRef.current?.setAttribute("tabindex", "-1");
          setFocus(prevFocus);
          focusableItems[prevFocus].focus();
          focusableItems[prevFocus].setAttribute("tabindex", "0");
          break;
      }
    };
    const childrenText = typeof children === "string" ? children : typeof children === "number" ? String(children) : void 0;
    return /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        role: "tab",
        "data-anv": "stepper-step",
        className: stepClassNames,
        "aria-selected": selected,
        "aria-controls": controls,
        "aria-label": childrenText || ariaLabel,
        tabIndex: allowNavigateToPrevStep && selected ? 0 : -1,
        "data-completed": completed,
        onClick: onClickHandler,
        onKeyDown: allowNavigateToPrevStep ? onKeyDownHandler : onKeyDown,
        ...rest,
        ref: useMergeRefs([stepRef, ref]),
        children: [
          /* @__PURE__ */ jsx("span", { className: styles$2.bar }),
          /* @__PURE__ */ jsxs("span", { className: styles$2.label, children: [
            /* @__PURE__ */ jsx("span", { className: styles$2.circle, children: /* @__PURE__ */ jsx(Icon, { svg: SvgCheck, inherit: true, "aria-hidden": true }) }),
            children
          ] })
        ]
      }
    );
  }
);
StepperStep.displayName = "StepperStep";

const styles$1 = {
	"stepper-panel": "_stepper-panel_14tpv_1"
};

const StepperPanel = forwardRef(
  (props, ref) => {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const { id, className, style, children, ...rest } = componentProps;
    const { current, items, allCompleted, setCurrentId } = useContext(StepperContext);
    const currentId = items?.[current].getAttribute("aria-controls");
    const isCurrent = currentId === id;
    useEffect(() => {
      if (isCurrent && !allCompleted) {
        setCurrentId(currentId ?? "");
      }
    }, [allCompleted, isCurrent, currentId, setCurrentId]);
    const tabPanelClassNames = cx(styles$1["stepper-panel"], className);
    const styleCombined = {
      ...style,
      ...layoutStyles
    };
    if (isCurrent && !allCompleted) {
      return /* @__PURE__ */ jsx(
        motion.div,
        {
          style: styleCombined,
          className: tabPanelClassNames,
          transition: {
            opacity: {
              duration: +DurationSlow.value.replace("ms", "") / 1e3
            }
          },
          initial: { opacity: 0 },
          animate: { opacity: 1 },
          exit: { opacity: 0 },
          layout: true,
          ...rest,
          role: "tabpanel",
          "data-anv": "stepper-panel",
          id,
          ref,
          children: /* @__PURE__ */ jsx(Overflow, { flexGrow: 1, children })
        }
      );
    }
    return /* @__PURE__ */ jsx(Fragment, {});
  }
);
StepperPanel.displayName = "StepperPanel";

const StepperFinalPanel = forwardRef((props, ref) => {
  const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
  const { id, className, style, children, ...rest } = componentProps;
  const { allCompleted, setCurrentId } = useContext(StepperContext);
  useEffect(() => {
    if (allCompleted) {
      setCurrentId("final-panel");
    }
  }, [allCompleted, setCurrentId]);
  const tabPanelClassNames = cx(styles$1["stepper-panel"], className);
  const styleCombined = {
    ...style,
    ...layoutStyles
  };
  if (allCompleted) {
    return /* @__PURE__ */ jsx(
      motion.div,
      {
        style: styleCombined,
        className: tabPanelClassNames,
        transition: {
          opacity: {
            duration: +DurationSlow.value.replace("ms", "") / 1e3
          }
        },
        initial: { opacity: 0 },
        animate: { opacity: 1 },
        exit: { opacity: 0 },
        layout: true,
        ...rest,
        role: "tabpanel",
        "data-anv": "stepper-final-panel",
        tabIndex: 0,
        ref,
        children: /* @__PURE__ */ jsx(Overflow, { children })
      }
    );
  }
  return null;
});
StepperFinalPanel.displayName = "StepperFinalPanel";

const StepperNextButton = forwardRef((props, ref) => {
  const {
    setAllCompleted,
    onComplete,
    setCurrent,
    setFocus,
    items,
    current,
    allCompleted
  } = useContext(StepperContext);
  const {
    onClick,
    onFocus,
    nextLabel = "Next",
    completeLabel = "Complete",
    appearance = "primary",
    ...rest
  } = props;
  const proceedToNextStep = () => {
    if (items && current === items.length - 1) {
      items.forEach((item) => item.setAttribute("tabindex", "-1"));
      setAllCompleted?.(true);
      onComplete?.();
      return;
    }
    setCurrent(current + 1);
    setFocus(current + 1);
  };
  const onClickHandler = (e) => {
    const onClickResult = onClick?.(e);
    if (onClickResult !== void 0 && !!onClickResult && onClickResult instanceof Promise) {
      onClickResult.then((result) => {
        if (result === false) return;
        proceedToNextStep();
      });
    } else {
      if (onClickResult === false) return;
      proceedToNextStep();
    }
  };
  const data = {
    nextLabel: props.nextLabel,
    completeLabel: props.completeLabel
  };
  const trackingId = useTrackingId({
    name: "StepperNextButton",
    data,
    hasOverride: !!props["data-tracking-id"]
  });
  return allCompleted ? null : /* @__PURE__ */ jsx(
    Button,
    {
      "data-anv": "stepper-next-button",
      "data-tracking-id": trackingId,
      onClick: onClickHandler,
      appearance,
      ref,
      ...rest,
      children: items && current === items.length - 1 ? completeLabel : nextLabel
    }
  );
});
StepperNextButton.displayName = "StepperNextButton";

const StepperPrevButton = forwardRef((props, ref) => {
  const {
    setCurrent,
    setFocus,
    allCompleted,
    setAllCompleted,
    items,
    current,
    allowNavigateToPrevStep
  } = useContext(StepperContext);
  const { onClick, label = "Previous", onFocus, ...rest } = props;
  const onClickHandler = (e) => {
    if (allCompleted) {
      setAllCompleted?.(false);
      if (allowNavigateToPrevStep) {
        items?.[current].setAttribute("tabindex", "0");
      }
    } else {
      setCurrent(current - 1);
      setFocus(current - 1);
    }
    onClick?.(e);
  };
  const data = {
    label: props.label
  };
  const trackingId = useTrackingId({
    name: "StepperPrevButton",
    data,
    hasOverride: !!props["data-tracking-id"]
  });
  return current === 0 ? null : /* @__PURE__ */ jsx(
    Button,
    {
      "data-anv": "stepper-prev-button",
      "data-tracking-id": trackingId,
      onClick: onClickHandler,
      ref,
      ...rest,
      children: label
    }
  );
});
StepperPrevButton.displayName = "StepperPrevButton";

const stepper = "_stepper_4q6gk_1";
const styles = {
	stepper: stepper
};

const Stepper = Object.assign(
  forwardRef(function StepperInner(props, ref) {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const {
      defaultIndex,
      className,
      allowNavigateToPrevStep,
      children,
      onChange,
      onComplete,
      style,
      ...rest
    } = componentProps;
    const tabRef = useRef(null);
    const [items, setItems] = useState();
    const [allCompleted, setAllCompleted] = useState(false);
    const [current, setCurrent] = useState(defaultIndex ?? 0);
    const [currentId, setCurrentId] = useState("");
    const [focus, setFocus] = useState(defaultIndex ?? 0);
    const stepperClassNames = cx(styles["stepper"], className);
    useEffect(() => {
      const newItems = tabRef.current?.querySelectorAll(
        "[role=tab]:not([disabled])"
      );
      setItems(newItems);
      if (defaultIndex !== void 0 && newItems && newItems.length > 0 && defaultIndex >= newItems.length) {
        const lastIndex = newItems.length - 1;
        setAllCompleted(true);
        setCurrent(lastIndex);
        setFocus(lastIndex);
      }
    }, []);
    useEffect(() => {
      onChange?.({
        currentStepId: currentId,
        currentStepIndex: allCompleted ? void 0 : current
      });
    }, [allCompleted, currentId, onChange]);
    const styleCombined = { ...style, ...layoutStyles };
    const value = useMemo(
      () => ({
        current,
        setCurrent,
        currentId,
        setCurrentId,
        focus,
        setFocus,
        onComplete,
        items,
        allCompleted,
        setAllCompleted,
        allowNavigateToPrevStep
      }),
      [
        current,
        currentId,
        focus,
        onComplete,
        items,
        allCompleted,
        setAllCompleted,
        allowNavigateToPrevStep
      ]
    );
    return /* @__PURE__ */ jsx(StepperContext.Provider, { value, children: /* @__PURE__ */ jsx(
      motion.div,
      {
        transition: { duration: 0 },
        layout: true,
        className: stepperClassNames,
        "data-anv": "stepper",
        style: styleCombined,
        ...rest,
        ref: useMergeRefs([tabRef, ref]),
        children
      }
    ) });
  }),
  {
    /**
     * Individual step component for the Stepper.
     *
     * Features:
     * - Visual progress indicator with animated bar
     * - Check icon for completed steps
     * - Keyboard navigation support
     * - Accessible with proper ARIA attributes
     * - Click handling for step navigation
     * - Visual states for current, completed, and future steps
     * - Responsive design with mobile-friendly layout
     * - Focus management for keyboard users
     * - Custom styling support
     *
     * @example
     * <Stepper.Step controls="step1">
     *   Personal Information
     * </Stepper.Step>
     *
     * @example
     * <Stepper.Step
     *   controls="step2"
     *   onClick={(e, index) => console.log(`Clicked step ${index}`)}
     * >
     *   Contact Details
     * </Stepper.Step>
     */
    Step: StepperStep,
    /**
     * Container component for organizing and displaying stepper steps.
     *
     * Features:
     * - Groups multiple stepper steps together
     * - Displays current step label
     * - Responsive design with mobile-friendly layout
     * - Accessible with proper ARIA roles
     * - Automatic step organization
     * - Visual step indicators
     * - Context-based current step display
     * - Flexible layout with CSS Grid/Flexbox
     * - Container queries for responsive behavior
     *
     * @example
     * <Stepper.List>
     *   <Stepper.Step controls="step1">Step 1</Stepper.Step>
     *   <Stepper.Step controls="step2">Step 2</Stepper.Step>
     *   <Stepper.Step controls="step3">Step 3</Stepper.Step>
     * </Stepper.List>
     */
    List: StepperList,
    /**
     * Content panel component for displaying step content in the Stepper.
     *
     * Features:
     * - Displays content for the current step only
     * - Smooth fade-in/fade-out animations
     * - Automatic overflow handling with scroll support
     * - Accessible with proper ARIA roles
     * - Layout utilities for positioning and spacing
     * - Motion animations for smooth transitions
     * - Focus management for keyboard navigation
     * - Responsive design with flexible layout
     * - Context-based visibility control
     *
     * @example
     * <Stepper.Panel id="step1">
     *   <h2>Personal Information</h2>
     *   <form>
     *     <label htmlFor="name">Name:</label>
     *     <input id="name" type="text" />
     *   </form>
     * </Stepper.Panel>
     */
    Panel: StepperPanel,
    /**
     * Next button component for navigating to the next step in the Stepper.
     *
     * Features:
     * - Automatically advances to the next step
     * - Changes label to "Complete" on the final step
     * - Supports async validation with Promise return
     * - Prevents navigation when validation fails
     * - Hides when all steps are completed
     * - Accessible with proper button semantics
     * - Customizable appearance and styling
     * - Integration with stepper context
     * - Automatic completion handling
     *
     * @example
     * <Stepper.NextButton
     *   nextLabel="Continue"
     *   completeLabel="Finish"
     * />
     *
     * @example
     * <Stepper.NextButton
     *   onClick={async (e) => {
     *     const isValid = await validateForm();
     *     return isValid;
     *   }}
     *   appearance="primary"
     * />
     */
    NextButton: StepperNextButton,
    /**
     * Previous button component for navigating to the previous step in the Stepper.
     *
     * Features:
     * - Navigates to the previous step when available
     * - Hides when on the first step
     * - Restores navigation when returning from completion
     * - Accessible with proper button semantics
     * - Customizable label and styling
     * - Integration with stepper context
     * - Automatic focus management
     * - Support for completion state handling
     *
     * @example
     * <Stepper.PrevButton label="Go Back" />
     *
     * @example
     * <Stepper.PrevButton
     *   label="Previous Step"
     *   appearance="secondary"
     *   onClick={(e) => console.log('Going back')}
     * />
     */
    PrevButton: StepperPrevButton,
    /**
     * Final panel component displayed when all stepper steps are completed.
     *
     * Features:
     * - Displays only when all steps are completed
     * - Smooth fade-in animation on completion
     * - Automatic overflow handling with scroll support
     * - Accessible with proper ARIA roles
     * - Layout utilities for positioning and spacing
     * - Motion animations for smooth transitions
     * - Focus management for keyboard navigation
     * - Responsive design with flexible layout
     * - Context-based visibility control
     *
     * @example
     * <Stepper.FinalPanel>
     *   <h2>Congratulations!</h2>
     *   <p>You have successfully completed all steps.</p>
     *   <Button onClick={handleSubmit}>Submit</Button>
     * </Stepper.FinalPanel>
     */
    FinalPanel: StepperFinalPanel
  }
);
Stepper.displayName = "Stepper";

export { Stepper as S };
//# sourceMappingURL=Stepper-CvaR7OoT.js.map
