"use client";

import { useEffect, useRef, useState } from "react";
import type { RestaurantCoordinates } from "@/lib/restaurant-map";

declare global {
  interface Window {
    ymaps?: {
      ready: (callback: () => void) => void;
      Map: new (container: HTMLElement, state: { center: [number, number]; zoom: number; controls: string[] }) => { geoObjects: { add: (object: unknown) => void }; destroy: () => void };
      Placemark: new (coordinates: [number, number], properties?: Record<string, string>, options?: Record<string, string>) => unknown;
    };
  }
}

let apiPromise: Promise<void> | null = null;

function loadYandexApi() {
  if (window.ymaps) return Promise.resolve();
  if (apiPromise) return apiPromise;
  apiPromise = new Promise((resolve, reject) => {
    const script = document.createElement("script");
    const apiKey = process.env.NEXT_PUBLIC_YANDEX_MAPS_API_KEY;
    script.src = `https://api-maps.yandex.ru/2.1/?lang=ru_RU&coordorder=latlong${apiKey ? `&apikey=${encodeURIComponent(apiKey)}` : ""}`;
    script.async = true;
    script.onload = () => window.ymaps ? window.ymaps.ready(resolve) : reject(new Error("Yandex Maps API unavailable"));
    script.onerror = () => reject(new Error("Yandex Maps API failed to load"));
    document.head.appendChild(script);
  });
  return apiPromise;
}

export function YandexMap({ routeUrl, coordinates }: { routeUrl: string; coordinates: RestaurantCoordinates | null }) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const mapRef = useRef<{ destroy: () => void } | null>(null);
  const [shouldLoad, setShouldLoad] = useState(false);
  const [error, setError] = useState(false);
  const lat = coordinates?.lat;
  const lon = coordinates?.lon;

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      setShouldLoad(true);
      observer.disconnect();
    }, { rootMargin: "200px 0px" });
    observer.observe(container);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    if (!shouldLoad || !containerRef.current || lat === undefined || lon === undefined) return;
    let cancelled = false;
    loadYandexApi().then(() => {
      if (cancelled || !window.ymaps || !containerRef.current) return;
      const map = new window.ymaps.Map(containerRef.current, { center: [lat, lon], zoom: 18, controls: ["zoomControl", "fullscreenControl"] });
      mapRef.current = map;
      map.geoObjects.add(new window.ymaps.Placemark([lat, lon], {
        iconCaption: "КИЛН",
        balloonContentHeader: "КИЛН",
        balloonContentBody: `<a href="${routeUrl}" target="_blank" rel="noreferrer">Построить маршрут к КИЛН</a>`
      }, { preset: "islands#redDotIconWithCaption" }));
    }).catch(() => { if (!cancelled) setError(true); });
    return () => {
      cancelled = true;
      mapRef.current?.destroy();
      mapRef.current = null;
    };
  }, [routeUrl, shouldLoad, lat, lon]);

  return (
    <div ref={containerRef} data-testid="restaurant-map" className="relative min-h-[420px] overflow-hidden rounded-lg bg-kiln-iron">
      {!coordinates || !shouldLoad || error ? (
        <div className="absolute inset-0 grid place-items-center p-8 text-center">
          <div><p className="muted">{!coordinates || error ? "Карту не удалось загрузить." : "Карта загрузится при прокрутке к этому блоку."}</p><a href={routeUrl} className="button button-secondary mt-4">Открыть КИЛН в Яндекс Картах</a></div>
        </div>
      ) : null}
    </div>
  );
}
