(function(){
  var map, ds, dr, userMarker, started = false, t;

  function $(s, c){ return (c||document).querySelector(s); 
  function getPlaceId(isFrom){
    var el = document.getElementById(isFrom ? 'execvitr_origin_place_id' : 'execvitr_dest_place_id');
    return el && el.value ? String(el.value) : '';
  }

}

  function ensureMap(){
    if (map) return true;
    var el = $('#execvitr-route-map');
    if (!el || !(window.google && google.maps)) return false;

    map = new google.maps.Map(el, {
      zoom: 10,
      center: { lat: 41.015, lng: 28.979 }, // fallback (İstanbul)
      mapTypeControl: false,
      streetViewControl: false,
      fullscreenControl: false
    });

    ds = new google.maps.DirectionsService();
    dr = new google.maps.DirectionsRenderer({ suppressMarkers: false, preserveViewport: false });
    dr.setMap(map);
    return true;
  }

  function centerToBrowserLocation(){
    if (!map || !navigator.geolocation) return;
    navigator.geolocation.getCurrentPosition(function(pos){
      var p = { lat: pos.coords.latitude, lng: pos.coords.longitude };
      map.setCenter(p);
      map.setZoom(12);
      if (userMarker) userMarker.setMap(null);
      userMarker = new google.maps.Marker({
        map: map,
        position: p,
        title: 'You are here',
        icon: { path: google.maps.SymbolPath.CIRCLE, scale: 6 }
      });
    }, function(){ /* izin yok/hata: fallback merkez kalsın */ }, {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 60000
    });
  }

	  // Center map to selected country (from plugin settings)
	  function centerToSelectedCountry(){
	    try {
	      var code = (window.ExecvitrData && ExecvitrData.country) ? String(ExecvitrData.country).toUpperCase() : '';
	      if (!code || !map) return false;
	      var centers = {
	        TR: { lat: 39.0,   lng: 35.0,   zoom: 6 },
	        US: { lat: 39.5,   lng: -98.35, zoom: 4 },
	        GB: { lat: 54.5,   lng: -3.0,   zoom: 6 },
	        DE: { lat: 51.1,   lng: 10.4,   zoom: 6 },
	        FR: { lat: 46.2,   lng: 2.2,    zoom: 6 },
	        IT: { lat: 41.9,   lng: 12.6,   zoom: 6 },
	        ES: { lat: 40.4,   lng: -3.7,   zoom: 6 },
	        CA: { lat: 56.1,   lng: -106.3, zoom: 4 },
	        AU: { lat: -25.3,  lng: 133.8,  zoom: 4 },
	        NL: { lat: 52.1,   lng: 5.3,    zoom: 7 },
	        BE: { lat: 50.8,   lng: 4.5,    zoom: 7 },
	        CH: { lat: 46.8,   lng: 8.2,    zoom: 7 },
	        AT: { lat: 47.6,   lng: 14.1,   zoom: 7 },
	        AE: { lat: 24.3,   lng: 54.4,   zoom: 6 },
	        IN: { lat: 22.9,   lng: 79.0,   zoom: 5 },
	        RU: { lat: 61.5,   lng: 105.3,  zoom: 3 },
	        JP: { lat: 36.2,   lng: 138.3,  zoom: 5 },
	      };
	      var c = centers[code];
	      if (!c) return false;
	      map.setCenter({ lat: c.lat, lng: c.lng });
	      map.setZoom(c.zoom || 6);
	      return true;
	    } catch(e) {
	      return false;
	    }
	  }

  function clearRoute(){
    if (dr) dr.set('directions', null);
  }

  function draw(){
    var a = $('#address_from'), b = $('#address_to');
    if (!a || !b) return;
    var from = (a.value||'').trim(), to = (b.value||'').trim();

    if (!ensureMap()) return;

    if (!from || !to) {
      clearRoute();
      return;
    }

    ds.route({
      origin: from,
      destination: to,
      travelMode: google.maps.TravelMode.DRIVING
    }, function(res, status){
      if (status === 'OK' && res && res.routes && res.routes[0]) {
        dr.setDirections(res);

        // Clear any warning
        var w = document.getElementById('execvitr-route-warning');
        if (w) w.textContent = '';

        // ✅ Rota çizildi: kullanıcı konum işaretçisini kaldır
        if (userMarker) {
          userMarker.setMap(null);
          userMarker = null;
        }
      } else {
        clearRoute();

        // Helpful debug: show a lightweight warning instead of silently failing
        try {
          console.warn('[execvitr] Directions route failed:', status, res);
        } catch(e) {}
        var warn = document.getElementById('execvitr-route-warning');
        if (!warn) {
          warn = document.createElement('div');
          warn.id = 'execvitr-route-warning';
          warn.style.marginTop = '8px';
          warn.style.fontSize = '13px';
          warn.style.opacity = '0.85';
          var mapEl = document.getElementById('execvitr-route-map');
          if (mapEl && mapEl.parentNode) mapEl.parentNode.insertBefore(warn, mapEl.nextSibling);
        }
        if (warn) {
          warn.textContent = 'Route could not be drawn. Please check your Google API key (Directions API) and the entered addresses.';
        }
      }
    });
  }

  function refreshSoon(){ clearTimeout(t); t = setTimeout(draw, 250); }

  function start(){
    if (started) return;
    if (!ensureMap()) return;
    started = true;

	    // Açılışta ayarlardaki ülkeye odaklan (ülke yoksa tarayıcı konumu)
	    if (!centerToSelectedCountry()) {
	      centerToBrowserLocation();
	    }

    // fiyat/mesafe hesaplandıktan sonra veya input değişince rotayı güncelle
    document.addEventListener('execvitr:price-updated', function(){ refreshSoon(); });

    var a = $('#address_from'), b = $('#address_to');
    if (a) { a.addEventListener('input', refreshSoon); a.addEventListener('change', refreshSoon); a.addEventListener('blur', refreshSoon); }
    if (b) { b.addEventListener('input', refreshSoon); b.addEventListener('change', refreshSoon); b.addEventListener('blur', refreshSoon); }

    // ilk çizim denemesi (adresler doluysa)
    refreshSoon();
  }

  if (window.google && google.maps) { start(); }
  else { document.addEventListener('execvitr:gmaps-ready', start, { once:true }); }

  document.addEventListener('DOMContentLoaded', function(){ setTimeout(start, 300); });
})();
