/**
 * Language-scoped localStorage utilities.
 * Prevents cross-language conversation leakage in multilingual WordPress setups
 * (WPML, Polylang, etc.).
 *
 * The page language comes from window.boostbot_config.locale, set by PHP
 * when the widget loads. Storage keys are suffixed with the 2-letter language
 * code so each language gets its own conversation state.
 */

let _cachedLocale: string | null = null;

/**
 * Extract a 2-letter language code from a raw locale string.
 * 'en_US' → 'en', 'he-IL' → 'he', 'ar' → 'ar'
 */
function normalizeLocale(raw: string): string {
  return raw.split(/[_-]/)[0].toLowerCase() || 'en';
}

/**
 * Get the current page language code (e.g. 'en', 'he', 'ar').
 */
export function getCurrentLocale(): string {
  if (_cachedLocale) return _cachedLocale;
  const raw =
    window.boostbot_config?.locale ||
    document.documentElement.lang ||
    'en';
  _cachedLocale = normalizeLocale(raw);
  return _cachedLocale;
}

/**
 * Force-refresh the cached locale. Call when language change is detected.
 */
export function refreshLocale(): string {
  _cachedLocale = null;
  return getCurrentLocale();
}

/**
 * Build a language-scoped localStorage key.
 */
export function getStorageKey(baseKey: string): string {
  return `${baseKey}_${getCurrentLocale()}`;
}

/**
 * Migrate unscoped localStorage data to language-scoped keys.
 * Runs once per browser on first load after the feature ships.
 *
 * Uses primary_language (site default) or current locale to decide which
 * language bucket receives the historical data.
 */
export function migrateUnscopedStorage(): void {
  const MIGRATION_FLAG = 'boostbot_locale_migrated';
  try {
    if (localStorage.getItem(MIGRATION_FLAG)) return;

    // Prefer the site's primary language so the data lands in the right bucket
    // even if the user happens to load a secondary-language page first.
    const primaryRaw =
      window.boostbot_config?.primary_language ||
      window.boostbot_config?.locale ||
      document.documentElement.lang ||
      'en';
    const targetLocale = normalizeLocale(primaryRaw);

    // --- Zustand persist store ---
    const chatData = localStorage.getItem('boostbot-chat');
    if (chatData && !localStorage.getItem(`boostbot-chat_${targetLocale}`)) {
      localStorage.setItem(`boostbot-chat_${targetLocale}`, chatData);
    }
    if (chatData) localStorage.removeItem('boostbot-chat');

    // --- Visit count ---
    const visitCount = localStorage.getItem('boostbot_visit_count');
    if (visitCount && !localStorage.getItem(`boostbot_visit_count_${targetLocale}`)) {
      localStorage.setItem(`boostbot_visit_count_${targetLocale}`, visitCount);
    }
    if (visitCount) localStorage.removeItem('boostbot_visit_count');

    // --- Trigger keys (boostbot_trigger_*) ---
    const keysToMigrate: string[] = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key?.startsWith('boostbot_trigger_')) {
        keysToMigrate.push(key);
      }
    }
    for (const key of keysToMigrate) {
      const scopedKey = `${key}_${targetLocale}`;
      const value = localStorage.getItem(key);
      if (value && !localStorage.getItem(scopedKey)) {
        localStorage.setItem(scopedKey, value);
      }
      localStorage.removeItem(key);
    }

    localStorage.setItem(MIGRATION_FLAG, '1');
  } catch {
    // Ignore storage errors (e.g. private browsing, quota exceeded)
  }
}
