<template>
  <AppPage>
    <PageContent :page="page">
      <template #mobile-toc>
        <PageMobileToc :title="page.body.toc.title" :toc="page.body.toc.links" />
      </template>
    </PageContent>

    <EditOnGithub v-if="repoUrl" :page="page" />

    <template #prev-next>
      <PagePrevNext :prev="prev" :next="next" />
    </template>

    <template #toc>
      <PageToc v-if="!page.body.hideToc" :title="page.body.toc.title" :toc="page.body.toc.links" />
    </template>
  </AppPage>
</template>

<script>
import { defineComponent, ref, useContext, useFetch, onMounted } from "@nuxtjs/composition-api";
import { useGitHub } from "../../composables";
import { scrollToHeading } from "../../utils";
export default defineComponent({
  props: {
    page: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const { $docus } = useContext();
    const { repoUrl } = useGitHub();
    const prev = ref(null);
    const next = ref(null);
    onMounted(() => {
      if (window.location.hash) {
        const hash = window.location.hash.replace("#", "");
        setTimeout(() => {
          scrollToHeading(hash, "--docs-scroll-margin-block");
        }, 300);
      }
      setTimeout(() => {
        const headings = [
          ...document.querySelectorAll(".docus-content h1"),
          ...document.querySelectorAll(".docus-content h2"),
          ...document.querySelectorAll(".docus-content h3")
        ];
        headings.forEach((heading) => {
          heading.addEventListener("click", (e) => {
            e.preventDefault();
            const hash = e.target.href.split("#").pop();
            scrollToHeading(hash, "--docs-scroll-margin-block");
          });
        });
      }, 500);
    });
    useFetch(async () => {
      const [prevLink, nextLink] = await $docus.getPreviousAndNextLink(props.page);
      prev.value = prevLink;
      next.value = nextLink;
    });
    return {
      repoUrl,
      prev,
      next
    };
  },
  templateOptions: {
    aside: true,
    fluid: false
  }
});
</script>
