"use client";
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import {
  readJsonFromLocalStorage,
  writeJsonToLocalStorage
} from "@open-mercato/shared/lib/browser/safeLocalStorage";
const LOCAL_BROADCAST_EVENT = "om:persisted-boolean-flag:change";
const localEmitter = typeof window !== "undefined" ? new EventTarget() : null;
function readCurrentValue(storageKey, defaultValue) {
  const saved = readJsonFromLocalStorage(storageKey, null);
  if (saved === "1") return true;
  if (saved === "0") return false;
  return defaultValue;
}
function persistValue(storageKey, next) {
  writeJsonToLocalStorage(storageKey, next ? "1" : "0");
  localEmitter?.dispatchEvent(
    new CustomEvent(LOCAL_BROADCAST_EVENT, { detail: storageKey })
  );
}
function subscribe(storageKey, onChange) {
  if (typeof window === "undefined") return () => {
  };
  const handleStorage = (event) => {
    if (event.key === storageKey) onChange();
  };
  const handleLocal = (event) => {
    const detail = event.detail;
    if (detail === storageKey) onChange();
  };
  window.addEventListener("storage", handleStorage);
  localEmitter?.addEventListener(LOCAL_BROADCAST_EVENT, handleLocal);
  return () => {
    window.removeEventListener("storage", handleStorage);
    localEmitter?.removeEventListener(LOCAL_BROADCAST_EVENT, handleLocal);
  };
}
function usePersistedBooleanFlag(storageKey, defaultValue) {
  const [isHydrated, setIsHydrated] = useState(false);
  const getSnapshot = useCallback(
    () => readCurrentValue(storageKey, defaultValue),
    [storageKey, defaultValue]
  );
  const getServerSnapshot = useCallback(() => defaultValue, [defaultValue]);
  const subscribeKey = useCallback(
    (onChange) => subscribe(storageKey, onChange),
    [storageKey]
  );
  const value = useSyncExternalStore(subscribeKey, getSnapshot, getServerSnapshot);
  useEffect(() => {
    setIsHydrated(true);
  }, []);
  const setValue = useCallback(
    (next) => {
      const current = readCurrentValue(storageKey, defaultValue);
      const nextValue = typeof next === "function" ? next(current) : next;
      persistValue(storageKey, nextValue);
    },
    [storageKey, defaultValue]
  );
  const toggle = useCallback(() => {
    const current = readCurrentValue(storageKey, defaultValue);
    persistValue(storageKey, !current);
  }, [storageKey, defaultValue]);
  return { value, toggle, setValue, isHydrated };
}
export {
  usePersistedBooleanFlag
};
//# sourceMappingURL=usePersistedBooleanFlag.js.map
