// ── MEGA MENU: JS hover with 120ms close-delay ───────────────────────

(function () {
  var timer = null, current = null;
  function open(li) {
    clearTimeout(timer);
    if (current && current !== li) current.classList.remove('is-open');
    li.classList.add('is-open'); current = li;
  }
  function scheduleClose() {
    clearTimeout(timer);
    timer = setTimeout(function () {
      if (current) { current.classList.remove('is-open'); current = null; }
    }, 120);
  }
  document.querySelectorAll('.mega-parent').forEach(function (li) {
    li.addEventListener('mouseenter', function () { open(li); });
    li.addEventListener('mouseleave', scheduleClose);
    var panel = li.querySelector('.mega-dropdown');
    if (panel) {
      panel.addEventListener('mouseenter', function () { clearTimeout(timer); });
      panel.addEventListener('mouseleave', scheduleClose);
    }
  });
  window.addEventListener('resize', function () {
    if (current && window.innerWidth >= 992) { current.classList.remove('is-open'); current = null; }
  });
})();

// ── NAVBAR SCROLL SHADOW + FLOAT SIDEBAR ─────────────────────────────
var hdr    = document.getElementById('site-header');
var floatS = document.getElementById('float-sidebar');
var heroEl = document.querySelector('.hero-slider-height');

window.addEventListener('scroll', function () {
  var scrollY = window.scrollY;
  if (hdr) hdr.classList.toggle('scrolled', scrollY > 12);
  if (floatS && heroEl) {
    var heroBottom = heroEl.offsetTop + heroEl.offsetHeight;
    floatS.classList.toggle('visible', scrollY > heroBottom - 80);
  }
}, { passive: true });

// ── CONTACT MODAL ─────────────────────────────────────────────────────
var MODAL_TITLES = {
  contact: 'Get in Touch',
  quote:   'Get a Free Quote'
};

window.openModal = function (type) {
  var overlay = document.getElementById('contact-modal-overlay');
  var title   = document.getElementById('cm-modal-title');
  var form    = document.getElementById('cm-form');
  var success = document.getElementById('cm-success');
  if (title)   title.textContent = MODAL_TITLES[type] || 'Contact Us';
  if (form)    form.style.display  = '';
  if (success) success.style.display = 'none';
  if (overlay) { overlay.classList.add('open'); document.body.style.overflow = 'hidden'; }
};

window.closeModal = function () {
  var overlay = document.getElementById('contact-modal-overlay');
  if (overlay) { overlay.classList.remove('open'); document.body.style.overflow = ''; }
};

window.handleOverlayClick = function (e) {
  if (e.target === document.getElementById('contact-modal-overlay')) closeModal();
};

window.handleContactSubmit = function (e) {
  e.preventDefault();
  var btn = document.getElementById('cm-submit-btn');
  if (btn) { btn.textContent = 'Sending…'; btn.disabled = true; }
  setTimeout(function () {
    var form    = document.getElementById('cm-form');
    var success = document.getElementById('cm-success');
    if (form)    form.style.display    = 'none';
    if (success) success.style.display = 'block';
    if (btn)     { btn.textContent = 'Send Message →'; btn.disabled = false; }
    var f = document.getElementById('cm-form');
    if (f) f.reset();
  }, 1200);
};

// Close modal on Escape key
document.addEventListener('keydown', function (e) {
  if (e.key === 'Escape') closeModal();
});

