---
import DefaultLayout from "../../layouts/DefaultLayout.astro";
import MapGoogle from "../../components/maps/MapGoogle.astro";
import RangeForm from "../../islands/RangeForm.jsx";

import "../../styles/map-google.css";

const apiKey = import.meta.env.PUBLIC_GOOGLE_MAPS_KEY;
const lat = 52.597388;
const lon = 21.456797;
const mapStyleId = "8e0a97af9476f2d3";
---

<script>
  declare global {
    interface Window {
      showAddressOnMap?: (result: any) => void;
      fuzMaps?: any;
    }
  }
</script>

<DefaultLayout title="FUZ Mapa zasięgu sieci światłowodowej">
  <section class="flex flex-col md:flex-row h-full min-h-[80vh]">
    <!-- PANEL LEWY -->
    <aside
      class="w-full md:w-[340px] bg-[var(--f-background)] text-[var(--f-text)]
            pt-6 px-6 flex flex-col gap-6 overflow-y-auto z-40"
    >
      <h3 class="text-3xl">Sprawdź dostępność usług</h3>
      <p class="text-sm">
        Wybierz swoją miejscowość i ulicę oraz numer budynku, aby sprawdzić
        dostępność usług światłowodowych FUZ.
      </p>

      <RangeForm client:load />
    </aside>

    <!-- MAPA -->
    <div class="flex-1 relative min-h-[50vh] md:min-h-0">
      <MapGoogle
        apiKey={apiKey}
        lat={lat}
        lon={lon}
        zoom={17}
        showMarker={true}
        mode="full"
        mapStyleId={mapStyleId}
      />
    </div>
  </section>

  <script is:inline>
    let fiberLayer = null;

    window.getActiveMap = function () {
      if (!window.fuzMaps) return null;
      return Object.values(window.fuzMaps)[0] || null;
    };

    function enableFiberLayer() {
      const map = window.getActiveMap();
      if (!map) return;

      if (fiberLayer) {
        fiberLayer.setMap(null);
      }

      fiberLayer = new google.maps.KmlLayer(
        "https://www.google.com/maps/d/kml?mid=1Or8SF_9qx6QMdidS-99V_jqQuhF9de0&forcekml=1",
        { suppressInfoWindows: true, preserveViewport: false },
      );
      fiberLayer.setMap(map);
    }

    // Czekamy aż mapa się załaduje
    const int = setInterval(() => {
      const map = window.getActiveMap();
      if (map && window.google?.maps) {
        clearInterval(int);
        enableFiberLayer();
      }
    }, 100);
  </script>

  <script is:inline>
    window.showAddressOnMap = async function (result) {
      const map = window.getActiveMap();
      if (!map) return;

      // Czekamy aż API będzie gotowe
      if (!window.google?.maps?.importLibrary) {
        await new Promise((resolve) => {
          const int = setInterval(() => {
            if (window.google?.maps?.importLibrary) {
              clearInterval(int);
              resolve(true);
            }
          }, 50);
        });
      }

      const { AdvancedMarkerElement } =
        await google.maps.importLibrary("marker");
      const { InfoWindow } = await google.maps.importLibrary("maps");

      if (window._activeMarker) window._activeMarker.map = null;
      if (window._activeInfo) window._activeInfo.close();

      const pos = { lat: result.lat, lng: result.lon };

      const overlay = document.createElement("div");
      overlay.className = "pulse-marker";

      const projection = map.getProjection();
      if (projection) {
        const point = projection.fromLatLngToPoint(new google.maps.LatLng(pos));
        overlay.style.left = point.x + "px";
        overlay.style.top = point.y + "px";
      }

      setTimeout(() => {
        overlay.remove();
      }, 1500);

      map.getDiv().appendChild(overlay);
      map.panTo(pos);
      let targetZoom = 16; 

      setTimeout(() => {
        map.setZoom(targetZoom);
      }, 250);

      const marker = new AdvancedMarkerElement({
        map,
        position: pos,
        title: `${result.city} ${result.street ?? ""} ${result.number}`,
        className: "marker-bounce",
      });

      window._activeMarker = marker;

      // InfoWindow
      const html = `
  <div class="f-info-window">
    <div class="f-info-header">
      <div class="f-info-heading">
        ${
          result.available
            ? `<span class="ok">✔</span> Internet światłowodowy dostępny`
            : `<span class="no">✖</span>  Światłowód niedostępny`
        }
      </div>
      <div class="f-info-city">${result.city}</div>
      <div class="f-info-street">${result.street ?? ""} ${result.number}</div>
    </div>   
    </div>
    <div class="w-full flex justify-center mb-4">
      <a href="/kontakt" class="btn btn-primary">Przejdź do kontaktu →</a>
    </div>
  </div>
`;

      const info = new InfoWindow({ content: html });
      window._activeInfo = info;

      info.open({ map, anchor: marker });
    };
  </script>
</DefaultLayout>
