import type { Map as MapLibreMap } from "maplibre-gl";
import { describe, expect, it } from "vitest";
import { waterNetworkLayers } from "./layers";
import { MAP_STYLE_TOKENS } from "./map-colors";
import {
  INITIAL_LAYER_VISIBILITY,
  MAP_LEGEND_ITEMS,
  createLayerControlItems,
  getWorkbenchLayerIds
} from "./map-control-config";

describe("workbench supply layer controls", () => {
  it("creates controls only for available supply system sources", () => {
    const items = createLayerControlItems(INITIAL_LAYER_VISIBILITY);

    expect(items.map((item) => item.id)).toEqual([
      "pipes",
      "junctions",
      "valves",
      "reservoirs",
      "scada",
      "simulation"
    ]);
    expect(items.map((item) => item.id)).not.toContain("pumps");
    expect(items.map((item) => item.id)).not.toContain("tanks");
    expect(items.slice(0, 5).map((item) => item.description)).toEqual([
      "tjwater:geo_pipes_mat",
      "tjwater:geo_junctions_mat",
      "tjwater:geo_valves",
      "tjwater:geo_reservoirs",
      "tjwater:geo_scada"
    ]);
  });

  it("shows only current visible business icons in the legend", () => {
    expect(MAP_LEGEND_ITEMS.map((item) => item.id)).toEqual([
      "major-pipe",
      "medium-pipe",
      "minor-pipe",
      "inactive-pipe",
      "junction",
      "valve",
      "reservoir",
      "scada-flow",
      "scada-pressure",
      "impact-area"
    ]);
    expect(MAP_LEGEND_ITEMS.find((item) => item.id === "valve")).toMatchObject({ imageSrc: "/map/valve.png" });
    expect(MAP_LEGEND_ITEMS.find((item) => item.id === "reservoir")).toMatchObject({
      label: "水库",
      imageSrc: "/map/reservoir.png"
    });
    expect(MAP_LEGEND_ITEMS.find((item) => item.id === "scada-flow")).toMatchObject({ imageSrc: "/map/scada-flow.png" });
    expect(MAP_LEGEND_ITEMS.find((item) => item.id === "scada-pressure")).toMatchObject({ imageSrc: "/map/scada-pressure.png" });
    expect(MAP_LEGEND_ITEMS.find((item) => item.id === "inactive-pipe")).toMatchObject({
      color: MAP_STYLE_TOKENS.state.inactive,
      shape: "dashed-line"
    });
  });

  it("finds every rendered layer that uses a source", () => {
    const map = {
      getLayer: (id: string) => waterNetworkLayers.some((layer) => layer.id === id),
      getStyle: () => ({ version: 8, sources: {}, layers: waterNetworkLayers })
    } as unknown as Pick<MapLibreMap, "getLayer" | "getStyle">;

    expect(getWorkbenchLayerIds(map, "valves")).toEqual([
      "valves-casing",
      "valves",
      "valves-symbol",
      "valves-hover",
      "valves-selected-outer",
      "valves-selected",
      "valves-hit"
    ]);
    expect(getWorkbenchLayerIds(map, "reservoirs")).toEqual([
      "reservoirs-halo",
      "reservoirs",
      "reservoirs-symbol",
      "reservoirs-hover",
      "reservoirs-selected-outer",
      "reservoirs-selected",
      "reservoirs-hit"
    ]);
  });
});
