#set($backtick = "`")
#set($dollar = "$")

<div class="ws-mobile-content ws-mobile-content--$currentPortlet">
   <button class="ws-mobile-content__toggle">
      Visa sidans innehåll
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">
         <path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
   </button>
   <nav class="ws-mobile-content__nav ws-mobile-content__nav--closed">
      <div class="ws-mobile-content__wrapper">
         <ul class="ws-mobile-content__list">
         </ul>
         <svg xmlns="http://www.w3.org/2000/svg">
            <path></path>
         </svg>
      </div>
   </nav>
</div>

<script>
   document.addEventListener("DOMContentLoaded", () => {
      const toggleButton = document.querySelector('.ws-mobile-content__toggle');
      const nav = document.querySelector('.ws-mobile-content__nav');
      const visibleClass = 'ws-mobile-content__link--visible';
      const list = document.querySelector('.ws-mobile-content__list');
      const navPath = nav.querySelector('svg path');

      toggleButton.addEventListener('click', () => {
         nav.classList.toggle('ws-mobile-content__nav--closed');
         toggleButton.classList.toggle('ws-mobile-content__toggle--open');
      });

      const sections = document.querySelectorAll('section[id]');

      let navItems = [];

      function createNavItems() {
         sections.forEach(section => {
            const sectionID = section.getAttribute('id');
            
            const heading = section.querySelector("h2")?.textContent

            if(heading) {
               const listItem = document.createElement('li');
               listItem.classList.add("ws-mobile-content__item");
               const anchor = document.createElement('a');
               anchor.classList.add("ws-mobile-content__link");
               anchor.setAttribute('href', ${backtick}#${dollar}{sectionID}${backtick});
               anchor.textContent = heading;
               listItem.appendChild(anchor);
               list.appendChild(listItem);
            }
         });

         navItems = [...nav.querySelectorAll('li')].map(listItem => {
            const anchor = listItem.querySelector('.ws-mobile-content__link');
            const targetID = anchor && anchor.getAttribute('href').slice(1);
            const target = document.getElementById(targetID);

            return { listItem, anchor, target };
         }).filter(item => item.target);

			const anchors = nav.querySelectorAll('.ws-mobile-content__link');
			anchors.forEach(anchor => {
          anchor.addEventListener('click', (event) => {
               event.preventDefault();
               const targetID = anchor.getAttribute("href").slice(1);
               const target = document.getElementById(targetID);

               target.scrollIntoView({behavior: 'smooth'});
               
               const observer = new IntersectionObserver((entries, observer) => {
               entries.forEach(entry => {
               console.log(entry)
                  if(entry.isIntersecting) {
                  console.log(entry)
                     nav.classList.add('ws-mobile-content__nav--closed');
                     toggleButton.classList.remove('ws-mobile-content__toggle--open');
                     observer.disconnect();
                  }
                  });
               }, {threshold: [0.1, 0.5, 1.0]});
               observer.observe(target);
				});
			});
      }

      createNavItems();

      drawPath();

      function drawPath() {
         let path = [], 
             pathIndent;

         navItems.forEach((item, i) => {
            const x = item.anchor.offsetLeft - 5,
                  y = item.anchor.offsetTop,
                  height = item.anchor.offsetHeight;

            if(i === 0) {
               path.push('M', x, y, 'L', x, y + height);
               item.pathStart = 0;
            } else {
               if(pathIndent !== x)
                  path.push('L', pathIndent, y);

               path.push('L', x, y);

               navPath.setAttribute('d', path.join(' '));
               item.pathStart = navPath.getTotalLength() || 0;
               path.push('L', x, y + height);  
            }

            pathIndent = x;
            navPath.setAttribute('d', path.join(' '));
            item.pathEnd = navPath.getTotalLength();
         });
      }

      function syncPath() {
         const someElsAreVisible = () => 
            nav.querySelectorAll(`.${dollar}{visibleClass}`).length > 0,
            thisElIsVisible = el =>
            el && el.classList.contains(visibleClass),
            pathLength = navPath.getTotalLength();

         let pathStart = 0;
         let pathEnd = 0;
         let lastPathEnd;

         navItems.forEach(item => {
            if (item.listItem && thisElIsVisible(item.listItem)) {
               pathEnd = Math.max(item.pathEnd, pathEnd);
            }
         });
         if (someElsAreVisible() && pathEnd > pathStart) {
            if (pathEnd !== lastPathEnd) {
               const dashArray = ${backtick}1 ${dollar}{pathStart} ${dollar}{pathEnd - pathStart} ${dollar}{pathLength}${backtick};

               navPath.style.setProperty('stroke-dashoffset', '1');
               navPath.style.setProperty('stroke-dasharray', dashArray);
               navPath.style.setProperty('opacity', 1);
            }
         } else { 
            navPath.style.setProperty('opacity', 0);
         }

         lastPathEnd = pathEnd;
      }

      let lastVisibleItem = null;

      function markVisibleSection() {
         let maxVisibleArea = 0;
         let largestVisibleSection = null;

         sections.forEach((section) => {
            let rect = section.getBoundingClientRect();
            let visibleArea = Math.max(0, Math.min(rect.bottom, window.innerHeight) - Math.max(rect.top, 0)) * Math.max(0, Math.min(rect.right, window.innerWidth) - Math.max(rect.left, 0));

            if (visibleArea > maxVisibleArea) {
               maxVisibleArea = visibleArea;
               largestVisibleSection = section;
            }
         });

         if (largestVisibleSection) {
            const current = largestVisibleSection.getAttribute('id');
            const anchor = document.querySelector(`.ws-mobile-content__nav li a[href="#${dollar}{current}"]`);
            if (!anchor) return;

            const listItem = anchor.parentElement;

            if (lastVisibleItem) {
               lastVisibleItem.classList.remove(visibleClass);
            }
            listItem.classList.add(visibleClass);
            lastVisibleItem = listItem;
         }

         syncPath();
      }

      window.addEventListener('scroll', markVisibleSection);

      markVisibleSection();
   });
</script>
