import { useState, useEffect, useCallback } from 'react';

var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// src/storage/adapters/web-adapter.ts
var isBrowser = typeof window !== "undefined" && typeof window.localStorage !== "undefined";
var WebStorageAdapter = class {
  async getItem(key) {
    if (!isBrowser) {
      return null;
    }
    try {
      return localStorage.getItem(key);
    } catch (error) {
      console.error('[WebStorage] Error getting item "' + key + '":', error);
      return null;
    }
  }
  async setItem(key, value) {
    if (!isBrowser) {
      return;
    }
    try {
      localStorage.setItem(key, value);
    } catch (error) {
      console.error('[WebStorage] Error setting item "' + key + '":', error);
      throw error;
    }
  }
  async removeItem(key) {
    if (!isBrowser) {
      return;
    }
    try {
      localStorage.removeItem(key);
    } catch (error) {
      console.error('[WebStorage] Error removing item "' + key + '":', error);
      throw error;
    }
  }
  async clear() {
    if (!isBrowser) {
      return;
    }
    try {
      localStorage.clear();
    } catch (error) {
      console.error("[WebStorage] Error clearing storage:", error);
      throw error;
    }
  }
  addChangeListener(callback) {
    if (!isBrowser) {
      return () => {
      };
    }
    const handleStorageEvent = (e) => {
      if (e.key) {
        callback(e.key, e.newValue);
      }
    };
    const handleCustomEvent = (e) => {
      const customEvent = e;
      callback(customEvent.detail.key, customEvent.detail.value);
    };
    window.addEventListener("storage", handleStorageEvent);
    window.addEventListener("local-storage-change", handleCustomEvent);
    return () => {
      window.removeEventListener("storage", handleStorageEvent);
      window.removeEventListener("local-storage-change", handleCustomEvent);
    };
  }
  /**
   * 触发自定义事件，通知同标签页的其他组件
   */
  dispatchChange(key, value) {
    if (!isBrowser) {
      return;
    }
    window.dispatchEvent(
      new CustomEvent("local-storage-change", {
        detail: { key, value }
      })
    );
  }
};

// src/storage/adapters/react-native-adapter.ts
var AsyncStorage = null;
try {
  AsyncStorage = __require("@react-native-async-storage/async-storage").default;
} catch (e) {
}
var ReactNativeStorageAdapter = class {
  constructor() {
    this.listeners = /* @__PURE__ */ new Map();
  }
  async getItem(key) {
    if (!AsyncStorage) return null;
    try {
      return await AsyncStorage.getItem(key);
    } catch (error) {
      console.error('[ReactNativeStorage] Error getting item "' + key + '":', error);
      return null;
    }
  }
  async setItem(key, value) {
    if (!AsyncStorage) {
      throw new Error("AsyncStorage is not available");
    }
    try {
      await AsyncStorage.setItem(key, value);
      this.notifyListeners(key, value);
    } catch (error) {
      console.error('[ReactNativeStorage] Error setting item "' + key + '":', error);
      throw error;
    }
  }
  async removeItem(key) {
    if (!AsyncStorage) {
      throw new Error("AsyncStorage is not available");
    }
    try {
      await AsyncStorage.removeItem(key);
      this.notifyListeners(key, null);
    } catch (error) {
      console.error('[ReactNativeStorage] Error removing item "' + key + '":', error);
      throw error;
    }
  }
  async clear() {
    if (!AsyncStorage) {
      throw new Error("AsyncStorage is not available");
    }
    try {
      await AsyncStorage.clear();
    } catch (error) {
      console.error("[ReactNativeStorage] Error clearing storage:", error);
      throw error;
    }
  }
  addChangeListener(callback) {
    if (!this.listeners.has("*")) {
      this.listeners.set("*", /* @__PURE__ */ new Set());
    }
    this.listeners.get("*").add(callback);
    return () => {
      this.listeners.get("*")?.delete(callback);
    };
  }
  notifyListeners(key, value) {
    const globalListeners = this.listeners.get("*");
    if (globalListeners) {
      globalListeners.forEach((callback) => callback(key, value));
    }
  }
};

