/**
 * incognito-detector.js
 * Detects if the browser is running in incognito/private mode
 * Uses LAZY initialization to avoid cascading failures at module load time
 */

let isIncognitoResult = null;
let storageTypeResult = null;

/**
 * Detect if browser is in incognito/private mode
 * Works by trying to write to localStorage and catching the silent failure
 * Result is memoized after first call
 */
function detectIncognito() {
  try {
    const testKey = '__incognito_test__';
    const testValue = Date.now().toString();

    // Try to write to localStorage
    localStorage.setItem(testKey, testValue);

    // Try to read it back
    const retrieved = localStorage.getItem(testKey);

    // Clean up
    localStorage.removeItem(testKey);

    // If we can write and read, we're not in incognito
    isIncognitoResult = retrieved !== testValue;
    storageTypeResult = isIncognitoResult ? 'sessionStorage' : 'localStorage';

    if (isIncognitoResult) {
      console.log('[IncognitoDetector] Incognito mode detected - using sessionStorage');
    }
    return isIncognitoResult;

  } catch (e) {
    // If localStorage access throws an error, we're definitely in incognito
    console.warn('[IncognitoDetector] Storage access failed, assuming incognito mode:', e);
    isIncognitoResult = true;
    storageTypeResult = 'sessionStorage';
    return true;
  }
}

/**
 * Get the appropriate storage object for this browser context
 * Triggers incognito detection if not yet done
 */
export function getStorage() {
  if (isIncognitoResult === null) {
    detectIncognito();
  }
  return isIncognitoResult ? sessionStorage : localStorage;
}

/**
 * Check if we're in incognito mode
 * Triggers detection if not yet done
 */
export function checkIncognito() {
  if (isIncognitoResult === null) {
    detectIncognito();
  }
  return isIncognitoResult;
}

/**
 * Set an item in the appropriate storage
 */
export function setItem(key, value) {
  try {
    getStorage().setItem(key, value);
    return true;
  } catch (e) {
    console.error('[IncognitoDetector] Failed to store item:', key, e);
    return false;
  }
}

/**
 * Get an item from the appropriate storage
 */
export function getItem(key) {
  try {
    return getStorage().getItem(key);
  } catch (e) {
    console.error('[IncognitoDetector] Failed to retrieve item:', key, e);
    return null;
  }
}

/**
 * Remove an item from the appropriate storage
 */
export function removeItem(key) {
  try {
    getStorage().removeItem(key);
    return true;
  } catch (e) {
    console.error('[IncognitoDetector] Failed to remove item:', key, e);
    return false;
  }
}

/**
 * Clear all items from the appropriate storage
 */
export function clear() {
  try {
    getStorage().clear();
    return true;
  } catch (e) {
    console.error('[IncognitoDetector] Failed to clear storage:', e);
    return false;
  }
}
