// Navigation functionality
const navToggle = document.querySelector('.nav-toggle');
const headerLeft = document.querySelector('.header-left');
const headerRight = document.querySelector('.header-right');
const navClose = document.querySelector('.nav-close');
const fullscreenNav = document.querySelector('.fullscreen-nav');
const body = document.body;
const header = document.querySelector('.header');

// Initialize AOS (Animate On Scroll)
document.addEventListener('DOMContentLoaded', function() {
  AOS.init({
    easing: 'ease-in-out'
  });
});

// Handle menu items with children
document.querySelectorAll('.nav-parent.has-children > a.parent').forEach(parentLink => {
  parentLink.addEventListener('click', (e) => {
    e.preventDefault();
    e.stopPropagation();
    
    // Get the child identifier from the clicked parent
    const childId = parentLink.getAttribute('data-child');
    
    // If the clicked parent is already active, deactivate it
    if (parentLink.classList.contains('active')) {
      parentLink.classList.remove('active');
      const targetChildren = document.querySelector(`.nav-children[data-parent="${childId}"]`);
      if (targetChildren) {
        targetChildren.classList.remove('active');
      }
      return;
    }
    
    // Hide all nav-children first
    document.querySelectorAll('.nav-children').forEach(navChild => {
      navChild.classList.remove('active');
    });
    
    // Remove active class from all parent links
    document.querySelectorAll('.nav-parent.has-children > a.parent').forEach(link => {
      link.classList.remove('active');
    });
    
    // Show the corresponding nav-children and activate the parent link
    const targetChildren = document.querySelector(`.nav-children[data-parent="${childId}"]`);
    if (targetChildren) {
      targetChildren.classList.add('active');
      parentLink.classList.add('active');
    }
  });
});

// Close child menus when clicking outside
document.addEventListener('click', (e) => {
  // Don't close if clicking inside the fullscreen nav or on the header
  if (e.target.closest('.fullscreen-nav') || e.target.closest('.header')) {
    return;
  }
  
  if (!e.target.closest('.nav-parent.has-children')) {
    document.querySelectorAll('.nav-children').forEach(navChild => {
      navChild.classList.remove('active');
    });
    document.querySelectorAll('.nav-parent.has-children > a.parent').forEach(link => {
      link.classList.remove('active');
    });
  }
});

function openServicesIfMobile() {
  const isMobile = window.innerWidth <= 767;

  if (isMobile) {
    const servicesLink = document.querySelector('.nav-parent.has-children > a.parent[data-child="services"]');

    if (servicesLink && !servicesLink.classList.contains('active')) {
      servicesLink.click();
    }
  }
}

function toggleNav() {
  const isOpening = !fullscreenNav.classList.contains('active');
  
  if (isOpening) {
    // Opening menu
    fullscreenNav.classList.add('active');
    headerLeft.classList.add('active');
    navClose.classList.add('active');
    body.classList.add('menu-active');

    setTimeout(openServicesIfMobile, 10);
  } else {
    // Closing menu
    fullscreenNav.classList.remove('active');
    headerLeft.classList.remove('active');
    navClose.classList.remove('active');
    body.classList.remove('menu-active');
  }
}

if (navToggle) {
  navToggle.addEventListener('click', toggleNav);
}

if (navClose) {
  navClose.addEventListener('click', toggleNav);
}

// Close nav when clicking a link
document.querySelectorAll('.fullscreen-nav a:not(.parent)').forEach(link => {
  link.addEventListener('click', () => {
    // Use toggleNav() to properly handle all state changes including button states
    if (fullscreenNav.classList.contains('active')) {
      toggleNav();
    }
  });
});

// Close nav when pressing Escape key
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape' && fullscreenNav.classList.contains('active')) {
    toggleNav();
  }
});

// Smooth scrolling for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();
    const target = document.querySelector(this.getAttribute('href'));
    if (target) {
      const headerHeight = document.querySelector('.header').offsetHeight;
      const targetPosition = target.offsetTop - headerHeight;
      
      window.scrollTo({
        top: targetPosition,
        behavior: 'smooth'
      });
    }
  });
});

// Header scroll effect
let lastScrollTop = 0;
const scrollThreshold = 50;
const stickyThreshold = 100;

// Function to check scroll position and apply scrolled class
function checkScrollPosition() {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  
  if (scrollTop > scrollThreshold) {
    body.classList.add('scrolled');
  } else {
    body.classList.remove('scrolled');
  }
}

