(function(window, document) {
  'use strict';

  var STORAGE_KEY = 'gfLocaleCountry';
  var cached = null;

  function normalizeCountry(code) {
    if (!code || typeof code !== 'string') {
      return '';
    }
    var trimmed = code.trim();
    if (trimmed.length !== 2) {
      return '';
    }
    return trimmed.toUpperCase();
  }

  function getStoredCountry() {
    try {
      var stored = window.sessionStorage ? window.sessionStorage.getItem(STORAGE_KEY) : '';
      return normalizeCountry(stored);
    } catch (e) {
      return '';
    }
  }

  function setStoredCountry(code) {
    var normalized = normalizeCountry(code);
    if (!normalized) {
      return;
    }
    try {
      if (window.sessionStorage) {
        window.sessionStorage.setItem(STORAGE_KEY, normalized);
      }
    } catch (e) {
      // ignore storage failures
    }
  }

  function extractRegion(locale) {
    if (!locale || typeof locale !== 'string') {
      return '';
    }
    var cleaned = locale.replace('_', '-');
    var parts = cleaned.split('-');
    if (window.Intl && window.Intl.Locale) {
      try {
        var intlLocale = new window.Intl.Locale(locale);
        if (intlLocale && intlLocale.region) {
          return normalizeCountry(intlLocale.region);
        }
      } catch (e) {
        // ignore
      }
    }
    for (var i = parts.length - 1; i >= 0; i -= 1) {
      var candidate = parts[i];
      if (candidate && candidate.length === 2) {
        return normalizeCountry(candidate);
      }
    }
    return '';
  }

  function getLocaleRegion() {
    var languages = (window.navigator && window.navigator.languages && window.navigator.languages.length)
      ? window.navigator.languages
      : [];
    var primary = (window.navigator && window.navigator.language) ? window.navigator.language : '';
    if (primary && languages.indexOf(primary) === -1) {
      languages.unshift(primary);
    }
    for (var i = 0; i < languages.length; i += 1) {
      var region = extractRegion(languages[i]);
      if (region) {
        return region;
      }
    }
    return '';
  }

  function resolveLocaleData() {
    if (cached) {
      return cached;
    }
    var stored = getStoredCountry();
    var locale = getLocaleRegion();
    cached = {
      stored: stored,
      locale: locale
    };
    return cached;
  }

  function getOptionCountry(option, selectEl) {
    if (!option) {
      return '';
    }
    if (selectEl && selectEl.classList.contains('griffinforms-phone-country-select')) {
      return normalizeCountry(option.getAttribute('data-iso') || '');
    }
    return normalizeCountry(option.value || '');
  }

  function findOptionByCountry(selectEl, country) {
    if (!selectEl || !country) {
      return null;
    }
    var options = selectEl.options || [];
    for (var i = 0; i < options.length; i += 1) {
      var opt = options[i];
      if (getOptionCountry(opt, selectEl) === country) {
        return opt;
      }
    }
    return null;
  }

  function applyDefaultToSelect(selectEl) {
    if (!selectEl || selectEl.disabled) {
      return;
    }
    if (selectEl.value && String(selectEl.value).trim() !== '') {
      return;
    }

    var localeData = resolveLocaleData();
    var candidates = [];
    if (localeData.stored) {
      candidates.push(localeData.stored);
    }
    if (localeData.locale && localeData.locale !== localeData.stored) {
      candidates.push(localeData.locale);
    }

    for (var i = 0; i < candidates.length; i += 1) {
      var option = findOptionByCountry(selectEl, candidates[i]);
      if (option) {
        selectEl.value = option.value;
        selectEl.dispatchEvent(new Event('change', { bubbles: true }));
        break;
      }
    }
  }

  function handleSelectChange(event) {
    var target = event.target;
    if (!target || !target.classList) {
      return;
    }
    if (target.classList.contains('griffinforms-phone-country-select')) {
      var selectedOption = target.options && target.selectedIndex >= 0 ? target.options[target.selectedIndex] : null;
      var iso = selectedOption ? selectedOption.getAttribute('data-iso') : '';
      setStoredCountry(iso);
      return;
    }
    if (target.classList.contains('gf-address-country')) {
      setStoredCountry(target.value || '');
    }
  }

  function applyDefaults(root) {
    var scope = root || document;
    var selects = scope.querySelectorAll('.griffinforms-phone-country-select, .gf-address-country');
    if (!selects.length) {
      return;
    }
    selects.forEach(function(selectEl) {
      applyDefaultToSelect(selectEl);
    });
  }

  document.addEventListener('change', handleSelectChange);
  document.addEventListener('DOMContentLoaded', function() {
    applyDefaults(document);
  });
  window.addEventListener('griffinformsFormLoaded', function() {
    applyDefaults(document);
  });

  window.GFLocaleUtils = {
    resolve: resolveLocaleData,
    applyDefaults: applyDefaults
  };
})(window, document);
