/**
 * tap2order-landing.js
 * Landing page JavaScript for tap2order promotional website.
 * Vanilla JS — no jQuery dependency.
 */
document.addEventListener('DOMContentLoaded', function () {

  /* ── Helpers ─────────────────────────────────────────────── */
  function qs(sel, ctx) { return (ctx || document).querySelector(sel); }
  function qsa(sel, ctx) { return Array.from((ctx || document).querySelectorAll(sel)); }

  /* ── 1. Sticky Header ────────────────────────────────────── */
  var header = qs('.landing-header');
  if (header) {
    window.addEventListener('scroll', function () {
      if (window.scrollY > 80) {
        header.classList.add('scrolled');
      } else {
        header.classList.remove('scrolled');
      }
    }, { passive: true });
  }

  /* ── 2. Mobile Menu Toggle ───────────────────────────────── */
  var menuToggle = qs('.landing-menu-toggle');
  var navMenu = qs('.landing-nav-menu');

  if (menuToggle && navMenu) {
    function closeMenu() {
      navMenu.classList.remove('open');
      menuToggle.classList.remove('active');
      menuToggle.setAttribute('aria-expanded', 'false');
      document.body.style.overflow = '';
    }

    function openMenu() {
      navMenu.classList.add('open');
      menuToggle.classList.add('active');
      menuToggle.setAttribute('aria-expanded', 'true');
      document.body.style.overflow = 'hidden';
    }

    menuToggle.addEventListener('click', function (e) {
      e.stopPropagation();
      var isOpen = navMenu.classList.contains('open');
      if (isOpen) {
        closeMenu();
      } else {
        openMenu();
      }
    });

    // Close on link click
    qsa('a', navMenu).forEach(function (link) {
      link.addEventListener('click', function () {
        closeMenu();
      });
    });

    // Close on outside click
    document.addEventListener('click', function (e) {
      if (navMenu.classList.contains('open') &&
          !navMenu.contains(e.target) &&
          !menuToggle.contains(e.target)) {
        closeMenu();
      }
    });
  }

  /* ── 3. Smooth Scroll ────────────────────────────────────── */
  qsa('a[href^="#"]').forEach(function (anchor) {
    anchor.addEventListener('click', function (e) {
      var targetId = this.getAttribute('href');
      if (targetId === '#' || targetId === '#!') return;

      var target = document.querySelector(targetId);
      if (!target) return;

      e.preventDefault();

      var headerOffset = 80;
      var elementPosition = target.getBoundingClientRect().top + window.pageYOffset;
      var offsetPosition = elementPosition - headerOffset;

      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth'
      });
    });
  });

  /* ── 4. Active Nav Highlight ─────────────────────────────── */
  var navLinks = qsa('.landing-nav-menu a[href^="#"]');
  var sections = [];

  navLinks.forEach(function (link) {
    var id = link.getAttribute('href');
    if (id && id !== '#' && id !== '#!') {
      var section = document.querySelector(id);
      if (section) {
        sections.push({ el: section, link: link });
      }
    }
  });

  if (sections.length) {
    function updateActiveNav() {
      var scrollPos = window.scrollY + 100;

      var active = null;
      sections.forEach(function (s) {
        if (s.el.offsetTop <= scrollPos) {
          active = s;
        }
      });

      navLinks.forEach(function (l) { l.classList.remove('active'); });
      if (active) {
        active.link.classList.add('active');
      }
    }

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

  /* ── 5. FAQ Accordion ────────────────────────────────────── */
  var faqQuestions = qsa('.t2o-faq-question');

  faqQuestions.forEach(function (question) {
    question.addEventListener('click', function () {
      var faqItem = this.closest('.t2o-faq-item');
      if (!faqItem) return;

      var answer = qs('.t2o-faq-answer', faqItem);
      var isOpen = faqItem.classList.contains('active');

      // Close all
      qsa('.t2o-faq-item.active').forEach(function (item) {
        item.classList.remove('active');
        var ans = qs('.t2o-faq-answer', item);
        if (ans) {
          ans.style.maxHeight = null;
          ans.setAttribute('aria-hidden', 'true');
        }
        var btn = qs('.t2o-faq-question', item);
        if (btn) btn.setAttribute('aria-expanded', 'false');
      });

      // Toggle clicked
      if (!isOpen && faqItem && answer) {
        faqItem.classList.add('active');
        answer.style.maxHeight = answer.scrollHeight + 'px';
        answer.setAttribute('aria-hidden', 'false');
        question.setAttribute('aria-expanded', 'true');
      }
    });
  });

  /* ── 6. Pricing Toggle ───────────────────────────────────── */
  var pricingToggles = qsa('.t2o-pricing-toggle');

  pricingToggles.forEach(function (toggle) {
    toggle.addEventListener('click', function () {
      var planCard = this.closest('.t2o-pricing-card') || this.closest('.t2o-pricing') || document;
      var prices = qsa('.t2o-plan-price', planCard);
      var periods = qsa('.t2o-plan-period', planCard);

      var isAnnual = this.dataset.period === 'annual';

      // Update toggle active state
      qsa('.t2o-pricing-toggle', this.closest('.t2o-pricing-toggle-group') || this.parentElement)
        .forEach(function (btn) { btn.classList.remove('active'); });
      this.classList.add('active');

      // Update prices
      prices.forEach(function (el) {
        var monthly = el.dataset.monthly;
        var annual = el.dataset.annual;
        if (isAnnual && annual) {
          el.textContent = annual;
        } else if (monthly) {
          el.textContent = monthly;
        }
      });

      // Update periods
      periods.forEach(function (el) {
        if (isAnnual) {
          el.textContent = el.dataset.annualText || '/year';
        } else {
          el.textContent = el.dataset.monthlyText || '/month';
        }
      });
    });
  });

  /* ── 7. Contact Form ─────────────────────────────────────── */
  var contactForm = qs('.t2o-contact-form');

  if (contactForm) {
    contactForm.addEventListener('submit', function (e) {
      e.preventDefault();

      var submitBtn = qs('button[type="submit"], input[type="submit"]', contactForm);
      var messageBox = qs('.t2o-form-message', contactForm) || document.querySelector('.t2o-form-message');
      var ajaxUrl = contactForm.dataset.ajaxUrl;

      if (!ajaxUrl) {
        if (messageBox) {
          messageBox.textContent = 'Configuration error. Please try again later.';
          messageBox.className = 't2o-form-message t2o-form-error';
        }
        return;
      }

      // Gather form data
      var formData = new FormData(contactForm);

      // Disable button
      if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.dataset.originalText = submitBtn.textContent;
        submitBtn.textContent = 'Sending…';
      }

      fetch(ajaxUrl, {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
      })
        .then(function (response) {
          if (!response.ok) throw new Error('Network response was not ok');
          return response.json();
        })
        .then(function (data) {
          if (messageBox) {
            if (data.success) {
              messageBox.textContent = data.message || 'Message sent successfully!';
              messageBox.className = 't2o-form-message t2o-form-success';
              contactForm.reset();
            } else {
              messageBox.textContent = data.message || 'Something went wrong. Please try again.';
              messageBox.className = 't2o-form-message t2o-form-error';
            }
          }
        })
        .catch(function (err) {
          if (messageBox) {
            messageBox.textContent = 'Network error. Please check your connection and try again.';
            messageBox.className = 't2o-form-message t2o-form-error';
          }
        })
        .finally(function () {
          if (submitBtn) {
            submitBtn.disabled = false;
            submitBtn.textContent = submitBtn.dataset.originalText || 'Send';
          }
        });
    });
  }

  /* ── 8. Scroll Animations ────────────────────────────────── */
  if ('IntersectionObserver' in window) {
    var animatedEls = qsa('.t2o-animate');

    if (animatedEls.length) {
      var animObserver = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
          if (entry.isIntersecting) {
            entry.target.classList.add('t2o-visible');
            animObserver.unobserve(entry.target);
          }
        });
      }, {
        threshold: 0.15,
        rootMargin: '0px 0px -50px 0px'
      });

      animatedEls.forEach(function (el) {
        animObserver.observe(el);
      });
    }
  }

  /* ── 9. Back to Top ──────────────────────────────────────── */
  var topBtn = qs('.t2o-topbtn');

  if (topBtn) {
    window.addEventListener('scroll', function () {
      if (window.scrollY > 500) {
        topBtn.classList.add('t2o-topbtn-visible');
        topBtn.style.display = '';
      } else {
        topBtn.classList.remove('t2o-topbtn-visible');
        topBtn.style.display = 'none';
      }
    }, { passive: true });

    // Initial state
    topBtn.style.display = window.scrollY > 500 ? '' : 'none';

    topBtn.addEventListener('click', function (e) {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    });
  }

  /* ── 10. WhatsApp Float ──────────────────────────────────── */
  var whatsappFloat = qs('.t2o-whatsapp-float');

  if (whatsappFloat) {
    whatsappFloat.style.opacity = '0';
    whatsappFloat.style.transition = 'opacity 0.4s ease';

    setTimeout(function () {
      whatsappFloat.style.opacity = '1';
    }, 1000);
  }

});
