<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>
      <a class="btn">Valider et envoyer le brief</a>
      <h2 class="font-serif text-lg">Titre du PDF</h2>
    </template>
    <div id="vpv-container">
      <VPdfViewer
        :darkMode="true"
        :initialThumbnailsVisible="true"
        :src="file.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"
        :current-page-index="currentPageIndex"
        :file="file"
        :comments="file.comments ?? []"
        @update:file="changeFile"
      />
    </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";

const { file } = defineProps({
  file: Object,
});

const emits = defineEmits(["close", "update:file"]);

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

// Variables
const isOpen = ref(true);
watch(isOpen, (newValue) => {
  emits("close");
});
const isCommentsOpen = ref(false);
const currentPageIndex = ref(1);

watch(isCommentsOpen, (newVal) => {
  if (newVal) {
    setCommentBubbles();
  } else {
    removeCommentBubbles();
  }
});

watch(
  () => file,
  (newVal) => {
    removeCommentBubbles();
    if (newVal.comments) {
      setCommentBubbles();
    }
  }
);

// 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 changeFile(newFile) {
  emits("update:file", newFile);
}

function setCommentBubbles() {
  console.log(file.comments);
  if (!file.comments) return;
  file.comments.forEach((comment) => {
    const bubble = document.createElement("a");

    bubble.classList.add("comment-bubble");
    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 removeCommentBubbles() {
  document.querySelectorAll(".comment-bubble").forEach((bubble) => {
    bubble.parentNode.removeChild(bubble);
  });
}
</script>

<style>
.comment-bubble {
  position: absolute;
  display: block;
  width: 1.2rem;
  height: 1.2rem;
  background: url("/assets/svg/comment-bubble.svg") no-repeat !important;
  cursor: pointer !important;
  z-index: 999;
}
#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>
:deep(.vpv-variables) {
  /* Base styles */
  --vpv-base-radius: var(--rounded-xl);
  /* Viewer container */
  --vpv-container-width-sm: 48rem;
  /* Toolbar */
  --vpv-toolbar-size: 4.5rem;
}
:deep(.vpv-variables.vpv-variables__dark) {
  /* Base styles */
  --vpv-base-border-color: var(--color-grey-700);
  /* Viewer container */
  --vpv-container-border-color: var(--vpv-base-border-color);
  /* Loader */
  --vpv-loader-backdrop-color: rgba(0, 0, 0, 0.8);
  /* Toolbar */
  --vpv-toolbar-background-color: var(--color-white-10);
  --vpv-toolbar-color: white;
  --vpv-toolbar-border-color: var(--vpv-base-border-color);
  /* Sidebar */
  --vpv-sidebar-content-background-color: var(--color-white-10);
  --vpv-sidebar-content_thumbnail-focused-border-color: var(--color-white-20);
  /* Drop file mask */
  --vpv-drop-zone-background: #1c2024;
  --vpv-drop-zone-border: #434c56;
  /* PDF Pages Content*/
  --vpv-pages-container-background: black;
  /* Popover */
  --vpv-popover-background-color: black;
  --vpv-popover-color: var(--color-white);
  --vpv-popover-border-color: transparent;
  /* Menu Dropdown */
  --vpv-dropdown-menu-content-background: #181818;
  --vpv-dropdown-menu-content-menu-hover-background: var(--color-white-10);
  --vpv-dropdown-menu-content-separator-background: var(--color-white-10);
  --vpv-dropdown-menu-content-border-color: var(--color-white-10);
  --vpv-dropdown-separator: var(--color-white-10);
  /* Search Input */
  --vpv-input-background-color: transparent;
  --vpv-input-border-color: var(--color-white);
  --vpv-input-placeholder-color: #596673;
  /* Modal of PDF Properties */
  --vpv-properties-content-background: var(
    --vpv-dropdown-menu-content-background
  );
  --vpv-properties-content-secondary-color: #c6ccd2;
  --vpv-properties-content-color: var(--vpv-toolbar-color);
  --vpv-properties-separator: var(--vpv-dropdown-separator);
  --vpv-properties-header: white;
  /* Modal of Print Progress */
  --vpv-print-progress-background: var(--vpv-dropdown-menu-content-background);
  /* Tooltip */
  --vpv-tooltip-background: #181818;
  --vpv-tooltip-color: white;
  --vpv-tooltip-border-color: var(--color-black);
  /* Outline */
  --vpv-outline-color: var(--color-white-10);
}

:deep(.vpv-container) {
  border-top-left-radius: 0 !important;
  border-top-right-radius: 0 !important;
}
:deep(.vpv-body-wrapper),
:deep(.vpv-container .vpv-sidebar-wrapper) {
  margin-top: 0 !important;
  margin-bottom: var(--vpv-toolbar-size) !important;
}
:deep(.vpv-splitter) {
  max-width: 0;
}

/* Sidebar */
:deep(.vpv-container .vpv-sidebar-wrapper__opened) {
  max-width: 9rem;
}
:deep(.vpv-sidebar-features) {
  display: none;
}
:deep(.pdf-thumbnail-wrapper .pdf-thumbnail img),
:deep(.pdf-thumbnail-wrapper .pdf-thumbnail .placeholder) {
  border-radius: var(--rounded-md);
}

/* Toolbar */
:deep(.vpv-container .vpv-toolbar-wrapper) {
  border-bottom-width: 0;
  border-top-width: 1px;
  padding-left: 1rem !important;
}
:deep(.vpv-toolbar-wrapper) {
  top: unset !important;
  bottom: 0 !important;
}
:deep(.vpv-toolbar-start .vpv-toolbar-btn) {
  display: none;
}
:deep(.vpv-toolbar-start::before) {
  content: "Page";
}
:deep(.vpv-input) {
  border-radius: var(--rounded-sm) !important;
  max-width: 1.5rem !important;
}
:deep(.vpv-input ~ span) {
  color: var(--color-grey-400);
}
:deep(.vpv-toolbar-end) {
  padding-right: 4rem;
}
:deep(.vpv-toolbar-end > button:nth-child(1)),
:deep(.vpv-toolbar-end > button:nth-child(3)),
:deep(.vpv-toolbar-end > button:nth-child(4)) {
  display: none;
}
</style>
