import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { persist } from "zustand/middleware";
import { LAYER_IDS } from "../dzkh-features/constants.js";

const INITIAL_STATE = {
  [LAYER_IDS.consumer]: true,
  [LAYER_IDS.source]: true,
  [LAYER_IDS.dispatcher]: true,
};

const store = (set) => ({
  isVisible: INITIAL_STATE,

  toggleVisibility: (layerId) =>
    set((state) => {
      state.isVisible[layerId] = !state.isVisible[layerId];
    }),

  showLayers: (layerIds) =>
    set((state) => {
      layerIds.forEach((layerId) => {
        state.isVisible[layerId] = true;
      });
    }),

  setLayersVisibility: (visibleLayerIds) =>
    set((state) => {
      visibleLayerIds.forEach((layerId) => {
        state.isVisible[layerId] = true;
      });
      const invisibleLayersIds = Object.keys(state.isVisible).filter(
        (l) => !visibleLayerIds.includes(l)
      );
      invisibleLayersIds.forEach((layerId) => {
        state.isVisible[layerId] = false;
      });
    }),
});

export const useLayersVisibility = create(
  persist(immer(store), { name: "dzkh/layers-visibility" })
);
