/* ═══════════════════════════════════════════════
   THREE STAR STATIONARY — MAIN JAVASCRIPT
═══════════════════════════════════════════════ */

/* ── Sticky Header ────────────────────────────── */
const header = document.getElementById('main-header');
const floatLeft = document.getElementById('float-left');
const floatRight = document.getElementById('float-right');

function handleScroll() {
  if (window.scrollY > 50) {
    header.classList.add('scrolled');
  } else {
    header.classList.remove('scrolled');
  }
  
  if (floatLeft && floatRight) {
    if (window.scrollY > 300) {
      floatLeft.classList.add('show');
      floatRight.classList.add('show');
    } else {
      floatLeft.classList.remove('show');
      floatRight.classList.remove('show');
    }
  }

  updateActiveNav();
}

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


/* ── Mobile Navigation ────────────────────────── */
const hamburgerBtn    = document.getElementById('hamburger-btn');
const nav             = document.querySelector('.nav');
const mobileOverlay   = document.getElementById('mobile-nav-overlay');

function openMobileNav() {
  nav.classList.add('open');
  mobileOverlay.classList.add('active');
  hamburgerBtn.classList.add('open');
  hamburgerBtn.setAttribute('aria-expanded', 'true');
  document.body.style.overflow = 'hidden';
}

function closeMobileNav() {
  nav.classList.remove('open');
  mobileOverlay.classList.remove('active');
  hamburgerBtn.classList.remove('open');
  hamburgerBtn.setAttribute('aria-expanded', 'false');
  document.body.style.overflow = '';
}

hamburgerBtn.addEventListener('click', () => {
  if (nav.classList.contains('open')) {
    closeMobileNav();
  } else {
    openMobileNav();
  }
});

mobileOverlay.addEventListener('click', closeMobileNav);

// Close mobile nav on nav link click
document.querySelectorAll('.nav-link').forEach(link => {
  link.addEventListener('click', closeMobileNav);
});

// Close on ESC key
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') closeMobileNav();
});


/* ── Active Nav Highlighting ──────────────────── */
const sections   = document.querySelectorAll('section[id], div[id]');
const navLinks   = document.querySelectorAll('.nav-link');

function updateActiveNav() {
  let current = '';
  sections.forEach(section => {
    const sectionTop = section.offsetTop - 100;
    if (window.scrollY >= sectionTop) {
      current = section.getAttribute('id');
    }
  });

  navLinks.forEach(link => {
    link.classList.remove('active');
    if (link.getAttribute('href') === '#' + current) {
      link.classList.add('active');
    }
  });
}


/* ── Scroll Reveal Animations ─────────────────── */

// Respect user's motion preferences
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

/**
 * Helper: tag elements with a reveal class and optional stagger delay,
 * then register them with the IntersectionObserver.
 */
function tagReveal(selector, cls, delayStep = 0, observer) {
  document.querySelectorAll(selector).forEach((el, i) => {
    el.classList.add(cls);
    if (delayStep > 0) el.style.transitionDelay = `${i * delayStep}s`;
    observer.observe(el);
  });
}

// Intersection Observer — fires once per element
const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      revealObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.1, rootMargin: '0px 0px -60px 0px' });

