/**
 * @file
 * erabletheme behaviors.
 */
(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.erabletheme = {
    attach: function (context, settings) {

      //
      // Carrousel
      //
      const isTaxonomyPage = document.querySelector('.taxonomy_page') ? true : false;

      if ($('.slick-container')  && !isTaxonomyPage) {
        let slickEl = $('.slick-container').find('div').eq(3);
        $(slickEl).slick({
          centerMode: true,
          slidesToShow: 3,
          dots: true,
          appendDots: $('#carousel_dots'),
          responsive: [
            {
              breakpoint: 760,
              settings: {
                slidesToShow: 1
              }
            },
          ],
        });
      }

      if ($('.diapo') && !isTaxonomyPage) {
        let slickEl = $('.diapo > div > div');$(slickEl).slick({
          dots: true,
          appendDots: $('#carousel_dots'),
        });
      }

      //
      // Toggle du menu
      //
      const hamburgerBtn = document.getElementById("hamburger");
      const hamburgerIcon = document.querySelector(".burger-icon");
      const menu = hamburgerBtn.nextElementSibling;
      const menuItems = menu.children;
      const opacityDelay = 50;
      let inTransition = false;

      function toggleMenuItems(action) {
        let delay = opacityDelay;
        for (let i = 0; i < menuItems.length; i++) {
          setTimeout(() => {
            if (action === 'show') {
              menuItems[i].classList.add('visible');
            } else if (action === 'hide') {
              menuItems[menuItems.length - i - 1].classList.remove('visible');
            }
          }, delay);
          delay += opacityDelay;
        }
      }

      // Toggle menu visibility on hamburger click
      hamburgerBtn.addEventListener("click", function(event) {
        event.stopPropagation();
        if (!inTransition) {
          inTransition = true;
          hamburgerIcon.classList.toggle('open');
          if(menu.classList.contains('active')) {
            setTimeout(() => {
              menu.style.display = "none";
            }, 700);
            toggleMenuItems('hide');
          } else {
            menu.style.display = "flex";
            toggleMenuItems('show');
          }
          setTimeout(() => {
            menu.classList.toggle("active");
          }, 1);
          setTimeout(() => {
            inTransition = false;
          }, 700);
        }


      });

      // Close menu when clicking outside of the menu
      document.addEventListener("click", function(event) {
        const isHamburgerClicked = event.target === hamburgerBtn;
        const isMenuClicked = event.target === menu || event.target.parentElement === menu;
        if (!isMenuClicked && !isHamburgerClicked && !inTransition) {
          inTransition = true;
          hamburgerIcon.classList.remove('open');
          menu.classList.remove("active");
          toggleMenuItems('hide');
          setTimeout(() => {
            menu.style.display = "none";
            inTransition = false;
          }, 700);
        }
      });

      //
      // Programme page text fade in when it enters viewport
      //
      const url = window.location.pathname;
      if (url.endsWith("le-programme-erable") || url.endsWith("le-programme-erable/")) {
        const textElements = document.querySelectorAll('.fullpage_content p, .fullpage_content h3');
        for (let element of textElements) element.classList.add('faded');
        const fadeInOnScroll = (entries, observer) => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              entry.target.classList.add('fade-in'); // Add your fade-in class
              observer.unobserve(entry.target); // Stop observing once it's visible
            }
          });
        };

        // Create an Intersection Observer
        const observer = new IntersectionObserver(fadeInOnScroll, {
            threshold: 0.1 // Adjust as needed (0.1 means 10% of the element is visible)
        });

        // Attach the observer to each element
        textElements.forEach(element => {
            observer.observe(element);
        });
      }


      //
      // Fixed links
      //
      let fluoButtons;
      if (document.querySelector('.actu_full')) {
        fluoButtons = document.querySelectorAll('.liens_fixed > div > div:nth-of-type(2):not(.visually-hidden), .file_fixed > div > .visually-hidden + div > div');
      } else if (document.querySelector('.offre-content')) {
        fluoButtons = document.querySelectorAll('.liens_fixed > div, .file_fixed > div > div');
      } else if (document.querySelector('.projets')) {
        fluoButtons = document.querySelectorAll('.file_fixed > div > div, .liens > div > div > div');
      } else {
        fluoButtons = document.querySelectorAll('.liens_fixed > div > div:not(.visually-hidden), .file_fixed > div > div, .liens > div > div');
      }

      let footer = document.querySelector('footer');

      function positionFluoLinks(scrollTop) {
        for (let i = fluoButtons.length; i > 0 ; i--) {
          if (window.innerWidth > 1080) {
            const layoutContainerEl = document.querySelector('.layout-container');
            let pageScrollableHeight = layoutContainerEl.offsetHeight;
            let prevButtonBottom = fluoButtons[i] ? parseInt(fluoButtons[i].style.bottom) : 0;
            let prevButtonHeight = fluoButtons[i] ? fluoButtons[i].offsetHeight : 0;
            fluoButtons[i - 1].style.position = 'fixed';
            fluoButtons[i - 1].style.left = document.querySelector('.projets') ? '76vw' : '75vw';
            /* console.log(`
              pageScrollableHeight: ${pageScrollableHeight},
              footer.offsetHeight: ${footer.offsetHeight},
              window.innerHeight: ${window.innerHeight},
              scrollTop: ${scrollTop}
            `); */

            if (pageScrollableHeight - footer.offsetHeight < window.innerHeight + scrollTop && i === fluoButtons.length) {
              let margin = document.querySelector('.projets') ? 15 : 30;
              fluoButtons[i - 1].style.bottom = `${window.innerHeight - footer.offsetTop + scrollTop + margin}px`;
            } else {
              let margin = document.querySelector('.projets') ? 0 : 15;
              fluoButtons[i - 1].style.bottom = i === fluoButtons.length ? '30px' : `${prevButtonBottom + prevButtonHeight + margin}px`;
            }
          } else {
            fluoButtons[i - 1].style.position = 'relative';
            fluoButtons[i - 1].style.left = '0';
            fluoButtons[i - 1].style.bottom = '0';
          }
        }
      }
      if (document.querySelector('.fullpage')) {
        let liens = document.querySelectorAll('.liens_fixed a, .file_fixed a, .content_partenaires a');
        for (let lien of liens) {
          lien.setAttribute('target', '_blank');
        }

        positionFluoLinks();
        document.body.addEventListener('scroll', (e) => {
          positionFluoLinks(e.target.scrollTop);
        });
        window.addEventListener('resize', () => {
          positionFluoLinks();
        });
      }

      // Changer le texte des liens des ressources
      if (document.querySelector('.ressources')) {
        let liens = document.querySelectorAll('.file a');
        for (let lien of liens) {
          lien.innerHTML = 'Télécharger le document';
        }
        // si la ressource n'a pas de date afficher le lien plus haute
        // et la ressource en premier
        let ressources = document.querySelectorAll('.views-row');
        let container = document.querySelector('.views-row:first-of-type').parentElement;

        for (let ressource of ressources) {
          if (!ressource.querySelector('time')) {
            let link = ressource.querySelector('.file');           
            let linkContainer = link.parentElement.parentElement;
            linkContainer.style.gridRow = '2';
            linkContainer.style.marginTop = '30px';
          }

          const rows = Array.from(container.querySelectorAll('.views-row'));

          const undated = [];
          const dated = [];

          rows.forEach(row => {
            if (row.querySelector('time')) {
              dated.push(row);
            } else {
              undated.push(row);
            }
          });

          // Clear container
          container.innerHTML = '';

          // Append undated rows first, then dated
          [...undated, ...dated].forEach(row => {
            container.appendChild(row);
          });
        }
      }


      //
      // Ajouter les logos réseaux sociaux dans le menu togglable
      //
      let socials = document.querySelector('.social-media-links--platforms');
      let socialsClone = socials.cloneNode(true);
      socialsClone.id = 'socials-in-menu-wrapper';
      let menuContainer = document.querySelector('#hamburger + ul');
      let socialsContainer = document.createElement('li');
      socialsContainer.append(socialsClone);
      menuContainer.append(socialsContainer);

      //
      // Retirer paragraphes vides fullpage
      // et ajouter de la marge pour les images en portrait
      //
      let currentPage;
      if (document.querySelector('.fullpage:not(.actus)')) currentPage = 'fullpage';
      else if (document.querySelector('.carousel_container')) currentPage = 'home';

      if (currentPage === 'fullpage') {
        let paragraphs = document.querySelectorAll('p');
        for (let paragraph of paragraphs) {
          if (!/[a-zA-Z]/.test(paragraph.innerText)) {
            paragraph.remove();
          }
        }

        let imgs = document.querySelectorAll('.fullpage img');
        let isActus = document.querySelector('.retour_actus');
        if (isActus) {
          for (let img of imgs) {
            if (img.height > img.width) {
              img.parentElement.style.padding = '0 12vw';
            }
          }
        }
      }

      //
      // all meetup card is a link
      //

      let meetup = document.querySelector('.meetup_list');
      if (meetup) {
        let meetupCards= document.querySelectorAll('.meetup_list > .views-row');
        for (let card of meetupCards) {
          let meetupLink = card.querySelector('.offre-title');
          meetupLink = meetupLink.getAttribute('href');
          let ficheLink = document.createElement('a');
          ficheLink.setAttribute('href', meetupLink);
          let cardArticle = card.querySelector('article');
          ficheLink.append(cardArticle);
          card.append(ficheLink);
        }
      }

      //
      // Sous Menu display on hover
      //

      const programLink = document.querySelector("#block-erabletheme-navigationprincipale ul li:first-of-type");
      const programSubmenu = document.querySelector("#block-erabletheme-leprogramme");
      let isSubmenuOpen = false;

      function showSubmenu() {
        programLink.classList.add("submenu-open");
        let rect = programLink.getBoundingClientRect();
        programSubmenu.style.top = `${rect.bottom}px`;
        programSubmenu.style.left = `${rect.left}px`;
        programSubmenu.style.display = "block";

        programSubmenu.style.display = "block";
        setTimeout(() => {
          programSubmenu.style.maxHeight = "50vh";
        }, 10)

        isSubmenuOpen = true;
      }

      function hideSubmenu() {
        programLink.classList.remove("submenu-open");
        programSubmenu.style.maxHeight = "0px";
        isSubmenuOpen = false;
        setTimeout(() => {
          if (!isSubmenuOpen) {
            programSubmenu.style.display = "none";
          }
        }, 600);
      }

      programLink.addEventListener("mouseenter", showSubmenu);
      programLink.addEventListener("mouseleave", hideSubmenu);

      programSubmenu.addEventListener("mouseenter", showSubmenu);
      programSubmenu.addEventListener("mouseleave", hideSubmenu);

      //
      // Aside menu toggle
      //

      const sideMenuTitle =
      document.querySelector('#block-erabletheme-leprogramme-2 h2') ||
      document.querySelector('#block-erabletheme-views-block-projets-block-1 h2');

      if (sideMenuTitle) {
        sideMenuTitle.addEventListener('click', () => {
          const sideMenu = document.querySelector('#block-erabletheme-leprogramme-2 > ul') ||
          document.querySelector('#block-erabletheme-views-block-projets-block-1 .projets_list');
          const titleArrow = sideMenuTitle.querySelector('div');
          if (!sideMenu.classList.contains('closed')) {
            sideMenu.classList.add('closed');
            titleArrow.classList.add('closed');
          } else {
            sideMenu.classList.remove('closed');
            titleArrow.classList.remove('closed');
          }
        });
      }

      //
      // set active project in aside project menu
      //

      const asideProjectMenu = document.querySelector('#block-erabletheme-views-block-projets-block-1 .projets_list');
      if (asideProjectMenu) {
        for (let item of asideProjectMenu.children) {
          const itemTitle = item.innerText;
          const contentPage = document.querySelector('.projet_full');
          const contentPageTitle = contentPage.querySelector('h2').innerText;

          if (itemTitle.toLowerCase() === contentPageTitle.toLowerCase()) {
            item.querySelector('a').classList.add('is-active');
          }
        }
      }

      //
      // set non breaking spaces
      //

      document.querySelectorAll('p, li, h1, h2, h3, h4, h5, h6').forEach((content) => {
        content.innerHTML = content.innerHTML.replaceAll(' ;', '&nbsp;;');
        content.innerHTML = content.innerHTML.replaceAll(' :', '&nbsp;:');
        content.innerHTML = content.innerHTML.replaceAll(' ?', '&nbsp;?');
        content.innerHTML = content.innerHTML.replaceAll(' !', '&nbsp;!');
        content.innerHTML = content.innerHTML.replaceAll('« ', '«&nbsp;');
        content.innerHTML = content.innerHTML.replaceAll(' »', '&nbsp;»');
        content.innerHTML = content.innerHTML.replaceAll('(« ', '(«&nbsp;');
        content.innerHTML = content.innerHTML.replaceAll(' »)', '&nbsp;»)');
      });

      //
      // index projets random shape
      //

      if (document.querySelector('.projets_list')) {
        const projets = document.querySelectorAll('.projets_list > .views-row');
        const shapesAmount = 6;
        for (let i = 0; i < projets.length; i++) {
          const randomShape = Math.floor(Math.random() * shapesAmount) + 1;
          if (projets[i].querySelector('img')) {
            const img = projets[i].querySelector('a');
            img.style.maskImage = `url('/themes/erabletheme/assets/shapes/shape_${randomShape}.svg')`;
          }
        }
      }

      //
      // set bg middle placement
      //
      let pageHeight = document.querySelector('.layout-container').offsetHeight;
      toggleBgMiddle(pageHeight)

      window.addEventListener('resize', () => {
        pageHeight = document.querySelector('.layout-container').offsetHeight;
        toggleBgMiddle(pageHeight);
      })

      function toggleBgMiddle(pageHeight) {
        const bgMiddle = document.querySelector('#bg-middle');
        const bgOnze = document.querySelector('#bg-11');
        if (pageHeight < 2500) {
          bgMiddle.style.display = 'none';
          bgOnze.style.display = 'none';
        } else {
          bgMiddle.style.display = 'block';
          bgOnze.style.display = 'block';
        }
      }

      //
      // bg parallax animation
      //
      var rellax = new Rellax('.bgImg', {
        wrapper: 'body',
      });
    }
  }

  let firstMap = null;

  Drupal.behaviors.customLeafletInteraction = {
    attach: function (context, settings) {
      $(context).on('leafletMapInit', function (e, settings, map, mapid, markers) {

        if (document.querySelector('.projet_full')) {
          // map on the projects page

          let customIcon = L.icon({
            iconUrl: '/themes/erabletheme/assets/leaf.svg',
            iconSize: [20, 20],
            iconAnchor: [10, 20],
            popupAnchor: [0, -20]
          });

          let initiatedMap = document.querySelector(`#${mapid}`);
          const currentLibelle = initiatedMap.parentElement.nextElementSibling.innerText;
          initiatedMap.parentElement.nextElementSibling.remove();
  
          if (document.querySelectorAll('.leaflet-container').length <= 1) {
            firstMap = map;
            let bounds = L.latLngBounds();
            map.eachLayer(function (layer) {
              if (layer instanceof L.Marker && !layer._popup) {
                layer.bindPopup(currentLibelle, { closeButton: false, className: 'popup' })
                  .setIcon(customIcon)
                  .on('mouseover', function () {
                    this.openPopup();
                  })
                  .on('mouseout', function () {
                    this.closePopup();
                  });

                bounds.extend(layer.getLatLng());
                map.fitBounds(bounds, { padding: [30, 30], maxZoom: 18 });
              }
            });
          } else {
            // map on the projects index

            document.querySelector(`#${mapid}`).parentElement.parentElement.parentElement.remove();
            const firstMarker = Object.values(markers)[0];
            let newMarker = L.marker([firstMarker._latlng.lat, firstMarker._latlng.lng], { icon: customIcon })
              .addTo(firstMap)
              .bindPopup(currentLibelle, { closeButton: false, className: 'popup' })
              .on('mouseover', function () {
                this.openPopup();
              })
              .on('mouseout', function () {
                this.closePopup();
              });

              firstMap.fitBounds(
                firstMap.getBounds().extend(newMarker.getLatLng()),
                { padding: [30, 30], maxZoom: 18 }
              );
          }
        } else {
          //
          // on projects pages, replace leaflet icons with erable leafs
          //
          const currentMap = document.querySelector('.leaflet-container');
          const leafletIcons = document.querySelectorAll('.leaflet-marker-pane img');
          for (let icon of leafletIcons) {
            icon.setAttribute('src', '/themes/erabletheme/assets/leaf.svg');
          }
  
          //
          // set hover on leaflet marker and zones
          //
          const leafletPlaces = document.querySelectorAll('.leaflet-marker-pane img, .leaflet-overlay-pane path');
          const libelles = document.querySelectorAll('.libelles-carte > div > div > div');
  
          for (let i = 0; i < leafletPlaces.length; i++) {
            const carte = document.querySelector('.carte');
  
            leafletPlaces[i].addEventListener('mouseenter', () => {
              let div = document.createElement('div');
              div.setAttribute('id', 'leaflet-popup');
              div.style.zIndex = '100';
              const x = leafletPlaces[i].getBoundingClientRect().left + leafletPlaces[i].getBoundingClientRect().width / 2;
              const y = leafletPlaces[i].getBoundingClientRect().top;
              setTimeout(() => {
                div.style.opacity = 1;
                const divHeight = div.getBoundingClientRect().height;
                const divWidth = div.getBoundingClientRect().width;
                setTimeout(() => {
                  div.style.left = `${x - divWidth / 2}px`;
                  div.style.top = `${y - divHeight}px`;
                }, 10);
              }, 10);
  
              div.innerText = libelles[i].innerText;
  
              carte.appendChild(div);
            });
            leafletPlaces[i].addEventListener('mouseleave', () => {
              let divs = document.querySelectorAll('#leaflet-popup');
              for (let div of divs) {
                div.style.opacity = 0;
                setTimeout(() => {
                  div.remove();
                }, 300);
              }
            });
          }
        }
      });
    }
  }

} (jQuery, Drupal));
