"use client";

import { useEffect, useRef } from "react";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";

const STYLE_URL = "https://tiles.openfreemap.org/styles/bright";

interface Props {
  lat: number;
  lng: number;
  title?: string;
  className?: string;
}

export function PropertyMapViewInner({ lat, lng, title, className = "" }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!containerRef.current) return;

    const map = new maplibregl.Map({
      container: containerRef.current,
      style: STYLE_URL,
      center: [lng, lat],
      zoom: 15,
      interactive: true,
    });

    map.addControl(new maplibregl.NavigationControl(), "top-right");

    const popup = title
      ? new maplibregl.Popup({ offset: 25, closeButton: false }).setText(title)
      : undefined;

    new maplibregl.Marker({ color: "#2563eb" })
      .setLngLat([lng, lat])
      .setPopup(popup)
      .addTo(map);

    return () => map.remove();
  }, [lat, lng, title]);

  return (
    <div
      ref={containerRef}
      className={`overflow-hidden rounded-lg border ${className}`}
    />
  );
}