// Function to handle sticky header
function handleStickyHeader() {
  const topHeader = document.querySelector('.top-header');
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  
  if (!topHeader) {
    return;
  }
  
  // Add/remove sticky class based on scroll position
  if (scrollTop > stickyThreshold) {
    if (!topHeader.classList.contains('sticky')) {
      topHeader.classList.add('sticky');
    }
  } else {
    if (topHeader.classList.contains('sticky')) {
      topHeader.classList.remove('sticky');
    }
  }
  
  // Mobile scroll detection for header visibility
  if (window.innerWidth <= 767 && !body.classList.contains('menu-active')) {
    if (scrollTop > lastScrollTop && scrollTop > 100) {
      // Scrolling down - hide header
      topHeader.classList.add('header-hidden');
    } else if (scrollTop < lastScrollTop) {
      // Scrolling up - show header
      topHeader.classList.remove('header-hidden');
    }
  }
  
  lastScrollTop = scrollTop;
}

window.addEventListener('scroll', () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  
  // Add scrolled class when page is scrolled
  if (scrollTop > scrollThreshold) {
    body.classList.add('scrolled');
  } else {
    body.classList.remove('scrolled');
  }
  
  // Handle sticky header behavior
  handleStickyHeader();
});

// Check scroll position on page load and apply appropriate class
document.addEventListener('DOMContentLoaded', () => {
  checkScrollPosition();
  handleStickyHeader();
  

});

