/**
 * 安全的本地存储工具 - 解决SSR环境localStorage不存在的问题
 */

// 安全的localStorage操作
export const safeLocalStorage = {
  // 获取数据
  getItem(key: string): string | null {
    if (typeof window === 'undefined') {
      return null;
    }
    try {
      return localStorage.getItem(key);
    } catch (error) {
      console.warn('Failed to get item from localStorage:', error);
      return null;
    }
  },

  // 设置数据
  setItem(key: string, value: string): void {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      localStorage.setItem(key, value);
    } catch (error) {
      console.warn('Failed to set item to localStorage:', error);
    }
  },

  // 删除数据
  removeItem(key: string): void {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      localStorage.removeItem(key);
    } catch (error) {
      console.warn('Failed to remove item from localStorage:', error);
    }
  },

  // 清空所有数据
  clear(): void {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      localStorage.clear();
    } catch (error) {
      console.warn('Failed to clear localStorage:', error);
    }
  }
};

// 安全的sessionStorage操作
export const safeSessionStorage = {
  // 获取数据
  getItem(key: string): string | null {
    if (typeof window === 'undefined') {
      return null;
    }
    try {
      return sessionStorage.getItem(key);
    } catch (error) {
      console.warn('Failed to get item from sessionStorage:', error);
      return null;
    }
  },

  // 设置数据
  setItem(key: string, value: string): void {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      sessionStorage.setItem(key, value);
    } catch (error) {
      console.warn('Failed to set item to sessionStorage:', error);
    }
  },

  // 删除数据
  removeItem(key: string): void {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      sessionStorage.removeItem(key);
    } catch (error) {
      console.warn('Failed to remove item from sessionStorage:', error);
    }
  },

  // 清空所有数据
  clear(): void {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      sessionStorage.clear();
    } catch (error) {
      console.warn('Failed to clear sessionStorage:', error);
    }
  }
};

// 检查是否在浏览器环境中
export const isBrowser = typeof window !== 'undefined';