"use client";

import React, { useEffect, useRef } from "react";

interface YandexMapProps {
  lat?: number;
  lng?: number;
  zoom?: number;
}

export default function YandexMap({
  lat = 41.3111,
  lng = 69.2406,
  zoom = 12,
}: YandexMapProps) {
  const mapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Yandex Map scriptini dinamik yuklash
    if (!window.ymaps) {
      const script = document.createElement("script");
      script.src = "https://api-maps.yandex.ru/2.1/?lang=ru_RU&apikey=5169ae9d-529a-43f8-9cb1-30e1a3360dac";
      script.async = true;
      script.onload = () => initMap();
      document.body.appendChild(script);
    } else {
      initMap();
    }

    function initMap() {
      if (!mapRef.current || !window.ymaps) return;

      window.ymaps.ready(() => {
        const map = new window.ymaps.Map(mapRef.current!, {
          center: [lat, lng],
          zoom,
          controls: ["zoomControl", "typeSelector", "fullscreenControl"],
        });

        const placemark = new window.ymaps.Placemark(
          [lat, lng],
          {
            balloonContent: `
              <div style="font-size:14px">
                <b>Bizning joylashuv:</b><br/>
                Toshkent sh., Mustaqillik maydoni<br/>
                <a href="https://yandex.uz/maps/?ll=${lng}%2C${lat}&z=14" target="_blank">Yandex xaritada ochish</a>
              </div>
            `,
          },
          {
            iconColor: "#ff0000",
            draggable: false,
          }
        );

        map.geoObjects.add(placemark);
      });
    }
  }, [lat, lng, zoom]);

  return (
    <div className="w-full h-[500px] rounded-lg shadow-md overflow-hidden" ref={mapRef}></div>
  );
}
