// GO2WILD AFRICA — site interactions (vanilla JS, no framework)
document.addEventListener('DOMContentLoaded', function () {

  /* sticky nav shrink */
  var nav = document.querySelector('.site-nav');
  if (nav) {
    var onScroll = function () {
      if (window.scrollY > 40) nav.classList.add('is-scrolled');
      else nav.classList.remove('is-scrolled');
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
  }

  /* mobile nav toggle */
  var toggle = document.querySelector('.nav-toggle');
  var links = document.querySelector('.nav-links');
  if (toggle && links) {
    toggle.addEventListener('click', function () {
      links.classList.toggle('open');
      document.body.classList.toggle('nav-open');
    });
    links.querySelectorAll('a').forEach(function (a) {
      a.addEventListener('click', function () { links.classList.remove('open'); });
    });
  }

  /* language switch dropdown (mobile tap) */
  document.querySelectorAll('.lang-switch').forEach(function (el) {
    var btn = el.querySelector('.lang-btn');
    if (!btn) return;
    btn.addEventListener('click', function (e) {
      e.stopPropagation();
      el.classList.toggle('open');
    });
  });
  document.addEventListener('click', function () {
    document.querySelectorAll('.lang-switch.open').forEach(function (el) { el.classList.remove('open'); });
  });

  /* animated counters */
  var counters = document.querySelectorAll('[data-counter]');
  if (counters.length) {
    var animate = function (el) {
      var target = parseInt(el.getAttribute('data-counter'), 10) || 0;
      var dur = 1400, start = null;
      var step = function (ts) {
        if (!start) start = ts;
        var p = Math.min((ts - start) / dur, 1);
        el.textContent = Math.floor(p * target);
        if (p < 1) requestAnimationFrame(step);
        else el.textContent = target;
      };
      requestAnimationFrame(step);
    };
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) { animate(entry.target); io.unobserve(entry.target); }
      });
    }, { threshold: 0.4 });
    counters.forEach(function (c) { io.observe(c); });
  }

  /* reveal-on-scroll */
  var reveals = document.querySelectorAll('[data-reveal]');
  if (reveals.length) {
    var rio = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          setTimeout(function () { entry.target.classList.add('in'); }, parseInt(entry.target.getAttribute('data-reveal-delay') || 0, 10));
          rio.unobserve(entry.target);
        }
      });
    }, { threshold: 0.12 });
    reveals.forEach(function (r) { rio.observe(r); });
  }

  /* testimonial slider */
  var testiSlides = document.querySelectorAll('.testi-slide');
  if (testiSlides.length > 1) {
    var dotsWrap = document.querySelector('.testi-nav');
    var idx = 0;
    testiSlides.forEach(function (_, i) {
      if (!dotsWrap) return;
      var dot = document.createElement('button');
      dot.className = 'testi-dot' + (i === 0 ? ' active' : '');
      dot.addEventListener('click', function () { show(i); });
      dotsWrap.appendChild(dot);
    });
    var dots = document.querySelectorAll('.testi-dot');
    function show(i) {
      testiSlides.forEach(function (s, si) { s.style.display = si === i ? '' : 'none'; });
      dots.forEach(function (d, di) { d.classList.toggle('active', di === i); });
      idx = i;
    }
    show(0);
    setInterval(function () { show((idx + 1) % testiSlides.length); }, 6000);
  }

  /* lightbox */
  var lightbox = document.querySelector('.lightbox');
  if (lightbox) {
    var lbImg = lightbox.querySelector('img');
    var lbCaption = lightbox.querySelector('.lightbox-caption');
    var lbItems = Array.prototype.slice.call(document.querySelectorAll('[data-lightbox-src]'));
    var lbIndex = 0;
    function openLightbox(i) {
      lbIndex = i;
      var el = lbItems[i];
      lbImg.src = el.getAttribute('data-lightbox-src');
      lbImg.alt = el.getAttribute('data-lightbox-caption') || '';
      lbCaption.textContent = el.getAttribute('data-lightbox-caption') || '';
      lightbox.classList.add('open');
    }
    function closeLightbox() { lightbox.classList.remove('open'); }
    lbItems.forEach(function (el, i) {
      el.addEventListener('click', function (e) { e.preventDefault(); openLightbox(i); });
    });
    lightbox.querySelector('.lightbox-close').addEventListener('click', closeLightbox);
    lightbox.addEventListener('click', function (e) { if (e.target === lightbox) closeLightbox(); });
    lightbox.querySelector('.lightbox-nav.prev').addEventListener('click', function () { openLightbox((lbIndex - 1 + lbItems.length) % lbItems.length); });
    lightbox.querySelector('.lightbox-nav.next').addEventListener('click', function () { openLightbox((lbIndex + 1) % lbItems.length); });
    document.addEventListener('keydown', function (e) {
      if (!lightbox.classList.contains('open')) return;
      if (e.key === 'Escape') closeLightbox();
      if (e.key === 'ArrowLeft') openLightbox((lbIndex - 1 + lbItems.length) % lbItems.length);
      if (e.key === 'ArrowRight') openLightbox((lbIndex + 1) % lbItems.length);
    });
  }

  /* gallery filter */
  var filters = document.querySelectorAll('.gal-filter');
  var galItems = document.querySelectorAll('[data-gal-cat]');
  if (filters.length && galItems.length) {
    filters.forEach(function (f) {
      f.addEventListener('click', function () {
        filters.forEach(function (x) { x.classList.remove('active'); });
        f.classList.add('active');
        var cat = f.getAttribute('data-filter');
        galItems.forEach(function (item) {
          var show = cat === 'all' || item.getAttribute('data-gal-cat') === cat;
          item.style.display = show ? '' : 'none';
        });
      });
    });
  }

  /* faq accordion */
  document.querySelectorAll('.faq-q').forEach(function (q) {
    q.addEventListener('click', function () {
      q.parentElement.classList.toggle('open');
    });
  });

  /* back to top + floating visibility */
  var backTop = document.querySelector('.back-to-top');
  if (backTop) {
    window.addEventListener('scroll', function () {
      backTop.classList.toggle('show', window.scrollY > 500);
    }, { passive: true });
  }

  /* detail page TOC active state */
  var tocLinks = document.querySelectorAll('.detail-toc a');
  if (tocLinks.length) {
    var sections = Array.prototype.map.call(tocLinks, function (a) {
      return document.querySelector(a.getAttribute('href'));
    }).filter(Boolean);
    window.addEventListener('scroll', function () {
      var pos = window.scrollY + 160;
      var current = sections[0];
      sections.forEach(function (s) { if (s.offsetTop <= pos) current = s; });
      tocLinks.forEach(function (a) {
        a.classList.toggle('active', current && a.getAttribute('href') === '#' + current.id);
      });
    }, { passive: true });
  }

  /* trip planner form */
  var plannerForm = document.getElementById('tripPlannerForm');
  if (plannerForm) {
    var pathRadios = plannerForm.querySelectorAll('input[name="planPath"]');
    var pickPanel = document.getElementById('pathPickPanel');
    var budgetPanel = document.getElementById('pathBudgetPanel');

    function updatePathPanels() {
      var selected = plannerForm.querySelector('input[name="planPath"]:checked');
      var value = selected ? selected.value : 'pick';
      pickPanel.classList.toggle('is-visible', value === 'pick');
      budgetPanel.classList.toggle('is-visible', value === 'budget');
      pathRadios.forEach(function (radio) {
        radio.closest('.path-option').classList.toggle('is-active', radio.checked);
      });
    }
    pathRadios.forEach(function (radio) { radio.addEventListener('change', updatePathPanels); });
    updatePathPanels();

    function val(id) { var el = document.getElementById(id); return el ? el.value : ''; }

    function buildSummary() {
      var destinations = Array.prototype.slice.call(plannerForm.querySelectorAll('input[name="destinations"]:checked')).map(function (c) { return c.value; });
      var duration = plannerForm.querySelector('input[name="duration"]:checked');
      var zanzibar = plannerForm.querySelector('input[name="zanzibar"]:checked');
      var path = plannerForm.querySelector('input[name="planPath"]:checked');

      var lines = [
        'New Safari Inquiry — Go2Wild Africa',
        'Name: ' + val('fullName'),
        'Email: ' + val('email'),
        'WhatsApp/Phone: ' + val('phone'),
        'Nationality: ' + val('nationality'),
        'Preferred Travel Date: ' + val('travelDate'),
        'Adults: ' + val('adults') + ' | Children under 12: ' + val('children'),
      ];
      if (path && path.value === 'pick') {
        lines.push('Destinations of Interest: ' + (destinations.length ? destinations.join(', ') : 'Not specified'));
      } else {
        lines.push('Budget per person: ' + val('budget'));
        lines.push('Trip Type: ' + val('tripType'));
      }
      lines.push('Duration: ' + (duration ? duration.value : 'Any'));
      lines.push('Season Preference: ' + val('season'));
      lines.push('Zanzibar Beach Extension: ' + (zanzibar ? zanzibar.value : 'Not specified'));
      lines.push('Accommodation Level: ' + val('accommodation'));
      lines.push('Heard About Us Via: ' + val('hearAbout'));
      lines.push('Special Requests: ' + (val('specialRequests') || 'None'));
      return lines.join('\n');
    }

    function requiredFieldsFilled() {
      var ok = true;
      ['fullName', 'email', 'phone'].forEach(function (id) {
        var field = document.getElementById(id);
        if (!field.value.trim() || !field.checkValidity()) { field.classList.add('is-invalid'); ok = false; }
        else field.classList.remove('is-invalid');
      });
      return ok;
    }

    function showThankYou() {
      plannerForm.closest('.planner-card').classList.add('is-hidden');
      document.getElementById('plannerThankyou').classList.add('is-visible');
    }

    var whatsappBtn = document.getElementById('sendWhatsapp');
    if (whatsappBtn) {
      whatsappBtn.addEventListener('click', function () {
        if (!requiredFieldsFilled()) return;
        var message = encodeURIComponent(buildSummary());
        window.open('https://wa.me/255790958854?text=' + message, '_blank', 'noopener');
        showThankYou();
      });
    }
    var emailBtn = document.getElementById('sendEmail');
    if (emailBtn) {
      emailBtn.addEventListener('click', function () {
        if (!requiredFieldsFilled()) return;
        var subject = encodeURIComponent('New Safari Inquiry — Go2Wild Africa');
        var body = encodeURIComponent(buildSummary());
        window.location.href = 'mailto:info@gowildsafariafrica.com?subject=' + subject + '&body=' + body;
        showThankYou();
      });
    }
  }

  /* year */
  var yearEl = document.getElementById('year');
  if (yearEl) yearEl.textContent = new Date().getFullYear();

  /* simple contact form UX (no backend wired) */
  var form = document.querySelector('.contact-form');
  if (form) {
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      var btn = form.querySelector('button[type="submit"]');
      var original = btn.textContent;
      btn.textContent = 'Sending…';
      setTimeout(function () {
        btn.textContent = 'Message Sent ✓';
        form.reset();
        setTimeout(function () { btn.textContent = original; }, 3000);
      }, 900);
    });
  }
});
