"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Switch = void 0;
var _FormLabel2 = _interopRequireDefault(require("@mui/material/FormLabel"));
var _styled = _interopRequireDefault(require("@emotion/styled"));
var _react = require("react");
var _Box = require("./Box.cjs");
var _FieldHint = require("./FieldHint.cjs");
var _i18n = require("./i18n.generated/i18n.cjs");
var _index = require("./icons.generated/index.cjs");
var _inputUtils = require("./inputUtils.cjs");
var _OdysseyDesignTokensContext = require("./OdysseyDesignTokensContext.cjs");
var _remUtils = require("./remUtils.cjs");
var _useUniqueId = require("./useUniqueId.cjs");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/*!
 * Copyright (c) 2022-present, Okta, Inc. and/or its affiliates. All rights reserved.
 * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 */

const {
  CONTROLLED
} = _inputUtils.ComponentControlledState;
const nonForwardedProps = ["isChecked", "isDisabled", "isFullWidth", "isReadOnly", "odysseyDesignTokens"];
const SwitchAndLabelContainer = (0, _styled.default)("div", {
  shouldForwardProp: prop => !nonForwardedProps.includes(prop)
})(({
  isFullWidth,
  odysseyDesignTokens
}) => ({
  display: "flex",
  alignItems: "flex-start",
  justifyContent: "space-between",
  maxWidth: isFullWidth ? "100%" : odysseyDesignTokens.TypographyLineLengthMax
}));
const SwitchContainer = _styled.default.div({
  position: "relative"
});
const StyledSwitchLabel = (0, _styled.default)(_FormLabel2.default, {
  shouldForwardProp: prop => !nonForwardedProps.includes(prop)
})(({
  isDisabled,
  isReadOnly,
  odysseyDesignTokens
}) => ({
  display: "block",
  margin: 0,
  color: odysseyDesignTokens.PaletteNeutralDark,
  ...(isDisabled && {
    color: odysseyDesignTokens.TypographyColorDisabled,
    p: {
      color: odysseyDesignTokens.TypographyColorDisabled
    },
    a: {
      color: `${odysseyDesignTokens.TypographyColorDisabled} !important`
    }
  }),
  ...(isReadOnly && {
    color: odysseyDesignTokens.HueNeutral700,
    p: {
      color: odysseyDesignTokens.HueNeutral700
    },
    a: {
      color: `${odysseyDesignTokens.HueNeutral700} !important`
    }
  })
}));
const SwitchTrack = (0, _styled.default)("div", {
  shouldForwardProp: prop => !nonForwardedProps.includes(prop)
})(({
  isChecked,
  isDisabled,
  isReadOnly,
  odysseyDesignTokens
}) => ({
  position: "relative",
  width: odysseyDesignTokens.Spacing7,
  height: `calc(${odysseyDesignTokens.Spacing4} + ${odysseyDesignTokens.Spacing1})`,
  borderRadius: odysseyDesignTokens.BorderRadiusOuter,
  backgroundColor: odysseyDesignTokens.HueNeutral300,
  transition: `background-color ${odysseyDesignTokens.TransitionDurationMain}`,
  ...(isDisabled && {
    backgroundColor: odysseyDesignTokens.HueNeutral200
  }),
  ...(isReadOnly && {
    backgroundColor: odysseyDesignTokens.HueNeutral600
  }),
  ...(isChecked && !isDisabled && !isReadOnly && {
    backgroundColor: odysseyDesignTokens.PaletteSuccessLight
  })
}));
const SwitchThumb = (0, _styled.default)("span", {
  shouldForwardProp: prop => !nonForwardedProps.includes(prop)
})(({
  isChecked,
  isDisabled,
  isReadOnly,
  odysseyDesignTokens
}) => {
  const thumbOffset = (0, _remUtils.toRem)(3);
  const trackWidth = (0, _remUtils.stripRem)(odysseyDesignTokens.Spacing7);
  const thumbWidth = (0, _remUtils.stripRem)(odysseyDesignTokens.Spacing4) - (0, _remUtils.toRem)(2);
  const transformDistance = trackWidth - thumbWidth - thumbOffset * 2;
  return {
    position: "absolute",
    top: "50%",
    left: `${thumbOffset}rem`,
    width: `calc(${odysseyDesignTokens.Spacing4} - ${(0, _remUtils.toRem)(2)}rem)`,
    height: `calc(${odysseyDesignTokens.Spacing4} - ${(0, _remUtils.toRem)(2)}rem)`,
    borderRadius: odysseyDesignTokens.BorderRadiusRound,
    backgroundColor: odysseyDesignTokens.HueNeutralWhite,
    transform: "translate3d(0, -50%, 0)",
    transition: `transform ${odysseyDesignTokens.TransitionDurationMain}`,
    ...(isDisabled && {
      backgroundColor: odysseyDesignTokens.HueNeutral50
    }),
    ...(isReadOnly && {
      backgroundColor: odysseyDesignTokens.HueNeutral400
    }),
    ...(isChecked && {
      transform: `translate3d(${transformDistance}rem, -50%, 0)`
    })
  };
});
const SwitchCheckMark = (0, _styled.default)(_index.CheckIcon, {
  shouldForwardProp: prop => !nonForwardedProps.includes(prop)
})(({
  isChecked,
  isDisabled,
  isReadOnly,
  odysseyDesignTokens
}) => ({
  position: "absolute",
  top: "50%",
  left: 3,
  width: odysseyDesignTokens.Spacing4,
  transform: "translateY(-50%)",
  transition: `opacity ${odysseyDesignTokens.TransitionDurationMain}`,
  opacity: 0,
  path: {
    fill: odysseyDesignTokens.HueNeutralWhite
  },
  ...(isChecked && {
    opacity: 1
  }),
  ...((isDisabled || isReadOnly) && {
    path: {
      fill: odysseyDesignTokens.HueNeutral50
    }
  })
}));
const HiddenCheckbox = _styled.default.input(({
  odysseyDesignTokens,
  isReadOnly
}) => ({
  position: "absolute",
  top: 0,
  left: 0,
  width: "100%",
  height: "100%",
  margin: 0,
  opacity: 0,
  cursor: isReadOnly ? "default" : "pointer",
  zIndex: 2,
  "&:focus-visible": {
    "~ [data-switch-track='true']": {
      boxShadow: `0 0 0 2px ${odysseyDesignTokens.HueNeutralWhite}, 0 0 0 4px ${odysseyDesignTokens.PalettePrimaryMain}`
    }
  }
}));
const SwitchLabel = ({
  hint,
  hintId,
  HintLinkComponent,
  inputId,
  isDisabled,
  label,
  isReadOnly
}) => {
  const odysseyDesignTokens = (0, _OdysseyDesignTokensContext.useOdysseyDesignTokens)();
  return (0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
    children: (0, _jsxRuntime.jsxs)(StyledSwitchLabel, {
      htmlFor: inputId,
      isDisabled: isDisabled,
      isReadOnly: isReadOnly,
      odysseyDesignTokens: odysseyDesignTokens,
      children: [label, hint && (0, _jsxRuntime.jsx)(_FieldHint.FieldHint, {
        id: hintId,
        LinkComponent: HintLinkComponent,
        text: hint
      })]
    })
  });
};
const MemoizedSwitchLabel = (0, _react.memo)(SwitchLabel);
SwitchLabel.displayName = "SwitchLabel";
const Switch = ({
  hint,
  HintLinkComponent,
  id: idProp,
  isChecked,
  isDefaultChecked,
  isDisabled,
  isFullWidth = false,
  isReadOnly = false,
  label,
  name,
  onChange,
  testId,
  value
}) => {
  const {
    t
  } = (0, _i18n.useTranslation)();
  const odysseyDesignTokens = (0, _OdysseyDesignTokensContext.useOdysseyDesignTokens)();
  const controlledStateRef = (0, _react.useRef)((0, _inputUtils.getControlState)({
    controlledValue: isChecked,
    uncontrolledValue: isDefaultChecked
  }));
  const inputValues = (0, _react.useMemo)(() => {
    if (controlledStateRef.current === CONTROLLED) {
      return {
        checked: isChecked
      };
    }
    return {
      defaultChecked: isDefaultChecked
    };
  }, [isDefaultChecked, isChecked]);
  const [internalSwitchChecked, setInternalSwitchChecked] = (0, _react.useState)(controlledStateRef.current === CONTROLLED ? Boolean(isChecked) : Boolean(isDefaultChecked));
  (0, _react.useEffect)(() => {
    if (controlledStateRef.current === CONTROLLED) {
      setInternalSwitchChecked(Boolean(isChecked));
    }
  }, [isChecked]);
  const inputId = (0, _useUniqueId.useUniqueId)(idProp);
  const hintId = hint ? `${inputId}-hint` : undefined;
  const labelElementId = `${inputId}-label`;
  const handleOnChange = (0, _react.useCallback)(event => {
    if (isReadOnly) {
      event.preventDefault();
      return;
    }
    const target = event.target;
    const {
      checked,
      value
    } = target;
    setInternalSwitchChecked(checked);
    onChange?.({
      checked,
      value
    });
  }, [onChange, setInternalSwitchChecked, isReadOnly]);
  return (0, _jsxRuntime.jsx)(_Box.Box, {
    sx: {
      marginBlockEnd: odysseyDesignTokens.Spacing2,
      "&:last-child": {
        marginBlockEnd: 0
      }
    },
    children: (0, _jsxRuntime.jsxs)(SwitchAndLabelContainer, {
      isFullWidth: isFullWidth,
      odysseyDesignTokens: odysseyDesignTokens,
      children: [(0, _jsxRuntime.jsx)(MemoizedSwitchLabel, {
        hint: hint,
        hintId: hintId,
        HintLinkComponent: HintLinkComponent,
        inputId: inputId,
        isDisabled: isDisabled,
        isFullWidth: isFullWidth,
        isReadOnly: isReadOnly,
        label: label
      }), (0, _jsxRuntime.jsxs)(SwitchContainer, {
        children: [(0, _jsxRuntime.jsx)(HiddenCheckbox, {
          ...inputValues,
          "aria-checked": internalSwitchChecked,
          "aria-describedby": hintId,
          "aria-label": internalSwitchChecked ? `${label}: ${t("switch.active")}` : `${label}: ${t("switch.inactive")}`,
          "aria-labelledby": labelElementId,
          "data-se": testId,
          disabled: isDisabled,
          id: inputId,
          isReadOnly: isReadOnly,
          name: name ?? inputId,
          odysseyDesignTokens: odysseyDesignTokens,
          onChange: handleOnChange,
          readOnly: isReadOnly,
          type: "checkbox",
          value: value
        }), (0, _jsxRuntime.jsxs)(SwitchTrack, {
          "data-switch-track": true,
          isChecked: internalSwitchChecked,
          isDisabled: isDisabled,
          isReadOnly: isReadOnly,
          odysseyDesignTokens: odysseyDesignTokens,
          children: [(0, _jsxRuntime.jsx)(SwitchThumb, {
            isChecked: internalSwitchChecked,
            isDisabled: isDisabled,
            isReadOnly: isReadOnly,
            odysseyDesignTokens: odysseyDesignTokens
          }), (0, _jsxRuntime.jsx)(SwitchCheckMark, {
            isChecked: internalSwitchChecked,
            isDisabled: isDisabled,
            isReadOnly: isReadOnly,
            odysseyDesignTokens: odysseyDesignTokens
          })]
        })]
      })]
    })
  });
};
const MemoizedSwitch = exports.Switch = (0, _react.memo)(Switch);
MemoizedSwitch.displayName = "Switch";
//# sourceMappingURL=Switch.cjs.map