// This Javascript is responsible for...
// ...the navigation sidebars on the left and right, and shows or hides them depending on display's size
// ...the pages main content's width

// set paths of the footer logos dynamically depending on host
// maybe redundant, needs testing
document.addEventListener('DOMContentLoaded', () => {
  var copy1;
  var copy2;
  var copy3;
  var hostname = window.location.hostname;
  var pathname = window.location.pathname;
  copy1 = "/medien/logo-rub.png";
  copy2 = "/medien/logo-worldfactory.png";
  copy3 = "/medien/logo-esc.png";

  if (hostname === 'localhost' || pathname.includes('127.0.0.1')) {
    copy1 = "/medien/logo-rub.png";
    copy2 = "/medien/logo-worldfactory.png";
    copy3 = "/medien/logo-esc.png";
  } 
  else if (hostname.includes('makerspace.ruhr-uni-bochum.de')) {
    copy1 = "/medien/logo-rub.png";
    copy2 = "/medien/logo-worldfactory.png";
    copy3 = "/medien/logo-esc.png";
  } 
  else if (hostname.includes('ruhr-uni-bochum.de') && pathname.includes('/makerspace/')) {
    copy1 = "/makerspace/medien/logo-rub.png";
    copy2 = "/makerspace/medien/logo-worldfactory.png";
    copy3 = "/makerspace/medien/logo-esc.png";
  }

  const c1 = document.querySelectorAll('.copyright1');
  c1.forEach(element => {
    element.src = copy1;
  });  

  const c2 = document.querySelectorAll('.copyright2');
  c2.forEach(element => {
    element.src = copy2;
  });

  const c3 = document.querySelectorAll('.copyright3');
  c3.forEach(element => {
    element.src = copy3;
  });
});

// Protects the ears of our dear visitors by setting the starting volume of our videos to a low amount
document.addEventListener("DOMContentLoaded", function() {
  // Select all video elements on the page
  var videos = document.querySelectorAll("video");
  
  // Loop through each video
  if (videos){
    for(var i = 0; i < videos.length; i++) {
      // Set the volume to your desired level (e.g., 0.2)
      videos[i].volume = 0.1;
    }
  }
});

document.addEventListener('DOMContentLoaded', function() {
  var videoContainers = document.querySelectorAll('.video-container');

  videoContainers.forEach(function(container) {
      var video = container.querySelector('video');
      var videoSrc = video.querySelector('source').src;
      var thumbnailSrc = videoSrc.replace('.mp4', '.jpg'); // Assuming a naming convention for thumbnails

      // Create thumbnail
      var img = document.createElement('img');
      img.src = thumbnailSrc;
      img.className = 'video-thumbnail';

      // Create play button
      var playButton = document.createElement('button');
      playButton.className = 'play-button';

      // When play button is clicked
      playButton.addEventListener('click', function() {
          // Replace the thumbnail and play button with the video
          container.innerHTML = '';
          container.appendChild(video);
          video.play();
      });

      // Clear the container and add the thumbnail and play button
      container.innerHTML = '';
      container.appendChild(img);
      container.appendChild(playButton);
  });
});


