// assets/js/execvitr-gmaps-loader.js
(function(w, d){
  var cfg = w.execvitrLoader || {};
  var LOADED_EVENT = 'execvitr:gmaps-ready';
  var SCRIPT_ID = 'execvitr-gmaps-api';

  function ready(){ try { return !!(w.google && w.google.maps && w.google.maps.places); } catch(e){ return false; } }
  function fire(){ try { d.dispatchEvent(new CustomEvent(LOADED_EVENT)); } catch(e){ /* IE11 not targeted */ } }

  // If already present (by other plugin/theme), just notify and exit
  if (ready()) { fire(); return; }

  // If a Google Maps API <script> is already in DOM, hook its onload once.
  var existing = d.querySelector('script[src*="maps.googleapis.com/maps/api/js"]');
  if (existing) {
    if (!existing.hasAttribute('data-execvitr-hooked')) {
      existing.setAttribute('data-execvitr-hooked', '1');
      existing.addEventListener('load', function(){ fire(); });
    }
    return; // don't inject duplicate
  }

  // No script found, inject our own once.
  if (d.getElementById(SCRIPT_ID)) { return; }
  if (!cfg.apiKey) { console.warn('[execvitr] Google Maps API key missing; loader skipped'); return; }

  var src = 'https://maps.googleapis.com/maps/api/js?key=' + encodeURIComponent(cfg.apiKey)
          + '&libraries=places'
          + (cfg.language ? '&language=' + encodeURIComponent(cfg.language) : '')
          + (cfg.region ? '&region=' + encodeURIComponent(cfg.region) : '');

  var s = d.createElement('script');
  s.id = SCRIPT_ID;
  s.src = src;
  s.async = true;
  s.defer = true;
  s.onload = fire;
  (d.head || d.documentElement).appendChild(s);
})(window, document);