function initRevealAnimations() {
  if (prefersReducedMotion) return; // skip all animations for accessibility

  // ── Hero section ─────────────────────────────────
  tagReveal('.hero-badge',    'reveal',       0,    revealObserver);
  tagReveal('.hero-title',    'reveal',       0,    revealObserver);
  document.querySelector('.hero-title') &&
    (document.querySelector('.hero-title').style.transitionDelay = '0.1s');
  tagReveal('.hero-subtitle', 'reveal',       0,    revealObserver);
  document.querySelector('.hero-subtitle') &&
    (document.querySelector('.hero-subtitle').style.transitionDelay = '0.2s');
  tagReveal('.hero-ctas',     'reveal',       0,    revealObserver);
  document.querySelector('.hero-ctas') &&
    (document.querySelector('.hero-ctas').style.transitionDelay = '0.3s');
  tagReveal('.hero-stats .stat', 'reveal',    0.1,  revealObserver);
  tagReveal('.hero-image-wrap',  'reveal-right', 0, revealObserver);
  document.querySelector('.hero-image-wrap') &&
    (document.querySelector('.hero-image-wrap').style.transitionDelay = '0.15s');

  // ── Section headers (all sections) ───────────────
  document.querySelectorAll('.section-header').forEach((header, i) => {
    header.querySelectorAll('.section-tag, .section-title, .section-subtitle').forEach((el, j) => {
      el.classList.add('reveal');
      el.style.transitionDelay = `${j * 0.1}s`;
      revealObserver.observe(el);
    });
  });

  // ── About section ────────────────────────────────
  const aboutVisual  = document.querySelector('.about-visual');
  const aboutContent = document.querySelector('.about-content');
  if (aboutVisual) {
    aboutVisual.classList.add('reveal-left');
    revealObserver.observe(aboutVisual);
  }
  if (aboutContent) {
    aboutContent.classList.add('reveal-right');
    revealObserver.observe(aboutContent);
  }
  tagReveal('.about-feature', 'reveal', 0.1, revealObserver);
  tagReveal('.stat-mini',     'reveal', 0.1, revealObserver);

  // ── Products section ─────────────────────────────
  tagReveal('.product-card',  'reveal', 0.08, revealObserver);

  // ── Wholesale section ─────────────────────────────
  tagReveal('.ws-target',     'reveal-scale', 0.08, revealObserver);
  tagReveal('.wholesale-ctas .btn', 'reveal', 0.12, revealObserver);

  // ── Gallery section ───────────────────────────────
  tagReveal('.gallery-item',  'reveal', 0.06, revealObserver);

  // ── Reviews section ───────────────────────────────
  tagReveal('.review-card',   'reveal', 0.1,  revealObserver);
  tagReveal('.rating-big',    'reveal', 0,    revealObserver);

  // ── Contact section ───────────────────────────────
  tagReveal('.contact-item',  'reveal', 0.08, revealObserver);
  tagReveal('.map-wrap',      'reveal-left', 0, revealObserver);
  tagReveal('.enquiry-form',  'reveal-right', 0, revealObserver);

  // ── Footer brand column ───────────────────────────
  tagReveal('.footer-col',    'reveal', 0.1,  revealObserver);
}

initRevealAnimations();



/* ── Counter Animation ────────────────────────── */
const counters = document.querySelectorAll('.stat-num');
let countersStarted = false;

function animateCounters() {
  if (countersStarted) return;
  const heroSection = document.getElementById('home');
  if (!heroSection) return;

  const rect = heroSection.getBoundingClientRect();
  if (rect.top < window.innerHeight && rect.bottom >= 0) {
    countersStarted = true;
    counters.forEach(counter => {
      const target = parseInt(counter.getAttribute('data-count'), 10);
      const duration = 1800;
      const step = target / (duration / 16);
      let current = 0;

      const updateCounter = () => {
        current += step;
        if (current < target) {
          counter.textContent = Math.floor(current);
          requestAnimationFrame(updateCounter);
        } else {
          counter.textContent = target;
        }
      };
      setTimeout(updateCounter, 800); // delay after page load
    });
  }
}

window.addEventListener('scroll', animateCounters, { passive: true });
// Trigger once on load too
setTimeout(animateCounters, 600);


/* ── Smooth Scroll for anchor links ───────────── */
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();
      target.scrollIntoView({ behavior: 'smooth' });
    }
  });
});


/* ── Footer Year ──────────────────────────────── */
const yearEl = document.getElementById('footer-year');
if (yearEl) yearEl.textContent = new Date().getFullYear();


