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

// 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 toggleNav() {
  const isOpening = !fullscreenNav.classList.contains('active');
  
  if (isOpening) {
    // Opening menu
    fullscreenNav.classList.add('active');
    navToggle.classList.add('active');
    navClose.classList.add('active');
    body.classList.add('menu-active');
  } else {
    // Closing menu
    fullscreenNav.classList.remove('active');
    navToggle.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', () => {
    fullscreenNav.classList.remove('active');
    body.style.overflow = '';
  });
});

// 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;

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');
  }
  
  lastScrollTop = scrollTop;
});

// Ensure elements are visible on page load
document.addEventListener('DOMContentLoaded', () => {
  body.classList.remove('scrolled');
});

// Add intersection observer for scroll animations
const observerOptions = {
  threshold: 0.1,
  rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.style.opacity = '1';
      entry.target.style.transform = 'translateY(0)';
    }
  });
}, observerOptions);

// Observe elements for scroll animations
document.addEventListener('DOMContentLoaded', () => {
  const animatedElements = document.querySelectorAll('.event-card, .feature-card, .content-wrapper');
  
  animatedElements.forEach(el => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(30px)';
    el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    observer.observe(el);
  });
});

// CTA Button interactions
document.querySelectorAll('.cta-button').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

  function nextSlide() {
    // 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');
  }

  // Set initial state
  slides[0].classList.add('active');

  // Only start the slideshow if there's more than one slide
  if (slides.length > 1) {
    setInterval(nextSlide, slideInterval);
  }
}

// Scroll Down Button Functionality
document.querySelector('.scroll-down-btn').addEventListener('click', () => {
  const textSection = document.querySelector('.text-section-1');
  const duration = 1000; // Duration in milliseconds
  const start = window.pageYOffset;
  const scrollDistance = textSection.offsetTop - start;
  const startTime = performance.now();

  function scrollStep(timestamp) {
    const currentTime = timestamp - startTime;
    const progress = Math.min(currentTime / duration, 1);
    
    // Easing function for smooth acceleration and deceleration
    const easeInOutCubic = progress => {
      return progress < 0.5
        ? 4 * progress * progress * progress
        : 1 - Math.pow(-2 * progress + 2, 3) / 2;
    };

    window.scrollTo(0, start + (scrollDistance * easeInOutCubic(progress)));

    if (progress < 1) {
      requestAnimationFrame(scrollStep);
    }
  }

  requestAnimationFrame(scrollStep);
});

// Initialize banner slideshow when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  initBannerSlideshow();
  initBannerOverlay();
  initCloudEffect();
  initHeaderHover();
});

// Initialize Splide Carousel for Services
document.addEventListener('DOMContentLoaded', () => {
  const servicesSplide = new Splide('.services-splide', {
    type: 'loop',
    perPage: 3,
    perMove: 1,
    focus: 'center',
    gap: '1rem',
    padding: { left: '10%', right: '10%' },
    breakpoints: {
      1200: {
        perPage: 2,
        padding: { left: '5%', right: '5%' }
      },
      768: {
        perPage: 1,
        padding: { left: '5%', right: '5%' }
      }
    },
    autoplay: true,
    interval: 4000,
    pauseOnHover: true,
    pauseOnFocus: true,
    arrows: true,
    pagination: false,
    classes: {
      arrows: 'splide__arrows',
      arrow: 'splide__arrow',
      prev: 'splide__arrow--prev',
      next: 'splide__arrow--next'
    }
  });

  servicesSplide.mount();
});

const stack = document.querySelector('.stack');
const nextBtn = document.querySelector('.nav-btn.next');
const prevBtn = document.querySelector('.nav-btn.prev');

const cards = Array.from(stack.children).reverse().filter((child) => child.classList.contains('card'));

cards.forEach((card) => stack.appendChild(card));

function moveCard(direction) {
  if (direction === 'next') {
    const lastCard = stack.lastElementChild;
    if (lastCard.classList.contains("card")) {
      lastCard.classList.add("swap-next");
      setTimeout(() => {
        lastCard.classList.remove("swap-next");
        stack.insertBefore(lastCard, stack.firstElementChild);
      }, 1200);
    }
  } else if (direction === 'prev') {
    const firstCard = stack.firstElementChild;
    if (firstCard.classList.contains("card")) {
      firstCard.classList.add("swap-prev");
      setTimeout(() => {
        firstCard.classList.remove("swap-prev");
        stack.appendChild(firstCard);
      }, 1200);
    }
  }
}

let autoplayInterval = setInterval(() => moveCard('next'), 3000);

// Add click event listeners to both buttons
nextBtn.addEventListener("click", () => moveCard('next'));
prevBtn.addEventListener("click", () => moveCard('prev'));

// Banner Overlay Transition
function initBannerOverlay() {
  const overlay = document.querySelector('.banner-overlay-transition');
  const banner = document.querySelector('.banner');
  const bannerHeight = banner.offsetHeight;
  let lastScrollTop = 0;

  window.addEventListener('scroll', () => {
    if (!overlay || !banner) return;

    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const viewportHeight = window.innerHeight;
    
    // Calculate how far we've scrolled relative to the banner height
    // When scrollTop is 0, progress is 0 (start)
    // When scrollTop is bannerHeight, progress is 1 (end)
    const scrollProgress = Math.min(Math.max(scrollTop / bannerHeight, 0), 1);
    
    // Update overlay transform based on scroll progress
    // When scrollProgress is 0, overlay is at 100% (fully hidden)
    // When scrollProgress is 1, overlay is at 0% (fully visible)
    const translateY = (1 - scrollProgress) * 100;
    overlay.style.transform = `translateY(${translateY}%)`;

    lastScrollTop = scrollTop;
  });
}

function initCloudEffect() {
  const cloud = document.getElementById('cloud');
  const banner = document.querySelector('.banner');
  const textSection1 = document.querySelector('.text-section-1');
  
  function updateCloudHeight() {
    const bannerBottom = banner.getBoundingClientRect().bottom;
    const textSection1Top = textSection1.getBoundingClientRect().top;
    const windowHeight = window.innerHeight;
    
    // Calculate how far we've scrolled between banner and text-section-1
    const scrollProgress = Math.max(0, Math.min(1, 
      (windowHeight - bannerBottom) / (windowHeight + textSection1Top - bannerBottom)
    ));
    
    // Set cloud height based on scroll progress (max height of 100vh)
    const cloudHeight = scrollProgress * windowHeight;
    cloud.style.height = `${cloudHeight}px`;
  }

  // Update cloud height on scroll
  window.addEventListener('scroll', updateCloudHeight);
  // Initial update
  updateCloudHeight();
}

function initHeaderHover() {
  const headerRight = document.querySelector('.header-right');
  const links = headerRight.querySelectorAll('a, button');

  links.forEach(link => {
    link.addEventListener('mouseenter', () => {
      headerRight.style.background = 'rgba(0, 0, 0, 0.2)';
    });

    link.addEventListener('mouseleave', () => {
      headerRight.style.background = 'rgba(255, 255, 255, 0.192)';
    });
  });
}