"use client";

const memoryStorage = new Map<string, string>();

const getLocalStorage = () => {
  if (typeof window === "undefined") {
    return null;
  }

  try {
    return window.localStorage;
  } catch {
    return null;
  }
};

export const safeStorageGet = (key: string) => {
  const storage = getLocalStorage();

  if (!storage) {
    return memoryStorage.get(key) ?? null;
  }

  try {
    const value = storage.getItem(key);

    if (value !== null) {
      memoryStorage.set(key, value);
    }

    return value;
  } catch {
    return memoryStorage.get(key) ?? null;
  }
};

export const safeStorageSet = (key: string, value: string) => {
  memoryStorage.set(key, value);

  const storage = getLocalStorage();

  if (!storage) {
    return false;
  }

  try {
    storage.setItem(key, value);
    return true;
  } catch {
    return false;
  }
};

export const safeStorageRemove = (key: string) => {
  memoryStorage.delete(key);

  const storage = getLocalStorage();

  if (!storage) {
    return false;
  }

  try {
    storage.removeItem(key);
    return true;
  } catch {
    return false;
  }
};