// src/storage/adapters/miniapp-adapter.ts
var Taro = null;
var taroLoadPromise = null;
var isMiniAppEnvironment = null;
function checkIsMiniApp() {
  if (isMiniAppEnvironment !== null) return isMiniAppEnvironment;
  if (typeof window === "undefined") {
    isMiniAppEnvironment = false;
    return false;
  }
  const globalObj = window;
  isMiniAppEnvironment = !!(globalObj.wx || // 微信小程序
  globalObj.my || // 支付宝小程序
  globalObj.swan || // 百度小程序
  globalObj.tt || // 抖音小程序
  globalObj.qq || // QQ 小程序
  globalObj.Taro);
  return isMiniAppEnvironment;
}
async function loadTaro() {
  if (!checkIsMiniApp()) {
    return;
  }
  if (Taro) return;
  if (taroLoadPromise) return taroLoadPromise;
  taroLoadPromise = (async () => {
    try {
      const importTaro = new Function('return import("@tarojs/taro")');
      const taroModule = await importTaro();
      Taro = taroModule.default || taroModule;
    } catch (e) {
      console.warn("[MiniAppStorage] Taro is not available. This is expected in non-MiniApp environments.");
    }
  })();
  return taroLoadPromise;
}
var MiniAppStorageAdapter = class {
  constructor() {
    this.listeners = /* @__PURE__ */ new Map();
  }
  async getItem(key) {
    if (!checkIsMiniApp()) {
      return null;
    }
    await loadTaro();
    if (!Taro) return null;
    try {
      const result = await Taro.getStorage({ key });
      return result.data;
    } catch (error) {
      if (error.errMsg?.includes("data not found")) {
        return null;
      }
      console.error('[MiniAppStorage] Error getting item "' + key + '":', error);
      return null;
    }
  }
  async setItem(key, value) {
    if (!checkIsMiniApp()) {
      throw new Error("[MiniAppStorage] This adapter can only be used in MiniApp environment");
    }
    await loadTaro();
    if (!Taro) {
      throw new Error("[MiniAppStorage] Taro is not available");
    }
    try {
      await Taro.setStorage({ key, data: value });
      this.notifyListeners(key, value);
    } catch (error) {
      console.error('[MiniAppStorage] Error setting item "' + key + '":', error);
      throw error;
    }
  }
  async removeItem(key) {
    if (!checkIsMiniApp()) {
      throw new Error("[MiniAppStorage] This adapter can only be used in MiniApp environment");
    }
    await loadTaro();
    if (!Taro) {
      throw new Error("[MiniAppStorage] Taro is not available");
    }
    try {
      await Taro.removeStorage({ key });
      this.notifyListeners(key, null);
    } catch (error) {
      console.error('[MiniAppStorage] Error removing item "' + key + '":', error);
      throw error;
    }
  }
  async clear() {
    if (!checkIsMiniApp()) {
      throw new Error("[MiniAppStorage] This adapter can only be used in MiniApp environment");
    }
    await loadTaro();
    if (!Taro) {
      throw new Error("[MiniAppStorage] Taro is not available");
    }
    try {
      await Taro.clearStorage();
    } catch (error) {
      console.error("[MiniAppStorage] Error clearing storage:", error);
      throw error;
    }
  }
  addChangeListener(callback) {
    if (!this.listeners.has("*")) {
      this.listeners.set("*", /* @__PURE__ */ new Set());
    }
    this.listeners.get("*").add(callback);
    return () => {
      this.listeners.get("*")?.delete(callback);
    };
  }
  notifyListeners(key, value) {
    const globalListeners = this.listeners.get("*");
    if (globalListeners) {
      globalListeners.forEach((callback) => callback(key, value));
    }
  }
};

