"use client";

import { useEffect, useRef, useState } from "react";
import { siteConfig } from "@/config/site";

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

const organizationId = "22727621504";
const { lat, lng } = siteConfig.coordinates;
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${apiKey ? `&apikey=${encodeURIComponent(apiKey)}` : ""}`;
    script.async = true;
    script.onload = () => window.ymaps?.ready(resolve);
    script.onerror = () => reject(new Error("Yandex Maps API failed to load"));
    document.head.appendChild(script);
  });
  return apiPromise;
}

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

  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) return;
    let cancelled = false;
    loadYandexApi().then(() => {
      if (cancelled || !window.ymaps || !containerRef.current) return;
      const map = new window.ymaps.Map(containerRef.current, { center: [lat, lng], zoom: 16 }, { controls: ["zoomControl", "fullscreenControl"] });
      mapRef.current = map;
      return window.ymaps.findOrganization(organizationId).then((organization) => {
        if (!cancelled) map.geoObjects.add(organization);
      }).catch(() => {
        if (cancelled || !window.ymaps) return;
        map.geoObjects.add(new window.ymaps.Placemark([lat, lng], {
          balloonContentHeader: "КИЛН",
          balloonContentBody: `<a href="${routeUrl}" target="_blank" rel="noreferrer">Открыть карточку КИЛН в Яндекс Картах</a>`
        }, { preset: "islands#redDotIconWithCaption", iconCaption: "КИЛН" }));
      });
    }).catch(() => setError(true));
    return () => {
      cancelled = true;
      mapRef.current?.destroy();
      mapRef.current = null;
    };
  }, [routeUrl, shouldLoad]);

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