"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSessionStorageState = exports.getSessionStorageValue = void 0;
var _react = require("react");
var _useMountLifecycleEffect = require("./useMountLifecycleEffect.cjs");
/*!
 * Copyright (c) 2025-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 getSessionStorageValue = key => {
  const sessionStorageValue = window.sessionStorage.getItem(key);
  try {
    if (typeof sessionStorageValue === "string") {
      return JSON.parse(sessionStorageValue);
    }
    return null;
  } catch {
    if (typeof sessionStorageValue === "string") {
      return sessionStorageValue;
    }
    return null;
  }
};
exports.getSessionStorageValue = getSessionStorageValue;
const useSessionStorageState = ({
  initialState,
  key
}) => {
  if (!key) {
    throw new Error("You must pass a value for `key`.");
  }
  const sessionState = (0, _react.useMemo)(() => getSessionStorageValue(key), [key]);
  const setSessionState = (0, _react.useCallback)(value => {
    const sessionStorageState = typeof value === "undefined" ? "" : JSON.stringify(value);
    window.sessionStorage.setItem(key, sessionStorageState);
  }, [key]);
  const [localState, setLocalState] = (0, _react.useState)(() => sessionState ?? initialState);
  (0, _react.useEffect)(() => {
    setSessionState(localState);
  }, [localState, setSessionState]);
  const onUpdate = (0, _react.useCallback)(() => {
    setLocalState(sessionState ?? initialState);
  }, [initialState, sessionState]);
  (0, _useMountLifecycleEffect.useMountLifecycleEffect)({
    onUpdate
  });
  return {
    sessionState: localState,
    setSessionState: setLocalState
  };
};
exports.useSessionStorageState = useSessionStorageState;
//# sourceMappingURL=useSessionStorageState.cjs.map