//dynamically adjusts the height of the colorful forms in the header's background & the position of the settings-window to be under the header
document.addEventListener('DOMContentLoaded', () => {

  // Get element for burgerContent to save its initial fontSize
  const burgerContent = document.querySelector('.main-nav_content__mobile');
  var burgerContentFontS = window.getComputedStyle(burgerContent).fontSize;

  // Function to adjust header heights
  function adjustHeaderHeights() {
      // Get the header and form elements
      const mdHeader = document.querySelector('.md-header');
      const headerForm1 = document.querySelector('#header-form_1');
      const headerForm2 = document.querySelector('#header-form_2');
      const headerForm3 = document.querySelector('#header-form_3');
      
      // Check if elements exist
      if (mdHeader && headerForm1 && headerForm2 && headerForm3) {
          // Read the height of the .md-header element
          const headerHeight = mdHeader.offsetHeight;

          // Adjust the heights of the form elements
          headerForm1.style.height = `${headerHeight * 0.7}px`;
          headerForm1.style.width = `${headerHeight * 0.7}px`;
          headerForm2.style.height = `${headerHeight * 0.3}px`;
          headerForm3.style.height = `${headerHeight}px`;

          if (window.innerWidth <= 1219) {
            headerForm1.style.height = `${headerHeight * 1}px`;
            headerForm1.style.width = `${headerHeight * 1}px`;
          }
      }

      // Get the settingsWrapper and banner elements
      const settingsWrapper = document.querySelector('.header-settings-wrapper')
      const banner = document.querySelector('.md-banner');

      // Check if elements exist
      if (settingsWrapper) {

          // Read the height of the .md-header element and banner element
          const headerHeight = mdHeader.offsetHeight;
          const bannerHeight = banner.offsetHeight;
          let top = headerHeight - 1;

          // if banner is there, adds the heights together
          if (settingsWrapper && banner) {
              top = headerHeight + bannerHeight - 1;
          }

          // If user has scrolled far enough, that the banner isn't visible anymore, removes bannerHeight
          if (window.scrollY >= bannerHeight) {
              top = headerHeight - 1;
          }

          // Adjust the top-property of the settingsWrapper element
          settingsWrapper.style.top = `${top}px`; 

          // Adjust the margin-property of the md-content element
          if (mdHeader && !window.matchMedia("(max-width: 768px) and (orientation: portrait)").matches) {
            const titleImage = document.querySelector('.title-image');
            if (!titleImage) {
              const content = document.querySelector('.md-content');
              content.style.marginTop = `${headerHeight}px`;
            }
          }
      }


      const burgerMenu = document.querySelector('.main-nav__mobile');

      // make sure the burgerMenu is correctly positioned at the top below header (and banner)
      if (window.getComputedStyle(burgerMenu).display !== 'none') {

        // Read the height of the .md-header element and banner element
        const headerHeight = mdHeader.offsetHeight;
        const bannerHeight = banner.offsetHeight;
        let placeholder = document.querySelector('.main-nav_content-placeholder');
      
        // distribute burgerMenu content evenly

        if (placeholder) {
          if (banner) {
            placeholder.style.minHeight = headerHeight + bannerHeight + 'px';
          };
          
          if (window.scrollY >= bannerHeight)  {
            placeholder.style.minHeight = headerHeight + 'px';
          };
        };

        // helper function to get the sum of height of all children of burgerContent
        function getTotalHeightOfChildren(burgerContent) {
          // Get all direct child elements of the parent element
          const children = burgerContent.children;

          // Initialize a variable to hold the total height
          let totalHeight = 0;

          // Loop through each child element
          for (let i = 0; i < children.length; i++) {
            // Add the height of the current child element to the total height
            totalHeight += children[i].offsetHeight;
          }

          // Return the total height
          return totalHeight;
        }

        if (burgerContent) {

          var contentGap;
          var burgerContentHeight;
          var contentHeight;

          function calcContentGap() {
            burgerContentHeight = burgerContent.offsetHeight;
            contentHeight = getTotalHeightOfChildren(burgerContent);
            contentGap = ((burgerContentHeight - contentHeight) / 5) - 10;
          }

          calcContentGap();

          // Function to decrease font size by a specific value
          function decreaseFontSize(element, decrement) {
            // Get the current font size
            let currentFontSize = window.getComputedStyle(element).fontSize;

            // Parse the current font size and remove the 'px' unit
            let currentSize = parseFloat(currentFontSize);

            // Decrease the font size by the decrement
            let newSize = currentSize - decrement;

            // Set the new font size with the 'px' unit
            element.style.fontSize = newSize + 'px';
          }

          // If the gap is too narrow it means the text is likely too big for the display forcing the menu to overflow
          // So if the gap is too narrow, we decrease the font-size, until it isn't.
          if (contentGap < 10 && parseFloat(window.getComputedStyle(burgerContent).fontSize) > 9) {
            do {
              decreaseFontSize(burgerContent, 2);
              calcContentGap();
            }
            while (contentGap < 10 && parseFloat(window.getComputedStyle(burgerContent).fontSize) > 9);
          }
          
          if (contentGap > 10 && burgerContentHeight > contentHeight) {
            burgerContent.style.gap = `${contentGap}px`;
          } else {
            burgerContent.style.gap = `5px`;
          }
        }
     }
  }

  function burgerLogoAdjust() {
    // Select all elements with the class 'main-nav__link-logo__mobile'
    const burgerLogos = document.querySelectorAll('.main-nav__link-logo__mobile');
  
    // Function to calculate the maximum height after images are loaded
    function calculateMaxHeight() {
      burgerLogos.forEach((logo) => {
        // Initialize a variable to hold the maximum height
        let logoHeight = 0;
  
        // Get all children (img elements) of the current logo element
        let logosChildren = logo.children;
  
        // Loop through each child element (images in this case) to find the maximum height
        for (let i = 0; i < logosChildren.length; i++) {
          // Get the height of the current child element
          const childHeight = logosChildren[i].offsetHeight;
    
          // Update logoHeight if the current child's height is greater
          if (childHeight > logoHeight) {
            logoHeight = childHeight;
          }
        }
  
        // Set the height of the current logo to the maximum child height
        if (logoHeight > 0) {
          logo.style.height = logoHeight + 'px';
        } 
      });
    }
  
    // Wait until all images within the burgerLogos are fully loaded
    let imagesLoaded = 0;
    const images = document.querySelectorAll('.main-nav__link-logo__mobile img');
  
    images.forEach((img) => {
      if (img.complete) {
        // If the image is already loaded
        imagesLoaded++;
      } else {
        // Add a load event listener for the images that are not yet loaded
        img.addEventListener('load', () => {
          imagesLoaded++;
          if (imagesLoaded === images.length) {
            calculateMaxHeight();
          }
        });
      }
    });
  
    // Check if all images were already loaded when the script runs
    if (imagesLoaded === images.length) {
      calculateMaxHeight();
    }
  }

  // This makes sure the fontSize of the burgerMenu resets when the window is resized
  function burgerResize() {
    // Set the opacity to 0 for a smoother transition
    burgerContent.style.opacity = '0';
  
    // Change the font size
    burgerContent.style.fontSize = burgerContentFontS;
  
    // After a tiny delay, set the opacity back to 1
    setTimeout(function() {
      burgerContent.style.opacity = '1';
    }, 400); // Delay in milliseconds
  }

  window.addEventListener('resize', burgerResize(), burgerLogoAdjust());
  
  function adjustHeaderTop() {
    const mdHeader = document.querySelector('.md-header');
    const headerHeight = mdHeader.offsetHeight;
    const banner = document.querySelector('.md-banner');
    const bannerHeight = banner.offsetHeight;
    const titleImage = document.querySelector('.title-image')
        mdHeader.style.top = '0vh';
        if (window.scrollY >= bannerHeight) {
          mdHeader.style.marginTop = `0px`;
        } else {
          mdHeader.style.marginTop = `${bannerHeight}px`;
        }
        mdHeader.style.position = 'fixed';
        if (titleImage) {
          titleImage.style.marginTop = `${headerHeight}px`;
        }
  }

  // Adjust heights on page load
  adjustHeaderHeights();
  adjustHeaderTop();

  // Adjust heights on scroll
  window.addEventListener('scroll', adjustHeaderHeights);
  window.addEventListener('scroll', adjustHeaderTop);
  window.addEventListener('resize', adjustHeaderTop);

  // Adjust heights on window resize with a tiny delay for better usability
  let resizeTimeout;
  window.addEventListener('resize', () => {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(adjustHeaderHeights, 100); // 100 ms delay
  });


  //handles the burger-menu for mobile navigation.
  var burgerIsOpen = 0;

  function handleMobileNavMenu() {
      const burgerLine1 = document.querySelector('.main-nav_mobile_button div:nth-child(1)');
      const burgerLine2 = document.querySelector('.main-nav_mobile_button div:nth-child(2)');
      const burgerLine3 = document.querySelector('.main-nav_mobile_button div:nth-child(3)');
      const burgerMenu = document.querySelector('.main-nav__mobile');
      const banner = document.querySelector('.md-banner');

      if (burgerIsOpen === 0) {
          // closes the settings-menu if open
          if (!settings.classList.contains('settings-close')) {
            closeSettingsMenu();
          }
          // Open the mobile menu
          burgerIsOpen = 1;
          // animate the button
          burgerLine1.style.transform = "scale(1.2) rotate(45deg) translateX(-50%) translateY(-50%)";
          burgerLine2.style.transform = "translateX(-20vw)";
          burgerLine3.style.transform = "scale(1.2) rotate(-45deg) translateX(-50%) translateY(-50%)";
          // display the menu
          burgerMenu.classList.remove("main-nav__mobile-close-burger");
          burgerMenu.classList.add("main-nav__mobile-open-burger");
          banner.classList.add('hidden');
          adjustHeaderHeights();
          adjustHeaderTop();
      } else {
          // Close the mobile menu
          burgerIsOpen = 0;
          // animate the button
          burgerLine1.style.transform = "scale(1) rotate(0) translateX(-50%) translateY(calc(-50% - 0.65em))";
          burgerLine2.style.transform = "rotate(0) translateX(-50%) translateY(-50%)";
          burgerLine3.style.transform = "scale(1) rotate(0) translateX(-50%) translateY(calc(-50% + 0.65em))";
          // hide the menu
          burgerMenu.classList.add("main-nav__mobile-close-burger");
          burgerMenu.classList.remove("main-nav__mobile-open-burger");
          banner.classList.remove('hidden');
          adjustHeaderHeights();
          adjustHeaderTop();
      }
  }

  const burgerButton = document.querySelector('.main-nav_mobile_button');
  burgerButton.addEventListener('click', handleMobileNavMenu);

  // Open Settings

  const settingsWrapper = document.querySelector('.header-settings-wrapper');
  // const overlay = document.getElementById('settings');
  const settings = document.getElementById('settings-content')
  const openOverlayButton = document.getElementById('openSettings');
  const closeOverlayButton = document.getElementById('closeSettings');
  const line = document.querySelectorAll('div#settings-line, div.settings-line__small');

  function openSettingsMenu() {
    //closes burgerMenu if open
    if (burgerIsOpen === 1) {
      handleMobileNavMenu();
    };
    openOverlayButton.classList.add('openS');
    // overlay.classList.remove('settings-hidden', 'settings-close');
    settingsWrapper.classList.add('settings-open');
    settings.style.display = "flex";
    for (const element of line) {
      element.style.display = "flex";
    };
  }

  function closeSettingsMenu() {
    openOverlayButton.classList.remove('openS');
    settingsWrapper.classList.remove('settings-open');
    // overlay.classList.add('settings-hidden');
    for (const element of line) {
      element.style.display = "none";
    };
  }

  // Function to open the overlay
  openOverlayButton.addEventListener('click', () => {
    const hasAnimated = sessionStorage.getItem('hasAnimated');

    if (hasAnimated)
      if (!settingsWrapper.classList.contains('settings-open')) {
        openSettingsMenu();
      }
      else {
        closeSettingsMenu();
      }
  });

  // Function to close the overlay
  closeOverlayButton.addEventListener('click', () => {
    closeSettingsMenu();
  });

    // settings button
    const hasAnimated = sessionStorage.getItem('hasAnimated');

    if (!hasAnimated) {
      const element = document.getElementById('openSettings');
  
      if (element) {
        // Ensure any previous transform styles are reset before applying the animation
        element.style.transform = 'scale(0)'; 
  
        // Trigger a reflow/repaint to ensure that the `transform` change is rendered
        element.offsetWidth; // Trigger reflow
  
        // Add the class to start the animation
        element.classList.add('animate');
  
        // Set sessionStorage to prevent future animations during this session
        sessionStorage.setItem('hasAnimated', 'true');
      }
    }
  
    var wasReset = 0;
  
    if (hasAnimated && wasReset == 0) {
     const element = document.getElementById('openSettings');
     if (element) {
      element.style.transform = "scale(1) rotate(0)";
      wasReset += 1;
     }
    }
});