import React, { useState } from 'react';
import classNames from 'classnames';
import { StepperItem } from './stepper-item';
import { jsx as _jsx } from "react/jsx-runtime";
export function isLastInList(index, listLength) {
  return index === listLength - 1;
}
export function getActiveStepIndex(steps, key) {
  return steps.findIndex(step => step.key === key);
}
export function isCompletedStep(stepIndex, activeStepIndex) {
  return stepIndex < activeStepIndex;
}

/** Stepper conveys progress through consecutive steps.
 * @uxr-only-supported
 * @midnight-gray-supported
 * @alpine-light-supported
 */
export function Stepper({
  steps,
  onClick,
  className,
  isDisabled,
  activeKey,
  testId = 'stepper'
}) {
  const [isActiveStepVisited, setIsActiveStepVisited] = useState(false);
  const activeStepIndex = getActiveStepIndex(steps, activeKey);
  function handleClick(key) {
    if (key === activeKey) {
      return;
    }
    const nextActiveStepIndex = getActiveStepIndex(steps, key);
    if (activeStepIndex > nextActiveStepIndex) {
      setIsActiveStepVisited(true);
    }
    if (isActiveStepVisited && activeStepIndex < nextActiveStepIndex) {
      setIsActiveStepVisited(false);
    }
    onClick(key);
  }
  return /*#__PURE__*/_jsx("ul", {
    className: classNames('stepper', className),
    "test-id": testId,
    children: steps.map(({
      key,
      icon,
      label,
      helperText,
      hasErrored,
      ...rest
    }, index) => {
      const isActive = activeKey === key;
      return /*#__PURE__*/_jsx(StepperItem, {
        stepKey: key,
        hasErrored: hasErrored,
        icon: icon,
        label: label,
        helperText: helperText,
        isDisabled: rest.isDisabled || isDisabled,
        isCompleted: index < activeStepIndex,
        onClick: handleClick,
        isRectHidden: isLastInList(index, steps.length),
        isActive: isActive,
        isVisited: isActive && isActiveStepVisited,
        testId: testId
      }, key);
    })
  });
}