/**
 * Wilcon - Main JavaScript (Vanilla)
 * Upgraded from jQuery to vanilla JS
 */

// ============================================
// AVIF Support Detection & Background Images
// ============================================
(function() {
  const avifSupport = new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
    img.src = 'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKBzgABq0JYRINAAsQQMICAwIAAAABAAIAAAAAACA=';
  });

  avifSupport.then((supported) => {
    if (supported) {
      document.documentElement.classList.add('avif');
      document.querySelectorAll('[style*="background-image"]').forEach(el => {
        const style = el.getAttribute('style');
        if (style && style.includes('.jpg')) {
          el.setAttribute('style', style.replace(/\.jpg/g, '.avif'));
        }
      });
    }
  });
})();

// ============================================
// Full Height Elements
// ============================================
function initFullHeight() {
  const elements = document.querySelectorAll('.js-fullheight');
  if (!elements.length) return;

  function setHeight() {
    const height = window.innerHeight + 'px';
    elements.forEach(el => el.style.height = height);
  }

  setHeight();
  window.addEventListener('resize', setHeight);
}

// ============================================
// Loader
// ============================================
function initLoader() {
  const loader = document.getElementById('ftco-loader');
  if (!loader) return;

  setTimeout(() => {
    loader.classList.remove('show');
  }, 1);
}

// ============================================
// Testimonial Slider (Swiper)
// ============================================
function initTestimonialSlider() {
  const swiperContainer = document.querySelector('.swiper-testimony');
  if (!swiperContainer || typeof Swiper === 'undefined') return;

  new Swiper('.swiper-testimony', {
    loop: true,
    autoplay: {
      delay: 5000,
      disableOnInteraction: false,
    },
    pagination: {
      el: '.swiper-pagination',
      clickable: true,
    },
    slidesPerView: 1,
    spaceBetween: 30,
  });
}

// ============================================
// Image Lightbox (GLightbox)
// ============================================
function initLightbox() {
  if (typeof GLightbox === 'undefined') return;

  const lightbox = GLightbox({
    selector: '.glightbox',
    touchNavigation: true,
    loop: true,
    closeOnOutsideClick: true,
  });
}

// ============================================
// Scroll Animations (AOS)
// ============================================
function initScrollAnimations() {
  if (typeof AOS === 'undefined') return;

  AOS.init({
    duration: 800,
    easing: 'ease-in-out',
    once: true,
    offset: 50,
  });
}

// ============================================
// Counter Animation with IntersectionObserver
// ============================================
function initCounter() {
  const counterSection = document.querySelector('.ftco-counter');
  if (!counterSection) return;

  const numbers = document.querySelectorAll('.number');
  if (!numbers.length) return;

  let animated = false;

  function animateNumber(el, target, duration = 2000) {
    const start = 0;
    const startTime = performance.now();

    function update(currentTime) {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);

      // Easing function (ease-out)
      const eased = 1 - Math.pow(1 - progress, 3);
      const current = Math.floor(start + (target - start) * eased);

      el.textContent = current.toLocaleString();

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

    requestAnimationFrame(update);
  }

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting && !animated) {
        animated = true;
        numbers.forEach(num => {
          const target = parseInt(num.dataset.number, 10);
          if (!isNaN(target)) {
            animateNumber(num, target);
          }
        });
      }
    });
  }, { threshold: 0.3 });

  observer.observe(counterSection);
}

// ============================================
// Navbar Scroll Behavior
// ============================================
function initNavbarScroll() {
  const navbar = document.querySelector('.ftco-navbar-light');
  if (!navbar) return;

  function handleScroll() {
    const st = window.scrollY;

    if (st > 150) {
      navbar.classList.add('scrolled');
    } else {
      navbar.classList.remove('scrolled', 'sleep');
    }

    if (st > 350) {
      navbar.classList.add('awake');
    } else {
      navbar.classList.remove('awake');
      if (st < 150) {
        navbar.classList.add('sleep');
      }
    }
  }

  window.addEventListener('scroll', handleScroll);
}

// ============================================
// Dropdown Hover (Desktop)
// ============================================
function initDropdownHover() {
  const dropdowns = document.querySelectorAll('nav .dropdown');

  dropdowns.forEach(dropdown => {
    dropdown.addEventListener('mouseenter', function() {
      this.classList.add('show');
      const toggle = this.querySelector('[data-bs-toggle="dropdown"]');
      const menu = this.querySelector('.dropdown-menu');
      if (toggle) toggle.setAttribute('aria-expanded', 'true');
      if (menu) menu.classList.add('show');
    });

    dropdown.addEventListener('mouseleave', function() {
      this.classList.remove('show');
      const toggle = this.querySelector('[data-bs-toggle="dropdown"]');
      const menu = this.querySelector('.dropdown-menu');
      if (toggle) toggle.setAttribute('aria-expanded', 'false');
      if (menu) menu.classList.remove('show');
    });
  });
}

// ============================================
// Parallax Effect (CSS-based alternative)
// ============================================
function initParallax() {
  const parallaxElements = document.querySelectorAll('[data-stellar-background-ratio]');
  if (!parallaxElements.length) return;

  function updateParallax() {
    const scrollY = window.scrollY;

    parallaxElements.forEach(el => {
      const ratio = parseFloat(el.dataset.stellarBackgroundRatio) || 0.5;
      const yPos = -(scrollY * ratio);
      el.style.backgroundPositionY = yPos + 'px';
    });
  }

  window.addEventListener('scroll', updateParallax);
  updateParallax();
}

// ============================================
// Initialize All
// ============================================
// AOS must be initialized outside DOMContentLoaded when scripts are at body bottom
if (typeof AOS !== 'undefined') {
  AOS.init({
    duration: 800,
    easing: 'ease-in-out',
    once: true,
    offset: 50,
  });
}

document.addEventListener('DOMContentLoaded', function() {
  initFullHeight();
  initLoader();
  initTestimonialSlider();
  initLightbox();
  initCounter();
  initNavbarScroll();
  initDropdownHover();
  initParallax();
});