/* ── Enquiry Form — WhatsApp Redirect ─────────── */
const enquiryForm = document.getElementById('enquiry-form');

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

    const name    = document.getElementById('enquiry-name').value.trim();
    const phone   = document.getElementById('enquiry-phone').value.trim();
    const message = document.getElementById('enquiry-message').value.trim();

    if (!name || !phone || !message) {
      alert('Please fill in all fields before submitting.');
      return;
    }

    const whatsappNumber = '919944682071'; // Replace with real number
    const text = `Hello Three Star Stationary! 👋\n\nName: ${name}\nPhone: ${phone}\n\nMessage: ${message}`;
    const encodedText = encodeURIComponent(text);
    const waUrl = `https://wa.me/${whatsappNumber}?text=${encodedText}`;

    window.open(waUrl, '_blank', 'noopener,noreferrer');
  });
}


/* ── Gallery Lightbox (simple) ────────────────── */
const galleryItems = document.querySelectorAll('.gallery-item');

galleryItems.forEach(item => {
  item.addEventListener('click', () => {
    const placeholder = item.querySelector('.gallery-placeholder');
    const icon  = placeholder ? placeholder.querySelector('i') : null;
    const label = placeholder ? placeholder.querySelector('span') : null;

    // Simple feedback animation
    item.style.transform = 'scale(0.97)';
    setTimeout(() => { item.style.transform = ''; }, 200);
  });
});


/* ── Product card hover ripple ────────────────── */
document.querySelectorAll('.product-card').forEach(card => {
  card.addEventListener('mouseenter', function() {
    this.style.zIndex = '10';
  });
  card.addEventListener('mouseleave', function() {
    this.style.zIndex = '';
  });
});


/* ── WhatsApp float button pulse on idle ──────── */
const waFloat = document.getElementById('whatsapp-float');
let scrolled = false;

window.addEventListener('scroll', () => {
  if (!scrolled) {
    scrolled = true;
    if (waFloat) {
      waFloat.style.animation = 'none';
      setTimeout(() => {
        waFloat.style.animation = '';
      }, 100);
    }
  }
}, { passive: true, once: true });


/* ── Preloader ────────────────────────────────── */
window.addEventListener('load', () => {
  document.body.classList.add('loaded');
  // Re-trigger counter check on load
  setTimeout(animateCounters, 300);
  // Trigger animations for elements already in viewport on load
  document.querySelectorAll('.reveal, .reveal-left, .reveal-right, .reveal-scale').forEach(el => {
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight) {
      el.classList.add('visible');
    }
  });
});


/* ── Passive scroll handler init ──────────────── */
handleScroll();

/* ── Gallery Lightbox ─────────────────────────── */
const galleryData = {
  'School Section': ['assets/school_stationery.png', 'assets/school_stationery.png', 'assets/school_stationery.png'],
  'Beads & Craft': ['assets/beads_craft.png', 'assets/beads_craft.png', 'assets/beads_craft.png'],
  'Laces & Threads': ['assets/laces_threads.png', 'assets/laces_threads.png', 'assets/laces_threads.png'],
  'Gift Corner': ['assets/gift_items.png', 'assets/gift_items.png', 'assets/gift_items.png'],
  'Office Section': ['assets/laces_threads.png', 'assets/school_stationery.png', 'assets/gift_items.png'],
  'Art & Paint Supplies': ['assets/art_supplies.png', 'assets/art_supplies.png', 'assets/art_supplies.png']
};

const lightbox = document.getElementById('gallery-lightbox');
const lightboxImg = document.getElementById('lightbox-img');
const lightboxTitle = document.getElementById('lightbox-title');
const lightboxCounter = document.getElementById('lightbox-counter');
const btnPrev = document.getElementById('lightbox-prev');
const btnNext = document.getElementById('lightbox-next');
const btnClose = document.getElementById('lightbox-close');
const overlay = document.getElementById('lightbox-overlay');

