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

    // 1. STICKY NAVBAR
    const nav = document.getElementById('mainNav');
    if (nav) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 100) {
                nav.classList.add('sticky-nav');
            } else {
                nav.classList.remove('sticky-nav');
            }
        });
    }

    // 2. COUNT-UP ANIMATION
    const countUpElements = document.querySelectorAll('[data-count-up]');
    if (countUpElements.length > 0) {
        const countUpObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const el = entry.target;
                    const target = parseInt(el.dataset.countUp) || 0;
                    const suffix = el.dataset.suffix || '';
                    const duration = 1500;
                    const startTime = performance.now();

                    function update(currentTime) {
                        const elapsed = currentTime - startTime;
                        const progress = Math.min(elapsed / duration, 1);
                        const easeOut = 1 - Math.pow(1 - progress, 3);
                        el.textContent = Math.floor(target * easeOut) + suffix;
                        if (progress < 1) {
                            requestAnimationFrame(update);
                        }
                    }
                    requestAnimationFrame(update);
                    countUpObserver.unobserve(el);
                }
            });
        }, { threshold: 0.15 });

        countUpElements.forEach(el => countUpObserver.observe(el));
    }

    // 3. COUNTDOWN TIMER
    const countdownEl = document.querySelector('[data-countdown]');
    if (countdownEl) {
        const targetDate = new Date(countdownEl.dataset.countdown + 'T00:00:00');
        const numberEls = countdownEl.querySelectorAll('.countdown-number');
        const expiredEl = countdownEl.querySelector('.countdown-expired');

        function updateCountdown() {
            const now = new Date();
            const diff = targetDate - now;

            if (diff <= 0) {
                if (expiredEl) expiredEl.style.display = 'block';
                numberEls.forEach(el => el.parentElement.style.display = 'none');
                const seps = countdownEl.querySelectorAll('.countdown-sep');
                seps.forEach(el => el.style.display = 'none');
                return;
            }

            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
            const minutes = Math.floor((diff / (1000 * 60)) % 60);
            const seconds = Math.floor((diff / 1000) % 60);

            if (numberEls[0]) numberEls[0].textContent = String(days).padStart(2, '0');
            if (numberEls[1]) numberEls[1].textContent = String(hours).padStart(2, '0');
            if (numberEls[2]) numberEls[2].textContent = String(minutes).padStart(2, '0');
            if (numberEls[3]) numberEls[3].textContent = String(seconds).padStart(2, '0');
        }
        updateCountdown();
        setInterval(updateCountdown, 1000);
    }

    // 4. AJAX FORMS
    document.querySelectorAll('.ajax-form').forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn ? submitBtn.innerHTML : '';
            const successId = form.dataset.successId || 'formSuccess';
            const successEl = document.getElementById(successId);
            const errorEl = form.querySelector('.form-error');

            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
            }

            fetch(form.action, {
                method: 'POST',
                body: new FormData(form)
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    form.style.display = 'none';
                    if (successEl) successEl.style.display = 'block';
                } else {
                    if (errorEl) {
                        errorEl.textContent = data.message || 'Something went wrong. Please try again.';
                        errorEl.style.display = 'block';
                    }
                }
            })
            .catch(() => {
                if (errorEl) {
                    errorEl.textContent = 'Network error. Please try again.';
                    errorEl.style.display = 'block';
                }
            })
            .finally(() => {
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            });
        });
    });

    // 5. GALLERY LIGHTBOX
    const galleryItems = document.querySelectorAll('[data-lightbox]');
    if (galleryItems.length > 0) {
        const images = Array.from(galleryItems).map(item => ({
            src: item.querySelector('img')?.src || item.dataset.src || '',
            alt: item.querySelector('img')?.alt || ''
        })).filter(img => img.src);

        let currentIndex = 0;

        // Create lightbox overlay
        const overlay = document.createElement('div');
        overlay.className = 'lightbox-overlay';
        overlay.innerHTML = `
            <button class="lightbox-close">&times;</button>
            <button class="lightbox-prev">&#8249;</button>
            <img src="" alt="">
            <button class="lightbox-next">&#8250;</button>
            <div class="lightbox-counter"></div>
        `;
        document.body.appendChild(overlay);

        const lbImg = overlay.querySelector('img');
        const lbCounter = overlay.querySelector('.lightbox-counter');

        function openLightbox(index) {
            currentIndex = index;
            lbImg.src = images[currentIndex].src;
            lbImg.alt = images[currentIndex].alt;
            lbCounter.textContent = (currentIndex + 1) + ' / ' + images.length;
            overlay.classList.add('active');
            document.body.style.overflow = 'hidden';
        }

        function closeLightbox() {
            overlay.classList.remove('active');
            document.body.style.overflow = '';
        }

        function nextImage() {
            currentIndex = (currentIndex + 1) % images.length;
            lbImg.src = images[currentIndex].src;
            lbImg.alt = images[currentIndex].alt;
            lbCounter.textContent = (currentIndex + 1) + ' / ' + images.length;
        }

        function prevImage() {
            currentIndex = (currentIndex - 1 + images.length) % images.length;
            lbImg.src = images[currentIndex].src;
            lbImg.alt = images[currentIndex].alt;
            lbCounter.textContent = (currentIndex + 1) + ' / ' + images.length;
        }

        galleryItems.forEach((item, index) => {
            item.addEventListener('click', () => openLightbox(index));
        });

        overlay.querySelector('.lightbox-close').addEventListener('click', closeLightbox);
        overlay.querySelector('.lightbox-next').addEventListener('click', (e) => { e.stopPropagation(); nextImage(); });
        overlay.querySelector('.lightbox-prev').addEventListener('click', (e) => { e.stopPropagation(); prevImage(); });
        overlay.addEventListener('click', (e) => { if (e.target === overlay) closeLightbox(); });

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

    // 6. FILTER TABS
    document.querySelectorAll('[data-filter-btn]').forEach(btn => {
        btn.addEventListener('click', function() {
            const filterValue = this.dataset.filterBtn;
            const container = this.closest('[data-filter-container]') || document;
            const allBtns = container.querySelectorAll('[data-filter-btn]');
            const allItems = container.querySelectorAll('[data-filter-item]');

            allBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            allItems.forEach(item => {
                const itemValue = item.dataset.filterItem;
                if (filterValue === 'all' || itemValue === filterValue) {
                    item.style.display = '';
                    setTimeout(() => { item.style.opacity = '1'; }, 10);
                } else {
                    item.style.opacity = '0';
                    setTimeout(() => { item.style.display = 'none'; }, 200);
                }
            });
        });
    });

    // 7. 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();
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });

    // 8. SCROLL REVEAL
    const revealElements = document.querySelectorAll('.reveal');
    if (revealElements.length > 0) {
        const revealObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('visible');
                    revealObserver.unobserve(entry.target);
                }
            });
        }, { threshold: 0.15 });

        revealElements.forEach(el => revealObserver.observe(el));
    }

    // Password show/hide toggle (admin login)
    document.querySelectorAll('[data-toggle-password]').forEach(toggle => {
        toggle.addEventListener('click', function() {
            const input = document.querySelector(this.dataset.togglePassword);
            if (input) {
                input.type = input.type === 'password' ? 'text' : 'password';
                this.textContent = input.type === 'password' ? 'Show' : 'Hide';
            }
        });
    });

    // Character counter for SEO fields (admin)
    document.querySelectorAll('[data-char-count]').forEach(input => {
        const target = document.querySelector(input.dataset.charCount);
        const maxChars = parseInt(input.dataset.maxChars) || 60;
        if (!target) return;

        function update() {
            const len = input.value.length;
            target.textContent = len + ' / ' + maxChars;
            if (len > maxChars) {
                target.style.color = '#f59e0b';
            } else {
                target.style.color = '#4ade80';
            }
        }
        input.addEventListener('input', update);
        update();
    });
});
