"use client";

import jsVectorMap from "jsvectormap";
import { useEffect, useRef } from "react";

import "@/js/us-aea-en";

export default function Map() {
  const mapContainerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let map: InstanceType<typeof jsVectorMap> | null = null;
    const container = mapContainerRef.current;

    if (!container) return;

    // Dev Strict Mode can run effects twice; clear old markup before re-init.
    container.innerHTML = "";

    map = new jsVectorMap({
      selector: "#mapOne",
      map: "us_aea_en",
      zoomButtons: true,
      regionStyle: {
        initial: {
          fill: "#C8D0D8",
        },
        hover: {
          fillOpacity: 1,
          fill: "#3056D3",
        },
      },
      regionLabelStyle: {
        initial: {
          fontWeight: "semibold",
          fill: "#fff",
        },
        hover: {
          cursor: "pointer",
        },
      },
      labels: {
        regions: {
          render(code: string) {
            return code.split("-")[1];
          },
        },
      },
    });

    return () => {
      try {
        map?.destroy?.();
      } catch {
        // jsVectorMap can throw during React Strict Mode cleanup in dev.
      }
      container.innerHTML = "";
    };
  }, []);

  return (
    <div className="h-[422px]">
      <div ref={mapContainerRef} id="mapOne" className="mapOne map-btn" />
    </div>
  );
}