let currentCategory = '';
let currentIndex = 0;

function openLightbox(category) {
  if (!galleryData[category]) return;
  currentCategory = category;
  currentIndex = 0;
  updateLightbox();
  lightbox.classList.add('active');
  lightbox.setAttribute('aria-hidden', 'false');
  document.body.style.overflow = 'hidden'; // prevent scrolling
}

function closeLightbox() {
  if (!lightbox) return;
  lightbox.classList.remove('active');
  lightbox.setAttribute('aria-hidden', 'true');
  document.body.style.overflow = '';
}

function updateLightbox() {
  if (!galleryData[currentCategory]) return;
  const images = galleryData[currentCategory];
  
  // Add a quick fade out/in effect for the image transition
  lightboxImg.style.opacity = '0.5';
  lightboxImg.style.transform = 'scale(0.98)';
  
  setTimeout(() => {
    lightboxImg.src = images[currentIndex];
    lightboxTitle.textContent = currentCategory;
    lightboxCounter.textContent = `${currentIndex + 1} / ${images.length}`;
    
    lightboxImg.style.opacity = '1';
    lightboxImg.style.transform = 'scale(1)';
  }, 150);
}

function nextImage() {
  if (!currentCategory) return;
  const images = galleryData[currentCategory];
  currentIndex = (currentIndex + 1) % images.length;
  updateLightbox();
}

function prevImage() {
  if (!currentCategory) return;
  const images = galleryData[currentCategory];
  currentIndex = (currentIndex - 1 + images.length) % images.length;
  updateLightbox();
}

// Event Listeners for Gallery Items
document.querySelectorAll('.gallery-item').forEach(item => {
  item.addEventListener('click', () => {
    const categoryNameSpan = item.querySelector('.gallery-overlay span');
    if (categoryNameSpan) {
      openLightbox(categoryNameSpan.textContent);
    }
  });
});

// Event Listeners for Lightbox Controls
if (btnPrev) btnPrev.addEventListener('click', prevImage);
if (btnNext) btnNext.addEventListener('click', nextImage);
if (btnClose) btnClose.addEventListener('click', closeLightbox);
if (overlay) overlay.addEventListener('click', closeLightbox);

// Keyboard Navigation
document.addEventListener('keydown', (e) => {
  if (!lightbox || !lightbox.classList.contains('active')) return;
  if (e.key === 'Escape') closeLightbox();
  if (e.key === 'ArrowRight') nextImage();
  if (e.key === 'ArrowLeft') prevImage();
});

/* ── Reviews Auto-Scroll ──────────────────────── */
const reviewsSlider = document.getElementById('reviews-slider');
if (reviewsSlider) {
  let scrollInterval;
  
  const startScroll = () => {
    scrollInterval = setInterval(() => {
      // Calculate max scroll left
      const maxScroll = reviewsSlider.scrollWidth - reviewsSlider.clientWidth;
      
      // If we are at the end, jump back to start
      if (reviewsSlider.scrollLeft >= maxScroll - 5) {
        reviewsSlider.scrollTo({ left: 0, behavior: 'smooth' });
      } else {
        // Scroll by the width of one card plus gap
        const scrollAmount = reviewsSlider.querySelector('.review-card').offsetWidth + 24; // 24px = 1.5rem gap
        reviewsSlider.scrollBy({ left: scrollAmount, behavior: 'smooth' });
      }
    }, 2000);
  };
  
  const stopScroll = () => {
    clearInterval(scrollInterval);
  };
  
  // Start auto scrolling
  startScroll();
  
  // Pause on hover or touch
  reviewsSlider.addEventListener('mouseenter', stopScroll);
  reviewsSlider.addEventListener('mouseleave', startScroll);
  reviewsSlider.addEventListener('touchstart', stopScroll);
  reviewsSlider.addEventListener('touchend', startScroll);
}
