import React, { useEffect, useRef } from "react";
import * as echarts from "echarts";
import indonesiaGeo from "../../public/assets/geo/indonesia.json";

export const IndonesiaMap: React.FC = () => {
  const chartRef = useRef<HTMLDivElement>(null);
  const myChart = useRef<echarts.EChartsType | null>(null);

  useEffect(() => {
    if (!chartRef.current) return;
    (window as any).echarts = echarts;

    const fixedGeo = {
      ...indonesiaGeo,
      features: indonesiaGeo.features.map((f) => ({
        ...f,
        properties: {
          ...f.properties,
          name: f.properties.Propinsi, // 🔥 inilah kuncinya
        },
      })),
    };

    echarts.registerMap("indonesia", fixedGeo as any);

    const chart = echarts.init(chartRef.current);
    myChart.current = chart;

    const rawData = [
      { name: "DI. ACEH", value: 10 },
      { name: "SUMATERA UTARA", value: 20 },
      { name: "DKI JAKARTA", value: 100 },
      { name: "JAWA BARAT", value: 30 },
      { name: "IRIAN JAYA TIMUR", value: 20 },
    ];

    console.log("raw", rawData);
    chart.setOption({
      backgroundColor: "#d3d3d3",
      title: {
        text: "Sebaran Data",
        left: "center",
        textStyle: { color: "#000" },
      },
      visualMap: {
        min: 0,
        max: 100,
        show: true,
        seriesIndex: 0,
        inRange: {
          color: ["#ffffff", "#ff0000"],
        },
      },
      series: [
        {
          type: "map",
          map: "indonesia",
          // nameProperty: "properties.Propinsi", // harus cocok

          roam: true,
          zoom: 1.2,
          center: [120, -2],
          label: {
            show: false,
            color: "#000",
          },
          itemStyle: {
            borderColor: "#999",
          },
          emphasis: {
            itemStyle: {
              areaColor: "#ffcccc",
            },
          },
          data: rawData,
        },
      ],
    });

    return () => {
      chart.dispose();
    };
  }, []);

  return <div ref={chartRef} style={{ height: "100%", width: "100%" }} />;
};