// ── HERO SLIDER WITH CONTENT ANIMATION ───────────────────────────────
(function () {
  var SLIDES = [
    {
      badge:    'Digital Transformation',
      title:    'Enterprise Websites & Apps That Scale',
      subtitle: 'Powering Growth for 500+ Businesses Worldwide',
      desc:     'AdvertSneak Technologies is your trusted technology partner — building beautiful brands, scalable IT infrastructures, and automated processes so you can focus on growing your core business.',
      cta2:     'View Our Services'
    },
    {
      badge:    'Digital Marketing',
      title:    'Data-Driven Marketing That Delivers Real Results',
      subtitle: 'SEO, Social Media & Performance Campaigns',
      desc:     'From SEO and social media to paid advertising and brand strategy — our full-funnel digital marketing solutions drive measurable growth and lasting brand authority.',
      cta2:     'Explore Marketing'
    },
    {
      badge:    'Cloud & AI Solutions',
      title:    'Automate, Innovate & Accelerate Your Business',
      subtitle: 'Cloud Infrastructure, AI & Custom Software',
      desc:     'Leverage cutting-edge cloud infrastructure, AI-powered automation, and custom software development to streamline operations and unlock new revenue streams.',
      cta2:     'Discover Solutions'
    }
  ];

  var total       = SLIDES.length;
  var current     = 1; // slide 2 active in HTML by default
  var transitioning = false;
  var autoTimer   = null;

  var bgs     = [1,2,3].map(function(n){ return document.getElementById('hero-slide-'+n); });
  var badge   = document.getElementById('hero-badge-text');
  var title   = document.getElementById('hero-title');
  var sub     = document.getElementById('hero-subtitle');
  var desc    = document.getElementById('hero-desc');
  var cta2    = document.getElementById('hero-cta-secondary');
  var counter = document.getElementById('hero-counter');
  var box     = document.getElementById('hero-content-box');
  var dots    = document.querySelectorAll('[aria-label^="Go to slide"]');
  var prevBtn = document.querySelector('[aria-label="Previous slide"]');
  var nextBtn = document.querySelector('[aria-label="Next slide"]');

  function pad(n) { return String(n+1).padStart(2,'0'); }

  function updateDots(idx) {
    dots.forEach(function(d,i){
      d.className = i===idx
        ? 'transition-all duration-300 rounded-full w-8 h-2.5 bg-white'
        : 'transition-all duration-300 rounded-full w-2.5 h-2.5 bg-white/40 hover:bg-white/70';
    });
  }

  function setContent(idx) {
    var s = SLIDES[idx];
    if (badge)   badge.textContent   = s.badge;
    if (title)   title.textContent   = s.title;
    if (sub)     sub.textContent     = s.subtitle;
    if (desc)    desc.textContent    = s.desc;
    if (counter) counter.textContent = pad(idx) + ' / ' + pad(total-1);
    if (cta2) {
      var nodes = cta2.childNodes;
      for (var i = nodes.length-1; i >= 0; i--) {
        if (nodes[i].nodeType === 3 && nodes[i].textContent.trim()) {
          nodes[i].textContent = '\n\t\t\t\t\t\t\t' + s.cta2 + '\n\t\t\t\t\t\t\t';
          break;
        }
      }
    }
  }

  function animateContent(idx) {
    if (!box) { setContent(idx); return; }

    // Phase 1: animate OUT current content
    box.classList.remove('ready','animating-in');
    box.classList.add('animating-out');

    setTimeout(function () {
      // Update text while invisible
      setContent(idx);
      updateDots(idx);

      // Phase 2: animate IN new content
      box.classList.remove('animating-out');
      box.classList.add('animating-in');

      // After animation completes, mark stable
      setTimeout(function () {
        box.classList.remove('animating-in');
        box.classList.add('ready');
      }, 700);

    }, 320); // matches heroOut duration + max delay
  }

  function goTo(idx) {
    if (transitioning) return;
    var target = ((idx % total) + total) % total;
    if (target === current) return;
    transitioning = true;

    // Swap background
    bgs[current].classList.remove('opacity-100','z-10');
    bgs[current].classList.add('opacity-0','z-0');
    current = target;
    bgs[current].classList.remove('opacity-0','z-0');
    bgs[current].classList.add('opacity-100','z-10');

    animateContent(current);
    setTimeout(function(){ transitioning = false; }, 750);
  }

  function startAuto() {
    clearInterval(autoTimer);
    autoTimer = setInterval(function(){ goTo(current+1); }, 5000);
  }

  if (prevBtn) prevBtn.addEventListener('click', function(){ goTo(current-1); startAuto(); });
  if (nextBtn) nextBtn.addEventListener('click', function(){ goTo(current+1); startAuto(); });
  dots.forEach(function(d,i){ d.addEventListener('click', function(){ goTo(i); startAuto(); }); });

  // Init
  setContent(current);
  updateDots(current);
  if (box) {
    // small delay so browser has painted first frame
    setTimeout(function(){
      box.classList.add('animating-in');
      setTimeout(function(){ box.classList.remove('animating-in'); box.classList.add('ready'); }, 700);
    }, 100);
  }
  startAuto();
})();


