<template>
  <!-- eslint-disable-next-line vue/no-template-shadow -->
  <DefineListTemplate v-slot="{ links, level }">
    <ul :class="level > 0 ? ui.listWithChildren({ class: props.ui?.listWithChildren }) : ui.list({ class: props.ui?.list })">
      <li v-for="(link, index) in links" :key="index" :class="link.children && link.children.length > 0 ? ui.itemWithChildren({ class: props.ui?.itemWithChildren }) : ui.item({ class: props.ui?.item })">
        <a
          :href="`#${link.id}`"
          :class="ui.link({ class: props.ui?.link, active: activeHeadings.includes(link.id) })"
          @click="scrollToHeading(link.id)"
        >
          {{ link.text }}
        </a>

        <ReuseListTemplate
          v-if="link.children?.length"
          :links="link.children"
          :level="level + 1"
        />
      </li>
    </ul>
  </DefineListTemplate>

  <div :class="ui.root({ class: [props.ui?.root, props.class] })">
    <div :class="ui.header({ class: props.ui?.header })">
      <UIcon :class="ui.icon({ class: props.ui?.icon })" :name="appConfig.ui.icons.toc" />

      <span :class="ui.title({ class: props.ui?.title })">
        {{ title }}
      </span>
    </div>

    <ReuseListTemplate :links="props.links" :level="0" />
  </div>
</template>

<script setup>
import theme from "#build/cms/toc";
import { useAppConfig, useNuxtApp, useRouter, useScrollspy } from "#imports";
import { createReusableTemplate } from "@vueuse/core";
import { computed } from "vue";
import { tv } from "../tv";
const props = defineProps({
  title: { type: String, required: false, default: "\u0421\u043E\u0434\u0435\u0440\u0436\u0430\u043D\u0438\u0435" },
  links: { type: Array, required: true },
  container: { type: String, required: false },
  class: { type: null, required: false },
  ui: { type: null, required: false }
});
const emits = defineEmits(["move"]);
const router = useRouter();
const appConfig = useAppConfig();
const { activeHeadings, updateHeadings } = useScrollspy();
const [DefineListTemplate, ReuseListTemplate] = createReusableTemplate({
  props: {
    links: Array,
    level: Number
  }
});
function scrollToHeading(id) {
  const encodedId = encodeURIComponent(id);
  router.push(`#${encodedId}`);
  emits("move", id);
}
const ui = computed(() => tv({ extend: tv(theme), ...appConfig.cms?.toc || {} })());
const nuxtApp = useNuxtApp();
nuxtApp.hooks.hook("page:loading:end", () => {
  const headings = Array.from(document.querySelector(props.container ?? "body")?.querySelectorAll("h2, h3") ?? []);
  updateHeadings(headings);
});
nuxtApp.hooks.hook("page:transition:finish", () => {
  const headings = Array.from(document.querySelector(props.container ?? "body")?.querySelectorAll("h2, h3") ?? []);
  updateHeadings(headings);
});
</script>