function initSmoothScrolling() {
  // Prevent multiple initializations
  if (window.__lepasSmoothInit) return;
  window.__lepasSmoothInit = true;

  // Register GSAP plugins
  gsap.registerPlugin(ScrollTrigger, ScrollToPlugin);
  
  // Leopard section setup (desktop stepped phases vs mobile auto-reveal)
  const leopardSection = document.getElementById('leopard-section');
  const isDesktop = window.innerWidth > 767;
  const holdAfterPhase2 = 500; // ms micro-hold to avoid overshoot but feel instant
  let leopardPhase = 0; // 0=image only, 1=overlay dark, 2=content visible
  let leopardCooldownUntil = 0; // debounce to avoid skipping phases on strong scrolls
  let leopardPhase2EnteredAt = 0; // timestamp of entering phase 2
  let leopardPhase2Armed = false; // require one extra wheel tick before leaving phase 2
  let leopardExitTicksNeeded = 0; // number of downward wheels required to leave phase 2
  let ignoreWheelUntil = 0; // ignore wheel events while snapping/locking
  let isScrolling = false; // GSAP snap in progress

  // Helper to toggle leopard phases using your existing classes
  function setLeopardPhase(phase) {
    if (!leopardSection) return;
    leopardPhase = Math.max(0, Math.min(2, phase));
    leopardSection.classList.toggle('overlay-dark', leopardPhase >= 1);
    leopardSection.classList.toggle('content-visible', leopardPhase >= 2);
    if (leopardPhase === 2) {
      leopardPhase2EnteredAt = performance.now();
      leopardPhase2Armed = false; // no extra tick required
      leopardExitTicksNeeded = 0; // proceed on next scroll
      ignoreWheelUntil = performance.now() + 450; // absorb the same burst
    }
  }

  if (leopardSection) {
    // Mobile: reveal content automatically when Leopard comes into view
    if (!isDesktop) {
      const content = leopardSection.querySelector('.leopard__content');
      const overlay = leopardSection.querySelector('.leopard-overlay');
      const carImage = leopardSection.querySelector('.leopard-background');
      let leopardContentTimer = null;
      let hasShownContent = false;

      const onScroll = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const sectionTop = leopardSection.offsetTop;
        const sectionHeight = leopardSection.offsetHeight;
        const windowHeight = window.innerHeight;
        const sectionProgress = (scrollTop + windowHeight - sectionTop) / (windowHeight + sectionHeight * 0.5);
        if (sectionProgress > 0.3) {
          if (leopardContentTimer) clearTimeout(leopardContentTimer);
          const leopardDelay = (window.innerWidth <= 767) ? 10 : 150;
          if (!hasShownContent) {
            leopardContentTimer = setTimeout(() => {
              leopardSection.classList.add('scrolled');
              if (carImage) carImage.classList.add('show-content');
              if (content) content.classList.add('show-content');
              if (overlay) overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.6)';
              hasShownContent = true;
            }, leopardDelay);
          }
        } else {
          if (leopardContentTimer) clearTimeout(leopardContentTimer);
          if (hasShownContent) {
            hasShownContent = false;
            leopardSection.classList.remove('scrolled');
            if (carImage) carImage.classList.remove('show-content');
            if (content) content.classList.remove('show-content');
            if (overlay) overlay.style.backgroundColor = 'rgba(0, 0, 0, 0)';
          }
        }
      };

      window.addEventListener('scroll', onScroll, { passive: true });
      onScroll();

      window.showLeopardContent = function() {
        const content = leopardSection.querySelector('.leopard__content');
        const overlay = leopardSection.querySelector('.leopard-overlay');
        const carImage = leopardSection.querySelector('.leopard-background');
        leopardSection.classList.add('scrolled');
        if (carImage) carImage.classList.add('show-content');
        if (content) content.classList.add('show-content');
        if (overlay) overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.6)';
      };
      window.hideLeopardContent = function() {
        const content = leopardSection.querySelector('.leopard__content');
        const overlay = leopardSection.querySelector('.leopard-overlay');
        const carImage = leopardSection.querySelector('.leopard-background');
        leopardSection.classList.remove('scrolled');
        if (carImage) carImage.classList.remove('show-content');
        if (content) content.classList.remove('show-content');
        if (overlay) overlay.style.backgroundColor = 'rgba(0, 0, 0, 0)';
      };
    }
  }

  // GSAP snap helper between full sections
  function scrollToSection(sectionIndex, direction = 0) {
    if (sectionIndex < 0 || sectionIndex >= sections.length) return;

    // If navigating into Leopard on desktop, start at phase 2 when coming from Three Model, or 0 when coming from Hero
    if (isDesktop && sectionIndex === 1) {
      if (direction < 0) {
        // from Three Model going up → start at phase 2
        setLeopardPhase(2);
        // absorb momentum briefly; no extra tick
        ignoreWheelUntil = performance.now() + 450;
        leopardExitTicksNeeded = 0;
      } else if (direction > 0) {
        // from Hero going down → start at phase 0
        setLeopardPhase(0);
        // require a fresh wheel after enter to show content
        ignoreWheelUntil = performance.now() + 250;
        requireFreshWheelAfterEnter = true;
      }
    }

    isScrolling = true;
    // swallow momentum during snap between sections
    ignoreWheelUntil = performance.now() + 550;
    const sectionPositions = getSectionPositions();
    gsap.to("html, body", {
      scrollTo: { y: sectionPositions[sectionIndex], offsetY: 0 },
      duration: 0.8,
      ease: "power2.out",
      onComplete: () => {
        setTimeout(() => {
          isScrolling = false;
        }, 300);
      }
    });
  }

  // Track current section & util
  let currentSection = 0;
  // Global wheel throttle to smooth out rapid event bursts
  let lastWheelAt = 0;
  const WHEEL_THROTTLE_MS = 180;
  
  // Get section positions
  const heroSection = document.getElementById('hero');
  const threeModelSection = document.querySelector('.three-model-section');
  const sections = [heroSection, leopardSection, threeModelSection];
  const getSectionPositions = () => sections.map(section => section ? section.offsetTop : 0);

  // Touch scroll guard on mobile: prevent accidental jump when momentum scroll happens
  if (!isDesktop && leopardSection) {
    let touchActive = false;
    leopardSection.addEventListener('touchstart', () => { touchActive = true; }, { passive: true });
    leopardSection.addEventListener('touchend', () => { touchActive = false; }, { passive: true });
  }
  
  function getCurrentSection() {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const totalHeight = windowHeight * 3;
    const sectionPositions = getSectionPositions();
    if (scrollTop > totalHeight) return -1;
    for (let i = sections.length - 1; i >= 0; i--) {
      if (scrollTop >= sectionPositions[i] - windowHeight / 2) return i;
    }
    return 0;
  }

  // Wheel handler (desktop): 1 scroll = 1 step, momentum absorbed
  window.addEventListener('wheel', (e) => {
    if (!isDesktop) return; // disable wheel-driven snapping on mobile/tablet
    const nowGlobal = performance.now();
    if (nowGlobal < ignoreWheelUntil) { e.preventDefault(); return; }
    if (isScrolling) { e.preventDefault(); return; }

    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const totalHeight = windowHeight * 3;

    // Re-evaluate current section using fresh positions each wheel
    currentSection = getCurrentSection();

    // Desktop-only: step through Leopard phases before changing sections
    if (isDesktop && leopardSection && currentSection === 1) {
      // Ensure we are within the visual bounds of the leopard section before stepping
      const sectionPositions = getSectionPositions();
      const leopardTop = sectionPositions[1];
      const leopardBottom = leopardTop + leopardSection.offsetHeight;
      const withinLeopard = (scrollTop + 1 >= leopardTop && scrollTop + windowHeight - 1 <= leopardBottom + windowHeight);

      const now = performance.now();
      const cooldown = 350; // ms

      if (withinLeopard) {
        // Momentum guard during phase changes
        if (now < leopardCooldownUntil) { e.preventDefault(); return; }

        // DOWN within Leopard: 0/1 -> 2 (show content), lock briefly
        if (e.deltaY > 0 && leopardPhase < 2) {
          e.preventDefault();
          setLeopardPhase(2);

          // Snap to exact top of leopard to avoid drift
          const sectionPositionsSnap = getSectionPositions();
          const leopardTopSnap = sectionPositionsSnap[1];
          gsap.to("html, body", { scrollTo: { y: leopardTopSnap, offsetY: 0 }, duration: 0.25, ease: "power2.out" });

          // Stronger momentum guard
          ignoreWheelUntil = now + 450;
          leopardCooldownUntil = now + cooldown;
          return;
        }

        // UP within Leopard: collapse back to phase 0
        if (e.deltaY < 0 && leopardPhase > 0) {
          e.preventDefault();
          setLeopardPhase(0);
          leopardCooldownUntil = now + cooldown;
          return;
        }
      }
      // If not within bounds or at phase limits, fall through to section scrolling
    }

    // Only handle scroll if we're within the controlled sections (0, 1, 2)
    if (currentSection >= 0 && currentSection <= 2) {
      if ((e.deltaY > 0 && currentSection < 2) || (e.deltaY < 0 && currentSection > 0)) {
        // Leaving Leopard → Three Model: allow next step after a short hold, but no double-tick
        if (isDesktop && currentSection === 1 && e.deltaY > 0) {
          const now = performance.now();
          if (leopardPhase === 2) {
            // Keep position stable while in phase 2 (no repeated re-snap to reduce jitter)
            if (now - leopardPhase2EnteredAt < holdAfterPhase2) {
              e.preventDefault();
              return; // hold a moment to let user read before moving on
            }
          }
        }

        e.preventDefault();
        const direction = e.deltaY > 0 ? 1 : -1;
        const targetSection = currentSection + direction;
        scrollToSection(targetSection, direction);
      }
    }
  }, { passive: false });

  // Resize: refresh cached positions for snapping accuracy
  window.addEventListener('resize', () => {
    ScrollTrigger.refresh(true);
  });

  // Expose helpers (optional)
  window.showLeopardContent = function() {
    const content = leopardSection ? leopardSection.querySelector('.leopard__content') : null;
    const overlay = leopardSection ? leopardSection.querySelector('.leopard-overlay') : null;
    const carImage = leopardSection ? leopardSection.querySelector('.leopard-background') : null;
    if (leopardSection) {
      leopardSection.classList.add('scrolled');
      if (carImage) carImage.classList.add('show-content');
      if (content) content.classList.add('show-content');
      if (overlay) overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.6)';
    }
  };
  window.hideLeopardContent = function() {
    const content = leopardSection ? leopardSection.querySelector('.leopard__content') : null;
    const overlay = leopardSection ? leopardSection.querySelector('.leopard-overlay') : null;
    const carImage = leopardSection ? leopardSection.querySelector('.leopard-background') : null;
    if (leopardSection) {
      leopardSection.classList.remove('scrolled');
      if (carImage) carImage.classList.remove('show-content');
      if (content) content.classList.remove('show-content');
      if (overlay) overlay.style.backgroundColor = 'rgba(0, 0, 0, 0)';
    }
  };
}


