// 创建内存存储替代方案，完全不依赖浏览器的 localStorage/sessionStorage
// 避免在某些浏览器（隐私模式、跨域、移动浏览器）中触发权限弹窗或报错

const memoryStorage = {};
const sessionMemoryStorage = {};

// 创建一个模拟的 storage 对象
const createStorageMock = (storage) => ({
  getItem: (key) => {
    return Object.prototype.hasOwnProperty.call(storage, key) ? storage[key] : null;
  },
  setItem: (key, value) => {
    storage[key] = String(value);
  },
  removeItem: (key) => {
    delete storage[key];
  },
  clear: () => {
    Object.keys(storage).forEach(key => delete storage[key]);
  },
  key: (i) => {
    const keys = Object.keys(storage);
    return keys[i] || null;
  },
  get length() {
    return Object.keys(storage).length;
  }
});

// 检测 localStorage 是否可用（静默检测，不触发弹窗）
let localStorageAvailable = false;
let testPerformed = false;

try {
  // 在某些浏览器中，仅访问 localStorage 就会触发权限弹窗
  // 我们需要在一个静默的 try-catch 中进行测试
  const testKey = '__mengyanote_storage_test__';
  const testValue = 'test';
  
  // 设置超时，避免阻塞
  const storage = window.localStorage;
  storage.setItem(testKey, testValue);
  const retrieved = storage.getItem(testKey);
  storage.removeItem(testKey);
  
  if (retrieved === testValue) {
    localStorageAvailable = true;
    testPerformed = true;
    console.log('[MengyaNote] ✓ Native localStorage is available');
  }
} catch (e) {
  testPerformed = true;
  localStorageAvailable = false;
  console.warn('[MengyaNote] ✗ LocalStorage unavailable:', e.name);
  // 注意：不输出完整错误信息，避免暴露敏感信息
}

// 如果 localStorage 不可用，强制使用内存存储
if (!localStorageAvailable && testPerformed) {
  try {
    const localStorageMock = createStorageMock(memoryStorage);
    const sessionStorageMock = createStorageMock(sessionMemoryStorage);
    
    // 覆盖 window.localStorage
    Object.defineProperty(window, 'localStorage', {
      value: localStorageMock,
      configurable: false,
      enumerable: true,
      writable: false
    });
    
    // 覆盖 window.sessionStorage
    Object.defineProperty(window, 'sessionStorage', {
      value: sessionStorageMock,
      configurable: false,
      enumerable: true,
      writable: false
    });
    
    console.log('[MengyaNote] ✓ Memory storage initialized as fallback');
  } catch (err) {
    console.error('[MengyaNote] ✗ Failed to initialize memory storage:', err.name);
    // 即使失败也不影响应用运行，因为数据主要来自后端API
  }
}

// 导出一个安全的存储API，供应用使用（双重保险）
export const safeStorage = {
  get: (key) => {
    try {
      const value = window.localStorage.getItem(key);
      return value;
    } catch (e) {
      console.warn('[MengyaNote] Storage get failed, using memory fallback');
      return memoryStorage[key] || null;
    }
  },
  set: (key, value) => {
    try {
      window.localStorage.setItem(key, value);
    } catch (e) {
      console.warn('[MengyaNote] Storage set failed, using memory fallback');
      memoryStorage[key] = String(value);
    }
  },
  remove: (key) => {
    try {
      window.localStorage.removeItem(key);
    } catch (e) {
      delete memoryStorage[key];
    }
  },
  clear: () => {
    try {
      window.localStorage.clear();
    } catch (e) {
      Object.keys(memoryStorage).forEach(key => delete memoryStorage[key]);
    }
  }
};

// 作为默认导出，方便导入
export default safeStorage;
