<template>
  <Dialog
    id="add-pdf"
    v-model:visible="isOpen"
    modal
    :draggable="false"
    header="Titre du PDF"
    class="dialog"
    :class="{ 'with-comments': isCommentsOpen }"
    :closeOnEscape="true"
  >
    <template #header>
      <button
        v-if="
          dialog.content.id === 'clientBrief' && !dialog.content?.isValidated
        "
        class="btn"
        @click="validate()"
      >
        Valider et envoyer le brief
      </button>
      <h2
        class="font-serif text-lg"
        :title="openedFile?.label.length ? openedFile.label : openedFile.name"
      >
        {{ openedFile?.label.length ? openedFile.label : openedFile.name }}
      </h2>
    </template>
    <div id="vpv-container">
      <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" />
    </div>
  </Dialog>
</template>

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

const router = useRouter();
const route = useRoute();

const dialog = useDialogStore();
const api = useApiStore();
const { openedFile, comments } = storeToRefs(useDialogStore());

openedFile.value = route.query.fileIndex
  ? dialog.content.files[route.query.fileIndex]
  : dialog.content.files[0];

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

const draftComment = ref(null);
const isOpen = ref(true);
watch(isOpen, (newValue) => {
  router.push({ name: route.name });
});
const isCommentsOpen = ref(false);
const currentPageIndex = ref(1);

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

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

// 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);
}

async function validate() {
  const response = await api.validateBrief(route.path + "/client-brief");
  dialog.content.isValidated = true;
}
</script>

<style>
#vpv-container {
  width: var(--dialog-max-w);
  height: calc(var(--dialog-max-h) - var(--dialog-header-h));
  background: black;
  position: relative;
}
.with-comments .vpv-pages-container-wrapper {
  margin-right: var(--dialog-comments-w, 20rem);
}
</style>

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