// Video control functionality
function initVideoControl() {
  const videoSection = document.getElementById('hero');
  const video = videoSection ? videoSection.querySelector('video') : null;
  
  if (!video) {
    return;
  }
  
  // Function to check if video section is visible
  function isVideoSectionVisible() {
    if (!videoSection) return false;
    
    const rect = videoSection.getBoundingClientRect();
    const windowHeight = window.innerHeight;
    
    // Check if section is at least 50% visible
    return rect.top < windowHeight * 0.5 && rect.bottom > windowHeight * 0.5;
  }
  
  // Function to control video playback
  function controlVideo() {
    if (isVideoSectionVisible()) {
      if (video.paused) {
        video.play().catch(e => console.log('Video play prevented:', e));
      }
    } else {
      if (!video.paused) {
        video.pause();
      }
    }
  }
  
  // Add scroll listener for video control
  window.addEventListener('scroll', controlVideo);
  
  // Initial check
  controlVideo();
  
  // Add manual control functions for testing
  window.playVideo = function() {
    if (video) {
      video.play().catch(e => console.log('Manual video play prevented:', e));
    }
  };
  
  window.pauseVideo = function() {
    if (video) {
      video.pause();
    }
  };
}

// Three Model Section Video Control
function initThreeModelVideoControl() {
  const modelCards = document.querySelectorAll('.three-model-card');
  let currentlyPlayingVideo = null;
  
  if (modelCards.length === 0) {
    return;
  }
  
  // Function to pause all videos except the specified one
  function pauseAllVideosExcept(exceptVideo) {
    modelCards.forEach(card => {
      const video = card.querySelector('video');
      if (video && video !== exceptVideo) {
        video.pause();
        video.currentTime = 0; // Reset to beginning
      }
    });
  }
  
  modelCards.forEach((card, index) => {
    const video = card.querySelector('video');
    if (!video) {
      return;
    }
    
    // Mouse enter - play video
    card.addEventListener('mouseenter', () => {
      // Pause all other videos first
      pauseAllVideosExcept(video);
      
      // Play current video
      video.currentTime = 0; // Reset to beginning
      video.play().catch(e => console.log('Video play prevented:', e));
      currentlyPlayingVideo = video;
    });
    
    // Mouse leave - pause video
    card.addEventListener('mouseleave', () => {
      if (video === currentlyPlayingVideo) {
        video.pause();
        currentlyPlayingVideo = null;
      }
    });
  });
  
  // Add manual control functions for testing
  window.playModelVideo = function(modelClass) {
    const card = document.querySelector(`.${modelClass}`);
    const video = card ? card.querySelector('video') : null;
    if (video) {
      pauseAllVideosExcept(video);
      video.currentTime = 0;
      video.play().catch(e => console.log('Manual video play prevented:', e));
    }
  };
  
  window.pauseAllModelVideos = function() {
    const videos = document.querySelectorAll('.three-model-card video');
    videos.forEach(video => {
      video.pause();
      video.currentTime = 0;
    });
    currentlyPlayingVideo = null;
  };
  
  // Debug function to show all videos
  window.showAllVideos = function() {
    const videos = document.querySelectorAll('.three-model-card video');
    videos.forEach((video, index) => {
      // Debug info available if needed
    });
  };
}

