<template>
  <span>
    <slot name="default" :value="selectedValue">
      {{ selectedValue?.label || 'Не выбрана' }}
    </slot>
  </span>
</template>

<script setup>
import {useAutocompleteStore} from "@/stores/autocomplete.js";
import {computed, onMounted, ref} from "vue";

const autocomplete = useAutocompleteStore();

const isLoading = ref(false);

const props = defineProps({
  id: {
    type: Number,
    default: null,
  },
});

function findNodeByKey(nodes, keyToFind) {
  for (const node of nodes) {
    if (node.key === keyToFind) {
      return node;
    }
    if (node.children?.length) {
      const found = findNodeByKey(node.children, keyToFind);
      if (found) return found;
    }
  }
  return null;
}

const selectedValue = computed(() => {
  const id = props.id;
  if (!id) return null;

  const node = findNodeByKey(autocomplete.categories || [], id);
  if (!node) return null;

  return node;
});

onMounted(async () => {
  isLoading.value = true;
  await autocomplete.fetchCategories();
  isLoading.value = false;
});
</script>
