<template>
  <VPdfViewer
    :darkMode="true"
    :initialThumbnailsVisible="true"
    :src="openedFile.url"
    local="fr_FR"
    @loaded="onPdfLoaded"
  />
  <button
    id="toggle-comments"
    :aria-pressed="isCommentsOpen"
    class="btn btn--transparent btn--outline"
    data-icon="comment"
    @click="isCommentsOpen = !isCommentsOpen"
  >
    <span class="sr-only">Afficher les commentaires</span>
  </button>
  <Comments v-if="isCommentsOpen" @show-draft-marker="showDraftMarker" />
</template>

<script setup>
import Comments from "../comments/Comments.vue";
import { ref, watch } from "vue";
import { useDialogStore } from "../../stores/dialog";
import { storeToRefs } from "pinia";
import { VPdfViewer, useLicense } from "@vue-pdf-viewer/viewer";
import { useRoute, useRouter } from "vue-router";

const licenseKey = import.meta.env.VITE_VPV_LICENSE;
useLicense({ licenseKey });

const { openedFile, isCommentsOpen, comments } = storeToRefs(useDialogStore());

const draftComment = ref(null);

watch(isCommentsOpen, (newVal) => {
  if (newVal) {
    setCommentMarkers();
  } else {
    removeCommentMarkers();
  }
});

watch(openedFile, (newVal) => {
  removeCommentMarkers();
  if (newVal.comments) {
    setCommentMarkers();
  }
});

const currentPageIndex = ref(1);

// Functions
const onPdfLoaded = () => {
  const wrapper = document.querySelector(".vpv-pages-inner-container");

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry, index) => {
        if (entry.intersectionRatio > 0.5) {
          currentPageIndex.value = parseInt(
            entry.target.getAttribute("aria-label").split(" ")[1]
          );
        }
      });
    },
    {
      root: wrapper,
      threshold: [0.5],
    }
  );

  const observePages = () => {
    const pages = document.querySelectorAll(".vpv-page-inner-container");
    pages.forEach((page) => {
      if (!page.__observed__) {
        observer.observe(page);
        page.__observed__ = true;
      }
    });
  };

  const mutationObserver = new MutationObserver(() => {
    observePages();
  });

  if (wrapper) {
    mutationObserver.observe(wrapper, { childList: true, subtree: true });
  }

  observePages();
};

function setCommentMarkers() {
  if (!comments.value) return;
  comments.value.forEach((comment) => {
    const bubble = document.createElement("a");

    bubble.classList.add("comment-marker");
    bubble.style.left = comment.position.x + "%";
    bubble.style.top = comment.position.y + "%";
    bubble.href = "#comment-" + comment.id;

    const container = document.querySelector(
      `.vpv-page-inner-container[aria-label="page ${comment.position.pageIndex}"] .page-inner-container`
    );

    container.appendChild(bubble);

    setTimeout(() => {
      bubble.addEventListener("mouseenter", () => highlight(comment));
      bubble.addEventListener("mouseleave", () => unhighlight(comment));
    }, 100);
  });
}

function highlight(comment) {
  const target = document.querySelector("#comment-" + comment.id);
  target.classList.add("highlight");
}
function unhighlight(comment) {
  const target = document.querySelector("#comment-" + comment.id);
  target.classList.remove("highlight");
}

function removeCommentMarkers() {
  document.querySelectorAll(".comment-marker").forEach((bubble) => {
    bubble.parentNode.removeChild(bubble);
  });
}

function showDraftMarker(draftComment) {
  const bubble = document.createElement("a");

  bubble.classList.add("comment-marker");
  bubble.classList.add("comment-marker--draft");
  bubble.style.left = draftComment.position.x + "%";
  bubble.style.top = draftComment.position.y + "%";
  bubble.href = "#comment-" + draftComment.id;

  const container = document.querySelector(
    `.vpv-page-inner-container[aria-label="page ${draftComment.position.pageIndex}"] .page-inner-container`
  );

  container.appendChild(bubble);
}
</script>

<style scoped>
@import "../../assets/css/src/2.blocks.pdf-viewer.css";
</style>
