/* =============================================
   FIREWORLD FIBER GLASS — Main JavaScript
   ============================================= */

document.addEventListener('DOMContentLoaded', function () {

    /* ===== Preloader ===== */
    var preloader = document.querySelector('.preloader');
    if (preloader) {
        document.body.style.overflow = 'hidden';
        window.addEventListener('load', function () {
            setTimeout(function () {
                preloader.classList.add('loaded');
                document.body.style.overflow = '';
            }, 2200);
        });
        setTimeout(function () {
            preloader.classList.add('loaded');
            document.body.style.overflow = '';
        }, 4000);
    }

    /* ===== Sticky Header ===== */
    var header = document.querySelector('.header');
    if (header) {
        window.addEventListener('scroll', function () {
            header.classList.toggle('scrolled', window.scrollY > 80);
        });
    }

    /* Mobile menu handled by inline script in <head> */

    /* ===== Hero Slider ===== */
    var heroSlides   = document.querySelectorAll('.hero-slide');
    var heroDots     = document.querySelectorAll('.hero-nav-dot');
    var heroPrev     = document.querySelector('.hero-arrow-prev');
    var heroNext     = document.querySelector('.hero-arrow-next');
    var heroProgress = document.querySelector('.hero-progress');
    var currentSlide = 0;
    var slideTimer   = null;
    var SLIDE_DUR    = 6000;

    function startProgress() {
        if (!heroProgress) return;
        heroProgress.style.transition = 'none';
        heroProgress.style.width = '0%';
        void heroProgress.offsetWidth;
        heroProgress.style.transition = 'width ' + SLIDE_DUR + 'ms linear';
        heroProgress.style.width = '100%';
    }

    function goToSlide(index, direction) {
        if (!heroSlides.length) return;
        direction = direction || 'next';
        var prev = currentSlide;
        currentSlide = ((index % heroSlides.length) + heroSlides.length) % heroSlides.length;

        heroSlides[prev].classList.add('slide-out');
        setTimeout(function () {
            heroSlides[prev].classList.remove('active', 'slide-out', 'slide-from-left');
        }, 900);

        if (direction === 'prev') {
            heroSlides[currentSlide].classList.add('slide-from-left');
        } else {
            heroSlides[currentSlide].classList.remove('slide-from-left');
        }

        requestAnimationFrame(function () {
            requestAnimationFrame(function () {
                heroSlides[currentSlide].classList.remove('slide-from-left');
                heroSlides[currentSlide].classList.add('active');
            });
        });

        heroDots.forEach(function (d, i) {
            d.classList.toggle('active', i === currentSlide);
        });

        startProgress();
    }

    function startAutoplay() {
        clearTimeout(slideTimer);
        slideTimer = setTimeout(function () {
            goToSlide(currentSlide + 1, 'next');
            startAutoplay();
        }, SLIDE_DUR);
    }

    function resetAutoplay() {
        clearTimeout(slideTimer);
        startAutoplay();
    }

    if (heroSlides.length > 1) {
        startProgress();
        startAutoplay();

        if (heroNext) {
            heroNext.addEventListener('click', function () {
                goToSlide(currentSlide + 1, 'next');
                resetAutoplay();
            });
        }
        if (heroPrev) {
            heroPrev.addEventListener('click', function () {
                goToSlide(currentSlide - 1, 'prev');
                resetAutoplay();
            });
        }
        heroDots.forEach(function (dot, i) {
            dot.addEventListener('click', function () {
                goToSlide(i, i > currentSlide ? 'next' : 'prev');
                resetAutoplay();
            });
        });

        /* Touch swipe */
        var touchStartX = 0;
        var heroEl = document.querySelector('.hero');
        if (heroEl) {
            heroEl.addEventListener('touchstart', function (e) {
                touchStartX = e.changedTouches[0].screenX;
            }, { passive: true });
            heroEl.addEventListener('touchend', function (e) {
                var diff = touchStartX - e.changedTouches[0].screenX;
                if (Math.abs(diff) > 48) {
                    goToSlide(diff > 0 ? currentSlide + 1 : currentSlide - 1, diff > 0 ? 'next' : 'prev');
                    resetAutoplay();
                }
            }, { passive: true });
        }

        document.addEventListener('keydown', function (e) {
            if (e.key === 'ArrowLeft')  { goToSlide(currentSlide - 1, 'prev'); resetAutoplay(); }
            if (e.key === 'ArrowRight') { goToSlide(currentSlide + 1, 'next'); resetAutoplay(); }
        });
    }

    /* ===== Scroll Reveal ===== */
    var revealEls = document.querySelectorAll('.reveal, .reveal-left, .reveal-right, .reveal-scale');
    if (revealEls.length && 'IntersectionObserver' in window) {
        var revealObs = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('revealed');
                    revealObs.unobserve(entry.target);
                }
            });
        }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
        revealEls.forEach(function (el) { revealObs.observe(el); });
    }

    /* ===== Counter Animation ===== */
    var counters = document.querySelectorAll('[data-count]');
    function animateCounter(el) {
        var target   = parseInt(el.getAttribute('data-count'));
        var suffix   = el.getAttribute('data-suffix') || '';
        var duration = 2000;
        var startTime = null;
        function step(ts) {
            if (!startTime) startTime = ts;
            var progress = Math.min((ts - startTime) / duration, 1);
            var eased = 1 - Math.pow(1 - progress, 3);
            el.textContent = Math.floor(eased * target) + suffix;
            if (progress < 1) requestAnimationFrame(step);
            else el.textContent = target + suffix;
        }
        requestAnimationFrame(step);
    }
    if (counters.length && 'IntersectionObserver' in window) {
        var cntObs = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    animateCounter(entry.target);
                    cntObs.unobserve(entry.target);
                }
            });
        }, { threshold: 0.5 });
        counters.forEach(function (c) { cntObs.observe(c); });
    }

    /* ===== Lightbox ===== */
    var lightbox      = document.querySelector('.lightbox');
    var lightboxImg   = document.querySelector('.lightbox-img');
    var lightboxClose = document.querySelector('.lightbox-close');
    var lightboxPrev  = document.querySelector('.lightbox-prev');
    var lightboxNext  = document.querySelector('.lightbox-next');
    var galleryItems  = document.querySelectorAll('[data-lightbox]');
    var lbImages = [], lbIndex = 0;

    galleryItems.forEach(function (item, i) {
        lbImages.push(item.getAttribute('data-lightbox'));
        item.addEventListener('click', function () { lbIndex = i; openLb(i); });
    });

    function openLb(idx) {
        if (!lightbox || !lightboxImg) return;
        lightboxImg.src = lbImages[idx];
        lightbox.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    function closeLb() {
        if (!lightbox) return;
        lightbox.classList.remove('active');
        document.body.style.overflow = '';
    }

    if (lightboxClose) lightboxClose.addEventListener('click', closeLb);
    if (lightbox) lightbox.addEventListener('click', function (e) { if (e.target === lightbox) closeLb(); });
    if (lightboxPrev) lightboxPrev.addEventListener('click', function () { lbIndex = (lbIndex - 1 + lbImages.length) % lbImages.length; lightboxImg.src = lbImages[lbIndex]; });
    if (lightboxNext) lightboxNext.addEventListener('click', function () { lbIndex = (lbIndex + 1) % lbImages.length; lightboxImg.src = lbImages[lbIndex]; });

    /* ===== Back to Top ===== */
    var backToTop = document.querySelector('.back-to-top');
    if (backToTop) {
        window.addEventListener('scroll', function () {
            backToTop.classList.toggle('visible', window.scrollY > 400);
        });
        backToTop.addEventListener('click', function () {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    }

    /* ===== Smooth Scroll ===== */
    document.querySelectorAll('a[href^="#"]').forEach(function (anchor) {
        anchor.addEventListener('click', function (e) {
            var target = document.querySelector(this.getAttribute('href'));
            if (target) { e.preventDefault(); target.scrollIntoView({ behavior: 'smooth' }); }
        });
    });

    /* ===== Contact Form ===== */
    var contactForm = document.getElementById('contactForm');
    if (contactForm) {
        contactForm.addEventListener('submit', function (e) {
            e.preventDefault();
            var valid = true;
            contactForm.querySelectorAll('[required]').forEach(function (input) {
                input.style.borderColor = input.value.trim() ? '' : '#e74c3c';
                if (!input.value.trim()) valid = false;
            });
            var emailInput = contactForm.querySelector('input[type="email"]');
            if (emailInput && emailInput.value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput.value)) {
                emailInput.style.borderColor = '#e74c3c';
                valid = false;
            }
            if (valid) {
                alert('Thank you for your message! We will get back to you shortly.');
                contactForm.reset();
            }
        });
    }

    /* ===== Click Tracking ===== */
    var STORE_KEY = 'fw_clicks';
    function getStore() { try { return JSON.parse(localStorage.getItem(STORE_KEY)) || {}; } catch(e) { return {}; } }
    function saveStore(d) { try { localStorage.setItem(STORE_KEY, JSON.stringify(d)); } catch(e) {} }
    function track(key) {
        var d = getStore();
        d[key] = (d[key] || 0) + 1;
        d['_last_' + key] = new Date().toISOString();
        d['_total'] = (d['_total'] || 0) + 1;
        saveStore(d);
    }

    document.querySelectorAll('.btn, .hp-link, .hero-btns a, .header-cta').forEach(function (el) {
        el.addEventListener('click', function () {
            track('btn__' + (el.textContent || '').trim().toLowerCase().replace(/[^a-z0-9]+/g,'_').substring(0,40));
        });
    });
    document.querySelectorAll('.whatsapp-widget, a[href*="wa.me"]').forEach(function (el) {
        el.addEventListener('click', function () { track('whatsapp'); });
    });
    document.querySelectorAll('[data-track]').forEach(function (el) {
        el.addEventListener('click', function () { track(el.getAttribute('data-track')); });
    });
    document.querySelectorAll('.nav-link, .footer-links a').forEach(function (el) {
        el.addEventListener('click', function () {
            track('nav__' + (el.textContent || '').trim().replace(/\s+/g,'_').toLowerCase().substring(0,30));
        });
    });

    window.FW_TRACKING = { getStore: getStore, track: track };

}); /* end DOMContentLoaded */
