/**
 * Yandex Maps lazy loader — shared across all pages
 *
 * Activates only when #ya-map[data-coords] is present.
 * Loads Yandex Maps API on first scroll > 100px (passive) or after 3s fallback.
 * Creates map with a placemark at the given coordinates.
 *
 * Required data attributes on #ya-map:
 *   data-coords — comma-separated lat,lng (e.g. "55.7558,37.6173")
 *   data-label  — placemark text (e.g. "Детский центр «Декарт»")
 *
 * @package Dekart
 */

(function () {
  var mapEl = document.getElementById('ya-map');
  if (!mapEl) return;

  var coordsAttr = mapEl.getAttribute('data-coords');
  var label      = mapEl.getAttribute('data-label') || '';
  if (!coordsAttr) return;

  var parts = coordsAttr.split(',');
  if (parts.length < 2) return;
  var mapCoords = [parseFloat(parts[0]), parseFloat(parts[1])];
  if (isNaN(mapCoords[0]) || isNaN(mapCoords[1])) return;

  var mapLoaded  = false;
  var apiLoading = false;

  function initMap() {
    if (typeof ymaps === 'undefined') return;
    ymaps.ready(function () {
      var map = new ymaps.Map('ya-map', {
        center: mapCoords,
        zoom: 16
      }, {
        searchControlProvider: 'yandex#search'
      });
      var placemark = new ymaps.Placemark(
        mapCoords,
        { iconContent: label },
        { preset: 'islands#redStretchyIcon' }
      );
      map.geoObjects.add(placemark);
      mapLoaded = true;
    });
  }

  function loadYandexMaps() {
    if (mapLoaded || apiLoading) return;
    apiLoading = true;
    var script = document.createElement('script');
    script.src = 'https://api-maps.yandex.ru/2.1/?lang=ru_RU';
    script.onerror = function () {
      apiLoading = false;
    };
    script.onload = initMap;
    document.head.appendChild(script);
  }

  // Scroll trigger — first >100px
  function onScroll() {
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    if (scrollTop > 100) {
      loadYandexMaps();
      window.removeEventListener('scroll', onScroll);
    }
  }

  // Fallback — 3 seconds after page load
  window.addEventListener('load', function () {
    setTimeout(function () {
      if (!mapLoaded && !apiLoading) loadYandexMaps();
    }, 3000);
  });

  window.addEventListener('scroll', onScroll, { passive: true });
})();
