import { inject, onUnmounted, provide, shallowRef, watch } from "vue";
const SELECTIONS_KEY = Symbol("shwfed-selections");
function sameSelection(a, b) {
  if (Object.is(a, b)) return true;
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return false;
    return a.every((item, i) => Object.is(item, b[i]));
  }
  return false;
}
export function provideSelectionsRegistry() {
  const entries = shallowRef({});
  const registry = {
    entries,
    set: (uuid, option) => {
      if (uuid in entries.value && sameSelection(entries.value[uuid], option)) return;
      entries.value = { ...entries.value, [uuid]: option };
    },
    clear: (uuid) => {
      if (!(uuid in entries.value)) return;
      entries.value = Object.fromEntries(
        Object.entries(entries.value).filter(([key]) => key !== uuid)
      );
    }
  };
  provide(SELECTIONS_KEY, registry);
  return registry;
}
export function useSelectionsRegistry() {
  return inject(SELECTIONS_KEY, void 0);
}
export function publishSelection(key, resolved, project) {
  const registry = useSelectionsRegistry();
  const NONE = "\0:none";
  let last = "\0:init";
  watch(
    resolved,
    (value) => {
      if (!registry) return;
      const id = value === void 0 ? NONE : project.identity(value);
      if (id === last) return;
      last = id;
      if (value === void 0) registry.clear(key);
      else registry.set(key, project.raw(value));
    },
    { immediate: true }
  );
  onUnmounted(() => registry?.clear(key));
}
