document.addEventListener('DOMContentLoaded', () => {
    // --- STICKY HEADER SCROLL EFFECT ---
    const header = document.querySelector('header');
    window.addEventListener('scroll', () => {
        if (window.scrollY > 50) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
    });

    // --- MOBILE MENU TOGGLE ---
    const menuToggle = document.getElementById('menuToggle');
    const navMenu = document.getElementById('navMenu');
    if (menuToggle && navMenu) {
        menuToggle.addEventListener('click', () => {
            navMenu.classList.toggle('open');
            const icon = menuToggle.querySelector('i');
            if (icon) {
                icon.classList.toggle('fa-bars');
                icon.classList.toggle('fa-times');
            }
        });
    }

    // --- TOAST NOTIFICATIONS ---
    const toast = document.getElementById('toast');
    const showToast = (message) => {
        if (!toast) return;
        toast.textContent = message;
        toast.classList.add('show');
        setTimeout(() => {
            toast.classList.remove('show');
        }, 4000);
    };

    // --- SUBSCRIBE & SAVE DYNAMIC PRICING ---
    const subSaveWidgets = document.querySelectorAll('.sub-save-widget');
    subSaveWidgets.forEach(widget => {
        const radios = widget.querySelectorAll('.sub-save-radio');
        const priceDisplay = widget.closest('.product-card').querySelector('.product-price');
        
        radios.forEach(radio => {
            radio.addEventListener('change', (e) => {
                const isSubscription = e.target.value === 'sub';
                const originalPrice = parseFloat(e.target.dataset.oneTimePrice);
                const subPrice = parseFloat(e.target.dataset.subPrice);
                
                if (isSubscription) {
                    priceDisplay.innerHTML = `<span class="price-crossed">$${originalPrice.toFixed(2)}</span>$${subPrice.toFixed(2)}`;
                } else {
                    priceDisplay.innerHTML = `$${originalPrice.toFixed(2)}`;
                }
            });
        });
    });

    // --- ADD TO CART SIMULATION ---
    const addToCartButtons = document.querySelectorAll('.btn-add-cart');
    const cartCountEl = document.querySelector('.cart-count');
    let cartCount = 0;

    addToCartButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            cartCount++;
            if (cartCountEl) {
                cartCountEl.textContent = cartCount;
                cartCountEl.style.display = 'flex';
            }
            showToast('Item successfully added to your cart!');
            addLoyaltyPoints(100);
        });
    });

    // --- LOYALTY POINTS WIDGET ---
    const loyaltyBtn = document.getElementById('loyaltyWidgetBtn');
    const loyaltyModal = document.getElementById('loyaltyModal');
    const modalOverlay = document.getElementById('modalOverlay');
    const loyaltyClose = document.getElementById('loyaltyClose');
    const loyaltyPointsVal = document.getElementById('loyaltyPointsVal');
    
    // Initial loyalty points
    let currentPoints = parseInt(localStorage.getItem('valkyrie_loyalty_points_v2') || '350');
    if (loyaltyPointsVal) {
        loyaltyPointsVal.textContent = currentPoints;
    }

    function addLoyaltyPoints(amount) {
        currentPoints += amount;
        localStorage.setItem('valkyrie_loyalty_points_v2', currentPoints.toString());
        if (loyaltyPointsVal) {
            loyaltyPointsVal.textContent = currentPoints;
        }
    }

    if (loyaltyBtn && loyaltyModal && modalOverlay) {
        loyaltyBtn.addEventListener('click', () => {
            loyaltyModal.classList.add('open');
            modalOverlay.classList.add('open');
        });

        const closeModal = () => {
            loyaltyModal.classList.remove('open');
            modalOverlay.classList.remove('open');
        };

        loyaltyClose.addEventListener('click', closeModal);
        modalOverlay.addEventListener('click', closeModal);
    }

    // --- CHAT DRAWER SIMULATION ---
    const chatBtn = document.getElementById('chatWidgetBtn');
    const chatDrawer = document.getElementById('chatDrawer');
    const chatClose = document.getElementById('chatClose');
    const chatSend = document.getElementById('chatSend');
    const chatInput = document.getElementById('chatInput');
    const chatMessages = document.getElementById('chatMessages');

    if (chatBtn && chatDrawer) {
        chatBtn.addEventListener('click', () => {
            chatDrawer.classList.toggle('open');
            setTimeout(() => {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }, 100);
        });

        chatClose.addEventListener('click', () => {
            chatDrawer.classList.remove('open');
        });

        const handleSendMessage = () => {
            const text = chatInput.value.trim();
            if (!text) return;

            appendMessage(text, 'user');
            chatInput.value = '';

            setTimeout(() => {
                const autoReply = getBotReply(text);
                appendMessage(autoReply, 'bot');
            }, 1000);
        };

        chatSend.addEventListener('click', handleSendMessage);
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleSendMessage();
            }
        });
    }

    function appendMessage(text, sender) {
        const bubble = document.createElement('div');
        bubble.classList.add('chat-bubble', sender);
        bubble.textContent = text;
        chatMessages.appendChild(bubble);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function getBotReply(msg) {
        const text = msg.toLowerCase();
        if (text.includes('hello') || text.includes('hi') || text.includes('hey')) {
            return "Hello brave warrior! Welcome to Valkyrie Coffee Company support. How can I help you today?";
        }
        if (text.includes('coffee') || text.includes('roast')) {
            return "All of our coffees are roasted in the USA from premium beans sourced globally. Our most popular roast is the Valhalla Dark Roast! You can buy it as a one-time purchase or Subscribe & Save 15%.";
        }
        if (text.includes('subscribe') || text.includes('save') || text.includes('subscription')) {
            return "Our Subscribe & Save program delivers fresh coffee directly to your door at your preferred frequency (every 2, 4, or 6 weeks) and saves you 15% on every bag. You can cancel or pause anytime!";
        }
        if (text.includes('veteran') || text.includes('charity') || text.includes('profit') || text.includes('donate')) {
            return "Valkyrie Coffee Company pledges to donate 5% of all profits to mental health organizations, PTSD programs, and resources that help veterans when the VA falls short. Thank you for your support!";
        }
        if (text.includes('help') || text.includes('resource') || text.includes('ptsd') || text.includes('support')) {
            return "If you or a loved one are in distress, please visit our Veterans Resource page, or call the Veterans Crisis Line directly by dialing 988 (Press 1). We are here to make sure you know you are not alone.";
        }
        return "Thank you for reaching out! A member of our Valkyrie Support Team will review your message and email you at your account address shortly. Until Valhalla!";
    }

    // --- PRODUCT FILTERS (FOR COLLECTION PAGES) ---
    const filterButtons = document.querySelectorAll('.filter-btn');
    const productCards = document.querySelectorAll('.product-card');

    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            filterButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');

            const filterValue = button.dataset.filter;

            productCards.forEach(card => {
                if (filterValue === 'all') {
                    card.style.display = 'flex';
                } else {
                    const category = card.dataset.category || '';
                    if (category.toLowerCase() === filterValue.toLowerCase()) {
                        card.style.display = 'flex';
                    } else {
                        card.style.display = 'none';
                    }
                }
            });
        });
    });

    // --- FORM SUBMISSION PREVENTS ---
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            
            if (form.classList.contains('notify-form')) {
                showToast("Success! We'll notify you as soon as the Merchandise collection drops.");
            } else if (form.classList.contains('contact-form')) {
                showToast("Message received! We will get back to you shortly at the provided email.");
            } else if (form.classList.contains('footer-sub-form')) {
                showToast("Thank you for joining our ranks! Check your inbox for a discount code.");
            } else {
                showToast("Form submitted successfully!");
            }
            form.reset();
        });
    });
});
