/**
 * FRESH Theme - Main JavaScript
 * @version 2.0.0
 */

(function() {
  'use strict';

  // ========== LOADING SCREEN ==========
  const loader = document.querySelector('.fresh-loader');
  if (loader) {
    window.addEventListener('load', () => {
      setTimeout(() => {
        loader.classList.add('loaded');
      }, 600);
    });
    // Fallback: remove loader after 3s regardless
    setTimeout(() => {
      if (loader) loader.classList.add('loaded');
    }, 3000);
  }

  // ========== SCROLL REVEAL ==========
  const reveals = document.querySelectorAll('.reveal');
  if (reveals.length) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('visible');
        }
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });

    reveals.forEach(el => observer.observe(el));
  }

  // ========== NAV SCROLL ==========
  const nav = document.getElementById('nav');
  if (nav) {
    window.addEventListener('scroll', () => {
      nav.classList.toggle('scrolled', window.scrollY > 50);
    });
    // Trigger on load
    nav.classList.toggle('scrolled', window.scrollY > 50);
  }

  // ========== MOBILE MENU ==========
  const mobileToggle = document.getElementById('mobileToggle');
  const navLinks = document.getElementById('navLinks');
  if (mobileToggle && navLinks) {
    mobileToggle.addEventListener('click', () => {
      navLinks.classList.toggle('open');
      mobileToggle.classList.toggle('active');
      const isOpen = navLinks.classList.contains('open');
      mobileToggle.setAttribute('aria-expanded', isOpen);
    });

    navLinks.querySelectorAll('a').forEach(link => {
      // Don't close mobile menu when clicking the services mega link
      if (link.closest('.has-mega') && link.parentElement.classList.contains('has-mega')) return;
      link.addEventListener('click', () => {
        navLinks.classList.remove('open');
        mobileToggle.classList.remove('active');
        mobileToggle.setAttribute('aria-expanded', 'false');
      });
    });

    // Close mega menu links on click (mobile)
    navLinks.querySelectorAll('.mega-menu a').forEach(link => {
      link.addEventListener('click', () => {
        navLinks.classList.remove('open');
        mobileToggle.classList.remove('active');
        mobileToggle.setAttribute('aria-expanded', 'false');
      });
    });
  }

  // ========== MEGA MENU (mobile toggle) ==========
  document.querySelectorAll('.nav-links > li.has-mega > a').forEach(link => {
    link.addEventListener('click', function(e) {
      // Only toggle on mobile (when mobile toggle is visible)
      if (window.innerWidth <= 768) {
        e.preventDefault();
        this.parentElement.classList.toggle('mega-open');
      }
    });
  });

  // Close mega menu when clicking outside (desktop)
  document.addEventListener('click', function(e) {
    if (window.innerWidth > 768 && !e.target.closest('.has-mega')) {
      document.querySelectorAll('.has-mega.mega-open').forEach(el => el.classList.remove('mega-open'));
    }
  });

  // ========== COUNTER ANIMATION ==========
  const counters = document.querySelectorAll('.number[data-count]');
  if (counters.length) {
    const counterObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const counter = entry.target;
          const target = parseInt(counter.getAttribute('data-count'));
          if (isNaN(target)) return;

          // Preserve suffix text (e.g., "+", "%", "M+")
          const fullText = counter.textContent;
          const suffix = fullText.replace(/[0-9]/g, '').trim();
          const duration = 2000;
          const start = performance.now();

          function update(now) {
            const elapsed = now - start;
            const progress = Math.min(elapsed / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 3);
            counter.textContent = Math.round(target * eased) + suffix;
            if (progress < 1) requestAnimationFrame(update);
          }

          requestAnimationFrame(update);
          counterObserver.unobserve(counter);
        }
      });
    }, { threshold: 0.5 });

    counters.forEach(c => counterObserver.observe(c));
  }

  // ========== SERVICES TABS ==========
  const tabBtns = document.querySelectorAll('.tab-btn');
  const serviceCards = document.querySelectorAll('.service-card, .service-listing-card[data-category], .portfolio-card[data-category]');

  if (tabBtns.length && serviceCards.length) {
    tabBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        tabBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');

        const category = btn.getAttribute('data-category');

        serviceCards.forEach(card => {
          if (category === 'all' || card.getAttribute('data-category') === category) {
            card.style.display = '';
            setTimeout(() => {
              card.style.opacity = '1';
              card.style.transform = 'translateY(0)';
            }, 50);
          } else {
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';
            setTimeout(() => { card.style.display = 'none'; }, 300);
          }
        });
      });
    });
  }

  // ========== SMOOTH SCROLL ==========
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
      const href = this.getAttribute('href');
      if (href === '#') return;

      const target = document.querySelector(href);
      if (target) {
        e.preventDefault();
        const offset = nav ? nav.offsetHeight : 80;
        const top = target.getBoundingClientRect().top + window.scrollY - offset;
        window.scrollTo({ top: top, behavior: 'smooth' });
      }
    });
  });

  // ========== REELS CAROUSEL (scroll-snap) ==========
  // No complex JS needed — scroll-snap handles swiping natively.
  // We just handle lightbox open from reel cards.

  // ========== VIDEO LIGHTBOX ==========
  const lightbox = document.getElementById('vcLightbox');
  if (lightbox) {
    const iframe = document.getElementById('vcLightboxIframe');
    const closeBtn = lightbox.querySelector('.vc-lightbox-close');
    const overlay = lightbox.querySelector('.vc-lightbox-overlay');

    // Open lightbox from reel card click
    document.querySelectorAll('.reel-card[data-embed]').forEach(card => {
      card.addEventListener('click', () => {
        const embedUrl = card.getAttribute('data-embed');
        if (!embedUrl) return;
        iframe.src = embedUrl;
        lightbox.classList.add('open');
        document.body.style.overflow = 'hidden';
      });
    });

    function closeLightbox() {
      lightbox.classList.remove('open');
      document.body.style.overflow = '';
      setTimeout(() => {
        iframe.src = '';
      }, 400);
    }

    if (closeBtn) closeBtn.addEventListener('click', closeLightbox);
    if (overlay) overlay.addEventListener('click', closeLightbox);

    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && lightbox.classList.contains('open')) {
        closeLightbox();
      }
    });
  }

  // ========== CONTACT FORM (AJAX) ==========
  const contactForm = document.getElementById('freshContactForm');
  if (contactForm && typeof freshData !== 'undefined') {
    contactForm.addEventListener('submit', function(e) {
      e.preventDefault();

      const formStatus = document.getElementById('formStatus');
      const submitBtn = contactForm.querySelector('button[type="submit"]');
      const originalText = submitBtn.textContent;

      submitBtn.textContent = 'שולח...';
      submitBtn.disabled = true;

      const formData = new FormData(contactForm);
      formData.append('action', 'fresh_contact');
      formData.append('nonce', freshData.nonce);

      fetch(freshData.ajaxUrl, {
        method: 'POST',
        body: formData,
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          formStatus.style.color = '#C9A84C';
          formStatus.textContent = data.data.message;
          contactForm.reset();
        } else {
          formStatus.style.color = '#e74c3c';
          formStatus.textContent = data.data.message || 'שגיאה בשליחה. נסו שוב.';
        }
      })
      .catch(() => {
        formStatus.style.color = '#e74c3c';
        formStatus.textContent = 'שגיאה בחיבור. נסו שוב מאוחר יותר.';
      })
      .finally(() => {
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
      });
    });
  }

  // ========== CTA FORM (homepage) ==========
  const ctaForm = document.querySelector('.cta-form');
  if (ctaForm) {
    const ctaBtn = ctaForm.querySelector('.btn-primary');
    const ctaInput = ctaForm.querySelector('.cta-input');
    if (ctaBtn && ctaInput) {
      ctaBtn.addEventListener('click', function(e) {
        e.preventDefault();
        const email = ctaInput.value.trim();
        if (!email || !email.includes('@')) {
          ctaInput.style.borderColor = '#e74c3c';
          return;
        }
        ctaInput.style.borderColor = '#C9A84C';
        ctaBtn.textContent = 'נשלח! ✓';
        ctaBtn.style.background = '#2ecc71';
        setTimeout(() => {
          ctaBtn.textContent = 'שלח ←';
          ctaBtn.style.background = '';
          ctaInput.value = '';
          ctaInput.style.borderColor = '';
        }, 3000);
      });
    }
  }

  // ========== POPUP CONTACT FORM ==========
  const popup = document.getElementById('popupContact');
  if (popup) {
    const popupForm = document.getElementById('popupContactForm');
    const popupStatus = document.getElementById('popupStatus');
    const popupClose = popup.querySelector('.popup-close');
    const popupBackdrop = popup.querySelector('.popup-backdrop');

    function openPopup() {
      popup.classList.add('open');
      document.body.style.overflow = 'hidden';
    }
    function closePopup() {
      popup.classList.remove('open');
      document.body.style.overflow = '';
    }

    // Trigger: any element with data-popup="contact" or .popup-trigger
    document.querySelectorAll('[data-popup="contact"], .popup-trigger').forEach(btn => {
      btn.addEventListener('click', function(e) {
        e.preventDefault();
        openPopup();
      });
    });

    if (popupClose) popupClose.addEventListener('click', closePopup);
    if (popupBackdrop) popupBackdrop.addEventListener('click', closePopup);
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && popup.classList.contains('open')) closePopup();
    });

    // AJAX submit
    if (popupForm && typeof freshData !== 'undefined') {
      popupForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const submitBtn = popupForm.querySelector('.popup-submit');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = 'שולח...';
        submitBtn.disabled = true;

        const formData = new FormData(popupForm);
        formData.append('action', 'fresh_contact');
        formData.append('nonce', freshData.nonce);

        fetch(freshData.ajaxUrl, { method: 'POST', body: formData })
          .then(res => res.json())
          .then(data => {
            if (data.success) {
              popupStatus.style.color = '#C9A84C';
              popupStatus.textContent = data.data.message;
              popupForm.reset();
              setTimeout(closePopup, 2500);
            } else {
              popupStatus.style.color = '#e74c3c';
              popupStatus.textContent = data.data.message || 'שגיאה בשליחה.';
            }
          })
          .catch(() => {
            popupStatus.style.color = '#e74c3c';
            popupStatus.textContent = 'שגיאה בחיבור. נסו שוב.';
          })
          .finally(() => {
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
          });
      });
    }
  }

  // ========== FOOTER MINI CONTACT FORM ==========
  const footerForm = document.getElementById('footerContactForm');
  if (footerForm && typeof freshData !== 'undefined') {
    footerForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const statusEl = document.getElementById('footerFormStatus');
      const submitBtn = footerForm.querySelector('button[type="submit"]');
      const originalText = submitBtn.textContent;
      submitBtn.textContent = 'שולח...';
      submitBtn.disabled = true;

      const formData = new FormData(footerForm);
      formData.append('action', 'fresh_contact');
      formData.append('nonce', freshData.nonce);

      fetch(freshData.ajaxUrl, { method: 'POST', body: formData })
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            statusEl.style.color = '#C9A84C';
            statusEl.textContent = 'תודה! נחזור אליכם בהקדם.';
            footerForm.reset();
          } else {
            statusEl.style.color = '#e74c3c';
            statusEl.textContent = data.data.message || 'שגיאה בשליחה.';
          }
        })
        .catch(() => {
          statusEl.style.color = '#e74c3c';
          statusEl.textContent = 'שגיאה בחיבור. נסו שוב.';
        })
        .finally(() => {
          submitBtn.textContent = originalText;
          submitBtn.disabled = false;
        });
    });
  }

})();