// src/storage/adapters/electron-adapter.ts
var hasLocalStorage = typeof window !== "undefined" && typeof window.localStorage !== "undefined";
var ElectronStorageAdapter = class {
  constructor() {
    this.listeners = /* @__PURE__ */ new Map();
  }
  async getItem(key) {
    if (!hasLocalStorage) {
      return null;
    }
    try {
      return localStorage.getItem(key);
    } catch (error) {
      console.error('[ElectronStorage] Error getting item "' + key + '":', error);
      return null;
    }
  }
  async setItem(key, value) {
    if (!hasLocalStorage) {
      return;
    }
    try {
      localStorage.setItem(key, value);
      this.notifyListeners(key, value);
      if (typeof window !== "undefined") {
        window.dispatchEvent(
          new CustomEvent("electron-storage-change", {
            detail: { key, value }
          })
        );
      }
    } catch (error) {
      console.error('[ElectronStorage] Error setting item "' + key + '":', error);
      throw error;
    }
  }
  async removeItem(key) {
    if (!hasLocalStorage) {
      return;
    }
    try {
      localStorage.removeItem(key);
      this.notifyListeners(key, null);
      if (typeof window !== "undefined") {
        window.dispatchEvent(
          new CustomEvent("electron-storage-change", {
            detail: { key, value: null }
          })
        );
      }
    } catch (error) {
      console.error('[ElectronStorage] Error removing item "' + key + '":', error);
      throw error;
    }
  }
  async clear() {
    if (!hasLocalStorage) {
      return;
    }
    try {
      localStorage.clear();
      this.listeners.forEach((listeners, key) => {
        listeners.forEach((listener) => {
          listener(key, null);
        });
      });
      if (typeof window !== "undefined") {
        window.dispatchEvent(
          new CustomEvent("electron-storage-change", {
            detail: { key: "*", value: null }
          })
        );
      }
    } catch (error) {
      console.error("[ElectronStorage] Error clearing storage:", error);
      throw error;
    }
  }
  /**
   * 添加存储变化监听器
   * 支持跨 Electron 窗口同步
   */
  addChangeListener(listener) {
    const allListeners = this.listeners.get("*") || /* @__PURE__ */ new Set();
    allListeners.add(listener);
    this.listeners.set("*", allListeners);
    const storageHandler = (e) => {
      if (e.key) {
        listener(e.key, e.newValue);
      }
    };
    const customHandler = (e) => {
      const customEvent = e;
      const { key, value } = customEvent.detail;
      if (key === "*") {
        this.listeners.forEach((_, k) => listener(k, null));
      } else {
        listener(key, value);
      }
    };
    if (typeof window !== "undefined") {
      window.addEventListener("storage", storageHandler);
      window.addEventListener("electron-storage-change", customHandler);
    }
    return () => {
      allListeners.delete(listener);
      if (allListeners.size === 0) {
        this.listeners.delete("*");
      }
      if (typeof window !== "undefined") {
        window.removeEventListener("storage", storageHandler);
        window.removeEventListener("electron-storage-change", customHandler);
      }
    };
  }
  removeChangeListener(listener) {
    const allListeners = this.listeners.get("*");
    if (allListeners) {
      allListeners.delete(listener);
      if (allListeners.size === 0) {
        this.listeners.delete("*");
      }
    }
  }
  /**
   * 通知监听器
   */
  notifyListeners(key, value) {
    const keyListeners = this.listeners.get(key);
    if (keyListeners) {
      keyListeners.forEach((listener) => {
        listener(key, value);
      });
    }
    const allListeners = this.listeners.get("*");
    if (allListeners) {
      allListeners.forEach((listener) => {
        listener(key, value);
      });
    }
  }
};
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);
}

// src/storage/hooks/useAsyncStorage.ts
var asyncStorage = new ReactNativeStorageAdapter();
function useAsyncStorage(key, defaultValue) {
  return useStorage(asyncStorage, key, defaultValue);
}

// src/storage/hooks/useTaroStorage.ts
var taroStorage = new MiniAppStorageAdapter();
function useTaroStorage(key, defaultValue) {
  return useStorage(taroStorage, key, defaultValue);
}

// src/storage/hooks/useElectronStorage.ts
var electronStorage = new ElectronStorageAdapter();
function useElectronStorage(key, defaultValue) {
  return useStorage(electronStorage, key, defaultValue);
}

export { ElectronStorageAdapter, MiniAppStorageAdapter, ReactNativeStorageAdapter, WebStorageAdapter, useAsyncStorage, useElectronStorage, useLocalStorage, useStorage, useTaroStorage };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map