<!doctype html>
<html <?php language_attributes(); ?>>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
  </head>

  <body <?php body_class(); ?>>
    <?php wp_body_open(); ?>
    <?php do_action('get_header'); ?>

    <div id="app" class="banner bg-jlg-dark-blue text-jlg-white font-authentic flex w-full flex-col justify-center items-center">
      <?php echo view(app('sage.view'), app('sage.data'))->render(); ?>
    </div>

    <script>
      document.addEventListener('DOMContentLoaded', function () {
        // CLEANER LE TABLEAU
        let minHeadTh = document.querySelector("#main table thead tr th:first-of-type");
        minHeadTh.style.width = `${100 / 8}%`;

        let otherHeadThs = document.querySelectorAll("#main table thead tr th:not(:first-of-type)");
        for (let otherHeadTh of otherHeadThs) {
          otherHeadTh.style.width = `${100 / 8 * 1.75}%`;
        }
        
        let minTableTds = document.querySelectorAll("#main table tbody tr td:first-of-type");
        for (let minTableTd of minTableTds) {
          if (minTableTd.parentNode.childElementCount != 1) {
            minTableTd.style.width = `${100 / 8}%`;
          }
        }

        let otherTableTds = document.querySelectorAll("#main table tbody tr td:not(:first-of-type)");
        for (let otherTableTd of otherTableTds) {
          otherTableTd.style.width = `${100 / 8 * 1.75}%`;
        }
        // HEADER AU SCROLL
        let tableHead = document.querySelector("thead tr");
        let tHeadHeight = tableHead.offsetHeight;
        window.onscroll = () => {
          tableHead.style.minHeight = `${document.querySelector("header").offsetHeight + 72}px`;
          let scroll = window.pageYOffset;
          let headerNewHeight = tHeadHeight - scroll;
          tableHead.style.height = `${headerNewHeight}px`;
        }
        // italiques -> A FAIRE SUR LE CSV AVANT D'IMPORTER CA RALENTIT DE OUF LE CHARGEMENT
        let tbody = document.querySelectorAll('tbody');
        let tbodyContent = tbody[0].innerHTML;
        let asteriskCounter = 0;
        for (let i = 0; i < tbodyContent.length; i++) {
          if (tbodyContent[i] == "*") {
            if (asteriskCounter % 2 == 0) {
              tbodyContent = tbodyContent.substring(0, i) + '<span class="font-caslon italic">' + tbodyContent.substring(i + 1);
            } else {
              tbodyContent = tbodyContent.substring(0, i) + '</span>' + tbodyContent.substring(i + 1);
            }
            asteriskCounter++;
          }
        }
        tbody[0].innerHTML = tbodyContent;


        // titres de parties
        let mainpartTitless = document.querySelectorAll('.isMainPart');
        for (let mainpartTitles of mainpartTitless) {
          if (mainpartTitles.nextElementSibling.classList.contains('isSubPart')) {
            mainpartTitles.firstElementChild.firstElementChild.style.height = "1.5rem";
            mainpartTitles.firstElementChild.style.marginBottom = "-0.25rem";
            mainpartTitles.style.borderBottom = "0";
            mainpartTitles.style.paddingBottom = "0";
            mainpartTitles.nextElementSibling.style.paddingTop = "0";
          }
        }
        // couleurs titres
        let colors = [
          {'red' : 'e4000c'},
          {'blue1': '5dfffd'},
          {'blue2': '0fe5f9'},
          {'blue3': '11c1f8'},
          {'blue4': '0779f1'},
          {'blue5': '040bcb'},
          {'yellow1': 'ffe113'},
          {'yellow2': 'f4ff1b'},
          {'yellow3': 'e2ff0c'},
          {'yellow4': '93fe0b'},
          {'yellow5': '17fe0b'},
          {'pink1': 'e70060'},
          {'pink2': 'f03cf3'}
        ];
        let titles = document.querySelectorAll('.isMainPart, .isSubPart');
        let partTitles = [];
        for (let title of titles) {
          if (!title.nextElementSibling.classList.contains('isSubPart')) {
            partTitles.push(title);
          }
        }
        for (let i  = 0; i < partTitles.length; i++) {
          if (partTitles[i].previousElementSibling?.classList.contains('isMainPart')) {
            partTitles[i].previousElementSibling.firstElementChild.firstElementChild.style.backgroundColor = "#" + Object.values(colors[i])[0];
          }
          partTitles[i].firstElementChild.firstElementChild.style.backgroundColor = "#" + Object.values(colors[i])[0];
        }
        // scroll with cursor
        // display parts rectangle on timeline

        let tlContainer, tlContainerHeight, bodyHeight;
        let partsHeight = [];
        let prevHeight = 0;
        let partBlockHeights = [];
        let activePartIndex;

        function getAllHeights() {
          tlContainer = document.querySelector('#timeline_container');
          tlContainerHeight = tlContainer.offsetHeight;
          bodyHeight = document.querySelector('tbody').offsetHeight;
          let lastTitle = document.querySelectorAll('.isMainPart');
          lastTitle = lastTitle[lastTitle.length - 1];
          for (let i  = 0; i < partTitles.length; i++) {
            let elTopFromParentTop = partTitles[i].offsetTop - document.querySelector('tbody').offsetTop;
            let partSize = elTopFromParentTop - prevHeight;
            prevHeight = elTopFromParentTop;
            if (i != 0) {
              partsHeight.push(partSize);
            }
          }
          partsHeight.push(bodyHeight - lastTitle.offsetTop);
          const partsHeightSum = partsHeight.reduce((partialSum, a) => partialSum + a, 0);
          for (let partHeight of partsHeight) {
            partBlockHeights.push(partHeight / bodyHeight * tlContainerHeight);
          }
        }
        getAllHeights();
        
        function drawFriseRects() {
          for (let i = 0; i < partBlockHeights.length; i++) {
            let partDiv = document.createElement('div');
            partDiv.style.width = "32px";
            partDiv.style.height = partBlockHeights[i] + "px";
            partDiv.style.backgroundColor = "#" + Object.values(colors[i])[0];
            partDiv.style.borderBottom = "solid 1.5px #010d19";
            partDiv.style.opacity = "0.6";
            partDiv.style.transition = "opacity 0.3s ease-out";
            partDiv.style.cursor = "pointer";
            tlContainer.prepend(partDiv);
            tlContainer.children[0].addEventListener("mouseenter", function() {
              let el = tlContainer.children[tlContainer.children.length - 1 - i];
              el.style.opacity = "1";
            });
            tlContainer.children[0].addEventListener("mouseleave", function() {
              let el = tlContainer.children[tlContainer.children.length - 1 - i];
              if (Array.from(el.parentNode.children).indexOf(el) != activePartIndex) {
                el.style.opacity = "0.7";
              }
            });
          }
        }
        drawFriseRects();

        window.addEventListener("resize", (event) => {
          getAllHeights();
          tlContainer.innerHTML = '';
          drawFriseRects();
        });
        
        // make the cursor move on scroll
        let scrollValue, cursorTop;
        let cursor = document.querySelector('#cursor');
        cursor.style.transform = `translateY(${window.scrollY / bodyHeight * tlContainerHeight}px)`;
        getActivePart();
        document.addEventListener("scroll", (event) => {
          scrollValue = window.scrollY;
          let diffSize = scrollValue / bodyHeight * tlContainerHeight;
          cursor.style.transform = `translateY(${diffSize}px)`;
          cursorTop = cursorTop + diffSize;
          getActivePart();
        });
        // make the cursor draggable
        let isCursorGrabbed = false;
        let cursorPrevTranslateAmount = +cursor.style.transform.slice(0, -3).slice(11);
        let prevCursorPos = 0;
        cursor.addEventListener("mousedown", (event) => {
          if (!isCursorGrabbed) {
            event.preventDefault();
            isCursorGrabbed = true;
            prevCursorPos = event.clientY;
          }
        });
        window.addEventListener("mousemove", (event) => {
          if (isCursorGrabbed) {
            event.preventDefault();
            let newPos = cursorPrevTranslateAmount + (event.clientY - prevCursorPos);
            if (event.clientY < tlContainerHeight + tlContainer.offsetTop && event.clientY > tlContainer.offsetTop) {
              cursor.style.transform = `translateY(${newPos}px)`;
              window.scrollBy(0, (event.clientY - prevCursorPos) * (bodyHeight / tlContainerHeight));
              cursorPrevTranslateAmount = +cursor.style.transform.slice(0, -3).slice(11);
              getActivePart();
            } else if (event.clientY <= tlContainer.offsetTop) {
              cursor.style.transform = "translateY(0px)";
              window.scroll(0, 0);
              cursorPrevTranslateAmount = 0;
            } else if (event.clientY >= tlContainerHeight + tlContainer.offsetTop) {
              cursor.style.transform = `translateY(${tlContainerHeight}px)`;
              window.scroll(0, bodyHeight);         
              cursorPrevTranslateAmount = +cursor.style.transform.slice(0, -3).slice(11);
            }
            prevCursorPos = event.clientY;
          }
        });
        window.addEventListener("mouseup", (event) => {
          if (isCursorGrabbed) {
            isCursorGrabbed = false;
          }
        });
        // lighten active part rectangle
        function getActivePart() {
          let partRects = tlContainer.children;
          let cursorYPos = cursor.getBoundingClientRect().top + cursor.clientHeight / 2;
          if (cursorYPos >= Object.values(partRects)[0].getBoundingClientRect().bottom) {
            for (let partRect of partRects) {
              partRect.style.opacity = 0.6;
            }
            Object.values(partRects)[0].style.opacity = 1;
          } else {
            for (let i = 0; i < partRects.length; i++) {
              if (cursorYPos >= partRects[i].getBoundingClientRect().top && cursorYPos < partRects[i].getBoundingClientRect().top + partRects[i].clientHeight) {
                partRects[i].style.opacity = 1;
                activePartIndex = i;
              } else {
                partRects[i].style.opacity = 0.6;
              }
            }
          }
        }

        // TODO
        // ajouter le titre collé au curseur et le temps total en bas
        // smoothscroll au clic sur une partie
      }, false);
    </script>

    <?php do_action('get_footer'); ?>
    <?php wp_footer(); ?>
  </body>
</html>