// Initialize smooth scrolling when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  initSmoothScrolling();
  initVideoControl();
  initThreeModelVideoControl();
  

});



// CTA Button interactions
const ctaButtons = document.querySelectorAll('.cta-button');
if (ctaButtons.length > 0) {
  ctaButtons.forEach(button => {
    button.addEventListener('click', function(e) {
      // Add ripple effect
      const ripple = document.createElement('span');
      const rect = this.getBoundingClientRect();
      const size = Math.max(rect.width, rect.height);
      const x = e.clientX - rect.left - size / 2;
      const y = e.clientY - rect.top - size / 2;
      
      ripple.style.width = ripple.style.height = size + 'px';
      ripple.style.left = x + 'px';
      ripple.style.top = y + 'px';
      ripple.classList.add('ripple');
      
      this.appendChild(ripple);
      
      setTimeout(() => {
        ripple.remove();
      }, 600);
      
      // Handle button actions (placeholder)
      console.log('CTA Button clicked:', this.textContent);
    });
  });
}

// Add ripple effect styles
const style = document.createElement('style');
style.textContent = `
  .cta-button {
    position: relative;
    overflow: hidden;
  }
  
  .ripple {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.3);
    transform: scale(0);
    animation: ripple 0.6s ease-out;
    pointer-events: none;
  }
  
  @keyframes ripple {
    to {
      transform: scale(2);
      opacity: 0;
    }
  }
`;
document.head.appendChild(style);


