import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { useMemo } from "react";

const INITIAL = {
  included: new Set([]),
  excluded: new Set([]),
};

const store = (set) => ({
  selection: INITIAL,
  include: (id) => {
    set((state) => {
      const { excluded } = state.selection;
      if (excluded.has(id)) {
        state.selection.excluded.delete(id);
      } else {
        state.selection.included.add(id);
      }
    });
  },

  exclude: (id) => {
    set((state) => {
      const { included } = state.selection;
      if (included.has(id)) {
        state.selection.included.delete(id);
      } else {
        state.selection.excluded.add(id);
      }
    });
  },

  reset: () =>
    set((state) => {
      state.selection.included.clear();
      state.selection.excluded.clear();
    }),
});

export const usePointSelection = create(immer(store));

export const useHasManualEdits = () => {
  const { selection } = usePointSelection();
  return useMemo(
    () => selection.included.size || selection.excluded.size,
    [selection]
  );
};
