function lazyLoadMap(selector, options = { threshold: 0.5 }) {
   const maps = document.querySelectorAll(`${selector}`);

   const observer = new IntersectionObserver((entries, observer) => {
      entries.forEach((entry) => {
         if (entry.isIntersecting) {
            const map = entry.target;
            const coordsStr = map.dataset.coords;
            const markerSrc = map.dataset.marker;
            const coords = coordsStr.split(",");

            if (typeof ymaps3 !== "undefined") {
               initMap(map, coords, markerSrc);
            } else {
               initMapApi(() => {
                  initMap(map, coords, markerSrc);
               });
            }
            observer.unobserve(map);
         }
      });
   }, options);

   maps.forEach((map) => {
      observer.observe(map);
   });
}

function initMapApi(callback) {
   const script = document.createElement("script");

   if (window.lzMapApiKey) {
      script.src = `https://api-maps.yandex.ru/v3/?apikey=${window.lzMapApiKey}&lang=ru_RU`;
   } else {
      script.src = "https://api-maps.yandex.ru/v3/?apikey=bb00b8d1-9047-46f6-830a-e23799edce1f&lang=ru_RU";
   }

   document.head.appendChild(script);
   script.onload = function () {
      console.log("yandex map is loaded");

      if (callback) {
         callback();
      }
   };
}

async function initMap(mapField, coordinates, markerSrc) {
   await ymaps3.ready;

   console.log(mapField, coordinates, markerSrc);

   const { YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapMarker } = ymaps3;

   const container = mapField;

   if (container) {
      const map = new YMap(
         container,
         {
            location: {
               center: coordinates,
               zoom: 16,
            },
            behaviors: ["drag", "dblClick"],
         },
         [new YMapDefaultSchemeLayer({}), new YMapDefaultFeaturesLayer({})],
      );

      const markerElement = document.createElement("img");
      markerElement.className = "my-marker";
      markerElement.src = markerSrc;

      const imgContainer = document.createElement("div");
      imgContainer.classList.add("marker-container");
      imgContainer.appendChild(markerElement);

      const marker = new YMapMarker(
         {
            coordinates: coordinates,
         },
         imgContainer,
      );

      // Добавляем слой для отображения схематической карты
      map.addChild(marker);
   }
}

export { lazyLoadMap };