// Banner Slideshow
function initBannerSlideshow() {
  const slides = document.querySelectorAll('.banner#hero .banner-slide');
  if (slides.length === 0) return; // Exit if no slides found
  
  let currentSlide = 0;
  const slideInterval = 4000; // Change slide every 4 seconds for image slides
  let slideTimer = null;

  function nextSlide() {
    // Pause video in current slide if it exists
    const currentVideo = slides[currentSlide].querySelector('video');
    if (currentVideo) {
      currentVideo.pause();
    }
    
    // Remove active class from current slide
    slides[currentSlide].classList.remove('active');
    
    // Update current slide index
    currentSlide = (currentSlide + 1) % slides.length;
    
    // Add active class to new current slide
    slides[currentSlide].classList.add('active');
    
    // Play video in new slide if it exists
    const newVideo = slides[currentSlide].querySelector('video');
    if (newVideo) {
      newVideo.currentTime = 0; // Reset to beginning
      newVideo.play().catch(e => console.log('Video autoplay prevented:', e));
      
      // Wait for video to finish before moving to next slide immediately
      newVideo.addEventListener('ended', function onVideoEnd() {
        newVideo.removeEventListener('ended', onVideoEnd); // Remove listener to avoid duplicates
        nextSlide(); // Immediately go to next slide
      }, { once: true });
    } else {
      // If it's an image slide, set up timer for next slide
      setupNextSlideTimer();
    }
  }

  function setupNextSlideTimer() {
    // Clear any existing timer
    if (slideTimer) {
      clearTimeout(slideTimer);
    }
    
    // Set timer for next slide
    slideTimer = setTimeout(nextSlide, slideInterval);
  }

  // Set initial state
  slides[0].classList.add('active');
  
  // Play video in first slide if it's a video slide
  const firstVideo = slides[0].querySelector('video');
  if (firstVideo) {
    firstVideo.play().catch(e => console.log('Video autoplay prevented:', e));
    
    // Wait for video to finish before moving to next slide immediately
    firstVideo.addEventListener('ended', function onFirstVideoEnd() {
      firstVideo.removeEventListener('ended', onFirstVideoEnd); // Remove listener to avoid duplicates
      nextSlide(); // Immediately go to next slide
    }, { once: true });
  } else {
    // If first slide is an image, set up timer for next slide
    setupNextSlideTimer();
  }

  // Only start the slideshow if there's more than one slide
  if (slides.length > 1) {
    // Initial timer setup is handled above based on first slide type
  }
}



// Initialize banner slideshow when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  initBannerSlideshow();
  initVideoModal();
  wrapLettersInSpans();
  initSmoothScrolling();
  initVideoControl();
});








// Mobile Events Carousel
function initMobileEventsCarousel() {
  const mobileCarousel = document.querySelector('.mobile-events-carousel');
  if (!mobileCarousel) return;

  const track = mobileCarousel.querySelector('.carousel-track');
  const slides = mobileCarousel.querySelectorAll('.carousel-slide');
  const prevBtn = mobileCarousel.querySelector('.nav-btn.prev');
  const nextBtn = mobileCarousel.querySelector('.nav-btn.next');
  const dots = mobileCarousel.querySelectorAll('.carousel-dot');

  let currentSlide = 0;
  const totalSlides = slides.length;

  function updateCarousel() {
    const slideWidth = 100; // 100% width
    track.style.transform = `translateX(-${currentSlide * slideWidth}%)`;
    
    // Update dots
    dots.forEach((dot, index) => {
      dot.classList.toggle('active', index === currentSlide);
    });
  }

  function nextSlide() {
    currentSlide = (currentSlide + 1) % totalSlides;
    updateCarousel();
  }

  function prevSlide() {
    currentSlide = (currentSlide - 1 + totalSlides) % totalSlides;
    updateCarousel();
  }

  function goToSlide(index) {
    currentSlide = index;
    updateCarousel();
  }

  // Event listeners
  if (nextBtn) {
    nextBtn.addEventListener('click', nextSlide);
  }

  if (prevBtn) {
    prevBtn.addEventListener('click', prevSlide);
  }

  // Dot navigation
  dots.forEach((dot, index) => {
    dot.addEventListener('click', () => goToSlide(index));
  });

  // Touch/swipe support
  let startX = 0;
  let endX = 0;

  track.addEventListener('touchstart', (e) => {
    startX = e.touches[0].clientX;
  });

  track.addEventListener('touchend', (e) => {
    endX = e.changedTouches[0].clientX;
    const diff = startX - endX;
    
    if (Math.abs(diff) > 50) { // Minimum swipe distance
      if (diff > 0) {
        nextSlide(); // Swipe left
      } else {
        prevSlide(); // Swipe right
      }
    }
  });

  // Autoplay
  let mobileAutoplayInterval = setInterval(nextSlide, 4000);

  // Pause autoplay on hover/touch
  mobileCarousel.addEventListener('mouseenter', () => {
    clearInterval(mobileAutoplayInterval);
  });

  mobileCarousel.addEventListener('mouseleave', () => {
    mobileAutoplayInterval = setInterval(nextSlide, 4000);
  });

  // Initialize
  updateCarousel();
}

