// assets/js/main.js
document.addEventListener('DOMContentLoaded', function() {
    // 1. Navbar scroll effect
    const navbar = document.querySelector('.navbar');
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }

    // 2. Add high-end visual Toast notification system dynamically
    const toastContainer = document.createElement('div');
    toastContainer.id = 'mndirect-toast-container';
    toastContainer.style.cssText = 'position: fixed; bottom: 30px; right: 30px; z-index: 9999; display: flex; flex-direction: column; gap: 10px; pointer-events: none;';
    document.body.appendChild(toastContainer);

    window.showToast = function(message, type = 'success') {
        const toast = document.createElement('div');
        toast.style.cssText = `
            background: rgba(27, 27, 27, 0.95);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border-left: 4px solid ${type === 'success' ? 'var(--accent-gold)' : '#dc3545'};
            color: #ffffff;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            font-size: 0.85rem;
            font-weight: 500;
            letter-spacing: 0.5px;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            pointer-events: auto;
            min-width: 250px;
        `;
        toast.innerHTML = `
            <div class="d-flex align-items-center justify-content-between gap-3">
                <div class="d-flex align-items-center gap-2">
                    <i class="${type === 'success' ? 'fa-solid fa-circle-check text-warning' : 'fa-solid fa-circle-exclamation text-danger'}"></i>
                    <span>${message}</span>
                </div>
                <button type="button" class="btn-close btn-close-white" style="font-size: 0.7rem; box-shadow: none;" onclick="this.parentElement.parentElement.remove()"></button>
            </div>
        `;
        
        toastContainer.appendChild(toast);
        
        // Trigger reflow & animate in
        setTimeout(() => {
            toast.style.opacity = '1';
            toast.style.transform = 'translateY(0)';
        }, 50);

        // Auto remove
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-20px)';
            setTimeout(() => {
                toast.remove();
            }, 400);
        }, 3500);
    };

    // 3. Dynamic AJAX Add-to-Cart handlers
    const addToCartButtons = document.querySelectorAll('.add-to-cart-btn');
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = this.getAttribute('data-product-id');
            const quantity = this.getAttribute('data-qty') || 1;
            
            // Show loading animation on button if possible
            const originalHTML = this.innerHTML;
            this.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';
            this.disabled = true;

            fetch('cart_action.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=add&product_id=${productId}&quantity=${quantity}`
            })
            .then(response => response.json())
            .then(data => {
                this.innerHTML = originalHTML;
                this.disabled = false;
                
                if (data.status === 'success') {
                    // Update header cart count badge dynamically
                    let cartBadge = document.querySelector('.cart-badge');
                    if (cartBadge) {
                        cartBadge.textContent = data.cart_count;
                    } else {
                        // Badge doesn't exist, create it in the header
                        const cartLink = document.querySelector('.fa-bag-shopping').parentElement;
                        const badgeSpan = document.createElement('span');
                        badgeSpan.className = 'position-absolute top-0 start-100 translate-middle badge rounded-circle cart-badge';
                        badgeSpan.textContent = data.cart_count;
                        cartLink.appendChild(badgeSpan);
                    }
                    
                    // Show success toast
                    window.showToast(`${data.product_name} added to cart!`);
                } else {
                    window.showToast(data.message || 'Error adding to cart.', 'error');
                }
            })
            .catch(error => {
                console.error('Error adding to cart:', error);
                this.innerHTML = originalHTML;
                this.disabled = false;
                window.showToast('Something went wrong. Please try again.', 'error');
            });
        });
    });

    // 4. Atelier Stories Testimonial Slider
    const testimonialTrack = document.querySelector('.testimonial-track');
    const testimonialSlides = document.querySelectorAll('.testimonial-slide');
    const testimonialDots = document.querySelectorAll('.testimonial-dot');
    
    if (testimonialTrack && testimonialSlides.length > 0 && testimonialDots.length > 0) {
        let currentSlide = 0;
        let slideInterval;
        const totalSlides = testimonialSlides.length;
        
        function updateTestimonialSlider(index) {
            // Update active dot
            testimonialDots.forEach((dot, idx) => {
                if (idx === index) {
                    dot.classList.add('active');
                } else {
                    dot.classList.remove('active');
                }
            });
            
            // Translate the track
            testimonialTrack.style.transform = `translateX(-${index * (100 / totalSlides)}%)`;
            currentSlide = index;
        }
        
        function nextSlide() {
            let next = (currentSlide + 1) % totalSlides;
            updateTestimonialSlider(next);
        }
        
        function startAutoSlide() {
            slideInterval = setInterval(nextSlide, 5000);
        }
        
        function stopAutoSlide() {
            clearInterval(slideInterval);
        }
        
        // Manual control click events
        testimonialDots.forEach((dot, idx) => {
            dot.addEventListener('click', function() {
                stopAutoSlide();
                updateTestimonialSlider(idx);
                startAutoSlide();
            });
        });
        
        // Pause auto-sliding on hover
        const testimonialSection = document.querySelector('.testimonial-section');
        if (testimonialSection) {
            testimonialSection.addEventListener('mouseenter', stopAutoSlide);
            testimonialSection.addEventListener('mouseleave', startAutoSlide);
        }
        
        // Start sliding initially
        startAutoSlide();
    }
});
