(function () {
  'use strict';
  var base = (window.MJ_BASE_URL || '').replace(/\/$/, '');
  var autoRedirect = !!window.MJ_AUTO_COUNTRY_REDIRECT;
  if (window.MJ_AREA_DETECTION === false) return;
  var noAuto = window.location.search.indexOf('no_auto_country=1') !== -1;
  var now = Date.now();
  var last = 0;
  try { last = parseInt(localStorage.getItem('mj_area_detected_at') || '0', 10); } catch(e) {}
  var fresh = last && (now - last < 1000 * 60 * 60 * 12);

  function rememberAndMaybeRedirect(payload) {
    if (!payload || !payload.ok) return;
    try {
      localStorage.setItem('mj_area_detected_at', String(Date.now()));
      localStorage.setItem('mj_area_label', payload.label || payload.country_name || '');
      localStorage.setItem('mj_last_country_slug', payload.country_slug || '');
    } catch (e) {}
    document.dispatchEvent(new CustomEvent('mj:area-detected', {detail: payload}));
    if (autoRedirect && !noAuto) {
      try { if (sessionStorage.getItem('mj_country_auto_done') === '1') return; } catch(e) {}
      if (payload.url) {
        try { sessionStorage.setItem('mj_country_auto_done', '1'); } catch(e) {}
        window.location.replace(payload.url + (payload.url.indexOf('?') === -1 ? '?auto_country=1' : '&auto_country=1'));
      }
    }
  }

  function saveLocation(data) {
    if (!data) return Promise.resolve(null);
    var payload = {
      country_code: data.country_code || data.country || data.iso2 || data.countryCode || '',
      country_name: data.country_name || data.country || '',
      region: data.region || data.region_name || data.state || '',
      city: data.city || '',
      timezone: data.timezone || (data.time_zone && data.time_zone.id) || '',
      latitude: data.latitude || data.lat || '',
      longitude: data.longitude || data.lon || data.lng || ''
    };
    if (!payload.country_code) return Promise.resolve(null);
    return fetch(base + '/ajax/visitor-location.php', {
      method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
    }).then(function(r){ return r.ok ? r.json() : null; }).then(function(resp){ rememberAndMaybeRedirect(resp); return resp; }).catch(function(){ return null; });
  }

  function tzFallback() {
    var tz = '';
    try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch (e) {}
    var map = {
      'Asia/Singapore': {country_code:'SG', country_name:'Singapore', timezone:tz},
      'Asia/Kolkata': {country_code:'IN', country_name:'India', timezone:tz},
      'Asia/Calcutta': {country_code:'IN', country_name:'India', timezone:tz},
      'Asia/Kuala_Lumpur': {country_code:'MY', country_name:'Malaysia', timezone:tz},
      'Asia/Bangkok': {country_code:'TH', country_name:'Thailand', timezone:tz},
      'Asia/Jakarta': {country_code:'ID', country_name:'Indonesia', timezone:tz},
      'Asia/Manila': {country_code:'PH', country_name:'Philippines', timezone:tz},
      'Asia/Dubai': {country_code:'AE', country_name:'UAE', timezone:tz},
      'Europe/London': {country_code:'GB', country_name:'United Kingdom', timezone:tz},
      'Australia/Sydney': {country_code:'AU', country_name:'Australia', timezone:tz},
      'Australia/Melbourne': {country_code:'AU', country_name:'Australia', timezone:tz},
      'Australia/Perth': {country_code:'AU', country_name:'Australia', timezone:tz},
      'America/New_York': {country_code:'US', country_name:'United States', timezone:tz},
      'America/Chicago': {country_code:'US', country_name:'United States', timezone:tz},
      'America/Denver': {country_code:'US', country_name:'United States', timezone:tz},
      'America/Los_Angeles': {country_code:'US', country_name:'United States', timezone:tz}
    };
    return map[tz] ? saveLocation(map[tz]) : Promise.resolve(null);
  }

  if (fresh && !autoRedirect) return;
  fetch('https://ipapi.co/json/', {cache: 'no-store'})
    .then(function(r){ return r.ok ? r.json() : Promise.reject(); })
    .then(saveLocation)
    .then(function(resp){ if (!resp) return tzFallback(); })
    .catch(function(){
      fetch('https://ipwho.is/', {cache: 'no-store'})
        .then(function(r){ return r.ok ? r.json() : Promise.reject(); })
        .then(saveLocation)
        .then(function(resp){ if (!resp) return tzFallback(); })
        .catch(tzFallback);
    });
})();