// Initialize mobile carousel when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  initMobileEventsCarousel();
});

// Mobile Footer Accordion
function initMobileFooterAccordion() {
  const accordionHeaders = document.querySelectorAll('.footer-section-header');
  
  accordionHeaders.forEach(header => {
    header.addEventListener('click', () => {
      const content = header.nextElementSibling;
      const icon = header.querySelector('.accordion-icon');
      
      // Close all other accordion sections
      accordionHeaders.forEach(otherHeader => {
        if (otherHeader !== header) {
          otherHeader.classList.remove('active');
          const otherContent = otherHeader.nextElementSibling;
          otherContent.classList.remove('active');
          // Reset maxHeight for smooth closing animation
          otherContent.style.maxHeight = '0px';
        }
      });
      
      // Toggle current section
      header.classList.toggle('active');
      content.classList.toggle('active');
      
      // Smooth animation for content height
      if (content.classList.contains('active')) {
        const contentHeight = content.scrollHeight;
        content.style.maxHeight = contentHeight + 'px';
      } else {
        content.style.maxHeight = '0px';
      }
    });
  });
}

// Initialize mobile footer accordion when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  initMobileFooterAccordion();
});

// Wrap letters in Tradewinds section titles with spans
function wrapLettersInSpans() {
  console.log('wrapLettersInSpans function called');
  
  // Try different selectors to find the titles
  const tradewindsTitles = document.querySelectorAll('.text-section .section-title');
  console.log('Found titles with .tradewinds .text-section .section-title:', tradewindsTitles.length);
  
  if (tradewindsTitles.length === 0) {
    // Try alternative selectors
    const allTitles = document.querySelectorAll('.section-title');
    console.log('Found all .section-title elements:', allTitles.length);
    
    allTitles.forEach(title => {
      console.log('Title text:', title.textContent);
      console.log('Title parent classes:', title.parentElement.className);
    });
  }
  
  tradewindsTitles.forEach((title, index) => {
    console.log(`Processing title ${index}:`, title.textContent);
    
    if (!title.classList.contains('letters-wrapped')) {
      const html = title.innerHTML;
      console.log('Original HTML:', html);
      
      // Split by HTML tags and text content
      const parts = html.split(/(<[^>]*>)/);
      const wrappedParts = parts.map(part => {
        // If it's an HTML tag, keep it as is
        if (part.startsWith('<') && part.endsWith('>')) {
          return part;
        }
        // If it's text content, wrap each letter
        else if (part.trim() !== '') {
          let letterIndex = 0;
          return part.split('').map(letter => {
            if (letter === ' ') {
              return '<span class="letter-space">&nbsp;</span>';
            } else {
              const span = `<span class="letter" style="--letter-index: ${letterIndex}">${letter}</span>`;
              letterIndex++;
              return span;
            }
          }).join('');
        }
        return part;
      });
      
      const wrappedHTML = wrappedParts.join('');
      console.log('Wrapped HTML:', wrappedHTML);
      title.innerHTML = wrappedHTML;
      title.classList.add('letters-wrapped');
      console.log('Letters wrapped successfully');
    } else {
      console.log('Title already wrapped');
    }
  });
}

// Initialize letter wrapping when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  wrapLettersInSpans();
});

