import { WebStorageAdapter } from './chunk-WEEXCPSE.mjs';
import { useState, useEffect, useCallback } from 'react';

function useStorage(storage, key, defaultValue) {
  const [value, setValue] = useState(defaultValue);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const loadValue = async () => {
      try {
        const stored = await storage.getItem(key);
        if (stored !== null) {
          setValue(JSON.parse(stored));
        }
      } catch (error) {
        console.error('Error reading storage key "' + key + '":', error);
      } finally {
        setLoading(false);
      }
    };
    void loadValue();
  }, [storage, key]);
  const updateValue = useCallback(
    async (newValue) => {
      try {
        setValue(newValue);
        await storage.setItem(key, JSON.stringify(newValue));
        if ("dispatchChange" in storage && typeof storage.dispatchChange === "function") {
          storage.dispatchChange(key, JSON.stringify(newValue));
        }
      } catch (error) {
        console.error('Error setting storage key "' + key + '":', error);
      }
    },
    [storage, key]
  );
  const removeValue = useCallback(async () => {
    try {
      setValue(defaultValue);
      await storage.removeItem(key);
      if ("dispatchChange" in storage && typeof storage.dispatchChange === "function") {
        storage.dispatchChange(key, null);
      }
    } catch (error) {
      console.error('Error removing storage key "' + key + '":', error);
    }
  }, [storage, key, defaultValue]);
  useEffect(() => {
    if (!storage.addChangeListener) {
      return;
    }
    const cleanup = storage.addChangeListener((changedKey, newValue) => {
      if (changedKey === key) {
        try {
          if (newValue === null) {
            setValue(defaultValue);
          } else {
            setValue(JSON.parse(newValue));
          }
        } catch (error) {
          console.error("Error parsing storage change event:", error);
        }
      }
    });
    return cleanup;
  }, [storage, key, defaultValue]);
  return [value, updateValue, removeValue, loading];
}

// src/storage/hooks/useLocalStorage.ts
var webStorage = new WebStorageAdapter();
function useLocalStorage(key, defaultValue) {
  return useStorage(webStorage, key, defaultValue);
}

export { useLocalStorage, useStorage };
//# sourceMappingURL=chunk-VVWQTO4Y.mjs.map
//# sourceMappingURL=chunk-VVWQTO4Y.mjs.map