"use client";

// src/hooks/useLocalStorage.ts
import { useCallback, useState } from "react";

// src/utils/storage.ts
var StorageService = class {
  // this seems to be a bug in eslint as 'paramter-properties' is a special syntax of typescript
  constructor(storage) {
    this.storage = storage;
  }
  get(key) {
    const value = this.storage.getItem(key);
    if (value === null) {
      return null;
    }
    return JSON.parse(value);
  }
  set(key, value) {
    this.storage.setItem(key, JSON.stringify(value));
  }
  delete(key) {
    this.storage.removeItem(key);
  }
  deleteAll() {
    this.storage.clear();
  }
};
var LocalStorageService = class extends StorageService {
  constructor() {
    super(window.localStorage);
  }
};

// src/utils/resolveSetState.ts
function resolveSetState(action, prev) {
  return typeof action === "function" ? action(prev) : action;
}

// src/hooks/useLocalStorage.ts
var useLocalStorage = (key, backupValue) => {
  const get = useCallback(() => {
    if (typeof window === "undefined") {
      return backupValue;
    }
    const storageService = new LocalStorageService();
    try {
      const value = storageService.get(key);
      return value || backupValue;
    } catch (_) {
      console.warn("useLocalStorage: Error while reading the stored value. Make sure your typing is correct.");
      storageService.delete(key);
      console.info(`useLocalStorage: deleted erroneous value for key: ${key}`);
      return backupValue;
    }
  }, [backupValue, key]);
  const [storedValue, setStoredValue] = useState(get);
  const setValue = useCallback((action) => {
    const newValue = resolveSetState(action, storedValue);
    const storageService = new LocalStorageService();
    storageService.set(key, newValue);
    setStoredValue(newValue);
  }, [storedValue, setStoredValue, key]);
  const deleteValue = () => {
    const storageService = new LocalStorageService();
    storageService.delete(key);
    setStoredValue(backupValue);
  };
  return { value: storedValue, setValue, deleteValue };
};
export {
  useLocalStorage
};
//# sourceMappingURL=useLocalStorage.js.map