//


// ===== HERO CAROUSEL INIT (already handled by data-bs-ride, but ensure interval) =====
  const heroCarouselEl = document.getElementById('heroCarousel');
  if (heroCarouselEl) {
    new bootstrap.Carousel(heroCarouselEl, {
      interval: 5000,
      ride: 'carousel',
      wrap: true
    });
  }

  // ===== MEGA MENU: Close on outside click =====
  document.addEventListener('click', function (e) {
    const openDropdowns = document.querySelectorAll('.mega-menu-wrapper .dropdown-menu.show');
    openDropdowns.forEach(function (menu) {
      const parent = menu.closest('.mega-menu-wrapper');
      if (parent && !parent.contains(e.target)) {
        const toggle = parent.querySelector('[data-bs-toggle="dropdown"]');
        if (toggle) {
          const bsDropdown = bootstrap.Dropdown.getInstance(toggle);
          if (bsDropdown) bsDropdown.hide();
        }
      }
    });
  });


// ── TESTIMONIAL SLIDER ─────────────────────────────────────────
(function () {
  'use strict';

  var viewport   = document.querySelector('.ts-viewport');
  var track      = document.getElementById('tsTrack');
  var dotsWrap   = document.getElementById('tsDots');
  var prevBtn    = document.getElementById('tsPrev');
  var nextBtn    = document.getElementById('tsNext');
  var progressEl = document.getElementById('tsProgress');
  var wrap       = document.getElementById('tsSliderWrap');

  if (!track || !viewport) return;

  var slides   = Array.prototype.slice.call(track.querySelectorAll('.ts-slide'));
  var total    = slides.length;
  var current  = 0;
  var AUTO_MS  = 5000;
  var autoID   = null;
  var progID   = null;
  var progVal  = 0;
  var busy     = false;
  var slidesToShow = 1;

  // ── Responsive Slides Count ─────────────────────
  function updateSlidesToShow() {
    var w = window.innerWidth;
    if (w >= 1024) slidesToShow = 3;
    else if (w >= 768) slidesToShow = 2;
    else slidesToShow = 1;

    slides.forEach(function (slide) {
      slide.style.flex = "0 0 " + (100 / slidesToShow) + "%";
    });

    goTo(current, true);
  }

  window.addEventListener('resize', updateSlidesToShow);

  // ── Move To Slide ───────────────────────────────
  function goTo(idx, instant) {
    if (busy && !instant) return;
    busy = true;

    var maxIndex = total - slidesToShow;
    if (idx < 0) idx = maxIndex;
    if (idx > maxIndex) idx = 0;

    current = idx;

    track.style.transition = instant ? 'none' : 'transform 0.55s cubic-bezier(0.4,0,0.2,1)';
    track.style.transform  = 'translateX(-' + (current * (100 / slidesToShow)) + '%)';

    setTimeout(function () { busy = false; }, instant ? 0 : 560);
  }

  // ── Auto-play ───────────────────────────────────
  function startAuto() {
    clearInterval(autoID);
    autoID = setInterval(function () {
      goTo(current + 1);
    }, AUTO_MS);
  }

  function stopAuto() {
    clearInterval(autoID);
  }

  if (prevBtn) prevBtn.addEventListener('click', function () { goTo(current - 1); });
  if (nextBtn) nextBtn.addEventListener('click', function () { goTo(current + 1); });

  if (wrap) {
    wrap.addEventListener('mouseenter', stopAuto);
    wrap.addEventListener('mouseleave', startAuto);
  }

  // ── Touch Support ───────────────────────────────
  var startX = 0;
  viewport.addEventListener('touchstart', function (e) {
    startX = e.touches[0].clientX;
    stopAuto();
  }, { passive: true });

  viewport.addEventListener('touchend', function (e) {
    var endX = e.changedTouches[0].clientX;
    var diff = startX - endX;

    if (diff > 50) goTo(current + 1);
    if (diff < -50) goTo(current - 1);

    startAuto();
  });

  // Init
  updateSlidesToShow();
  startAuto();

})();