// Video Modal Functionality
function initVideoModal() {
  const videoModal = document.getElementById('videoModal');
  if (!videoModal) return; // Exit if modal doesn't exist
  
  const videoModalClose = document.querySelector('.video-modal-close');
  const modalVideo = videoModal.querySelector('video');
  
  // Get video elements from both banner slider and separate video banner
  const bannerSliderVideo = document.querySelector('.banner-slide.video-slide video');
  const bannerVideo = document.querySelector('.video-banner video');
  const videoPlayBtn = document.querySelector('.video-slide .video-play-btn');
  const bannerVideoPlayBtn = document.querySelector('.video-banner .video-play-btn');

  // Debug video loading for banner slider video
  if (bannerSliderVideo) {
    bannerSliderVideo.addEventListener('loadstart', () => console.log('Banner slider video loading started'));
    bannerSliderVideo.addEventListener('canplay', () => console.log('Banner slider video can play'));
    bannerSliderVideo.addEventListener('error', (e) => console.error('Banner slider video error:', e));
    bannerSliderVideo.addEventListener('loadeddata', () => console.log('Banner slider video data loaded'));
    
    // Check if video is actually playing
    setInterval(() => {
      if (bannerSliderVideo.readyState >= 2) {
        console.log('Banner slider video ready state:', bannerSliderVideo.readyState);
      }
    }, 2000);
  } else {
    console.log('Banner slider video element not found');
  }

  // Debug video loading for separate video banner
  if (bannerVideo) {
    bannerVideo.addEventListener('loadstart', () => console.log('Video banner loading started'));
    bannerVideo.addEventListener('canplay', () => console.log('Video banner can play'));
    bannerVideo.addEventListener('error', (e) => console.error('Video banner error:', e));
    bannerVideo.addEventListener('loadeddata', () => console.log('Video banner data loaded'));
    
    // Check if video is actually playing
    setInterval(() => {
      if (bannerVideo.readyState >= 2) {
        console.log('Video banner ready state:', bannerVideo.readyState);
      }
    }, 2000);
  } else {
    console.log('Video banner element not found');
  }

  // Open modal when play button is clicked (banner slider video)
  if (videoPlayBtn) {
    videoPlayBtn.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      openVideoModal();
    });
  }

  // Open modal when video overlay is clicked (banner slider video)
  const videoOverlay = document.querySelector('.video-slide .video-overlay');
  if (videoOverlay) {
    videoOverlay.addEventListener('click', function(e) {
      if (e.target !== videoPlayBtn) {
        openVideoModal();
      }
    });
  }

  // Open modal when play button is clicked (separate video banner)
  if (bannerVideoPlayBtn) {
    bannerVideoPlayBtn.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      openVideoModal();
    });
  }

  // Open modal when video overlay is clicked (separate video banner)
  const bannerVideoOverlay = document.querySelector('.video-banner .video-overlay');
  if (bannerVideoOverlay) {
    bannerVideoOverlay.addEventListener('click', function(e) {
      if (e.target !== bannerVideoPlayBtn) {
        openVideoModal();
      }
    });
  }

  // Close modal when close button is clicked
  if (videoModalClose) {
    videoModalClose.addEventListener('click', function() {
      closeVideoModal();
    });
  }

  // Close modal when clicking outside the video
  videoModal.addEventListener('click', function(e) {
    if (e.target === videoModal) {
      closeVideoModal();
    }
  });

  // Close modal with Escape key
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && videoModal.classList.contains('active')) {
      closeVideoModal();
    }
  });

  function openVideoModal() {
    videoModal.classList.add('active');
    document.body.style.overflow = 'hidden'; // Prevent background scrolling
    
    // Pause all videos and play modal video
    if (bannerSliderVideo) {
      bannerSliderVideo.pause();
    }
    if (bannerVideo) {
      bannerVideo.pause();
    }
    if (modalVideo) {
      modalVideo.currentTime = 0; // Start from beginning
      modalVideo.play();
    }
  }

  function closeVideoModal() {
    videoModal.classList.remove('active');
    document.body.style.overflow = ''; // Restore scrolling
    
    // Pause modal video and resume appropriate video
    if (modalVideo) {
      modalVideo.pause();
    }
    
    // Resume the video that was playing before modal opened
    // Check which video slide is currently active
    const activeSlide = document.querySelector('.banner-slide.active');
    if (activeSlide && activeSlide.classList.contains('video-slide') && bannerSliderVideo) {
      bannerSliderVideo.play();
    } else if (bannerVideo) {
      bannerVideo.play();
    }
  }
}

