let hoveredStateId = null;

export const addCountryBorder = (map: maplibregl.Map) => {
  map.on("load", () => {
    map.addSource("states", {
      type: "geojson",
      data: "/static/src/earth.geojson",
      promoteId: "iso_n3", // use this field as the unique identifier for each country
    });

    // The feature-state dependent fill-opacity expression will render the hover effect
    // when a feature's hover state is set to true.
    map.addLayer({
      id: "state-fills",
      type: "fill",
      source: "states",
      layout: {},
      paint: {
        "fill-color": "#627BC1",
        "fill-opacity": [
          "case",
          ["boolean", ["feature-state", "hover"], false],
          0.2,
          0,
        ],
      },
    });

    map.addLayer({
      id: "state-borders",
      type: "line",
      source: "states",
      layout: {
        "line-join": "round",
        "line-cap": "round",
      },
      paint: {
        "line-color": "#4b4b4b", // Border color
        "line-width": [
          "case",
          ["boolean", ["feature-state", "hover"], false], // Check if hovered
          1, // Thicker border on hover
          0.5, // Regular border width
        ],
        "line-opacity": 1, // Full opacity for borders
      },
    });

    // When the user moves their mouse over the state-fill layer, we'll update the
    // feature state for the feature under the mouse.
    map.on("mousemove", "state-fills", (e) => {
      if (e.features.length > 0) {
        if (hoveredStateId) {
          map.setFeatureState(
            { source: "states", id: hoveredStateId },
            { hover: false }
          );
        }
        hoveredStateId = e.features[0].id;
        map.setFeatureState(
          { source: "states", id: hoveredStateId },
          { hover: true }
        );
      }
    });

    // When the mouse leaves the state-fill layer, update the feature state of the
    // previously hovered feature.
    map.on("mouseleave", "state-fills", () => {
      if (hoveredStateId) {
        map.setFeatureState(
          { source: "states", id: hoveredStateId },
          { hover: false }
        );
      }
      hoveredStateId = null;
    });
  });
};
