// Mobile Menu Logic
document.addEventListener('DOMContentLoaded', () => {
    const menuBtn = document.getElementById('menu-btn');
    const mobileMenu = document.getElementById('mobile-menu');
    const closeMenuBtn = document.getElementById('close-menu-btn');

    if (menuBtn && mobileMenu && closeMenuBtn) {
        menuBtn.addEventListener('click', () => {
            mobileMenu.classList.remove('hidden');
            // Small timeout to allow display:block to apply before opacity transition
            setTimeout(() => {
                mobileMenu.classList.remove('opacity-0');
            }, 10);
        });

        closeMenuBtn.addEventListener('click', () => {
            mobileMenu.classList.add('opacity-0');
            setTimeout(() => {
                mobileMenu.classList.add('hidden');
            }, 300);
        });
    }

    // Mobile Submenu Toggle Logic
    const submenuToggles = document.querySelectorAll('.submenu-toggle');

    submenuToggles.forEach(toggle => {
        toggle.addEventListener('click', () => {
            const targetId = toggle.getAttribute('data-target');
            const target = document.getElementById(targetId);
            const icon = toggle.querySelector('.material-symbols-outlined:last-child');

            if (target) {
                const isHidden = target.classList.contains('hidden');

                if (isHidden) {
                    target.classList.remove('hidden');
                    icon.style.transform = 'rotate(180deg)';
                } else {
                    target.classList.add('hidden');
                    icon.style.transform = 'rotate(0deg)';
                }
            }
        });
    });

    // Single Product Plan Logic
    const tierButtons = document.querySelectorAll('.tier-btn');
    const toggleFeaturesButtons = document.querySelectorAll('.toggle-features-btn');

    if (tierButtons.length > 0) {
        tierButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                // Update button states
                tierButtons.forEach(b => {
                    b.classList.remove('active', 'bg-white', 'dark:bg-surface-dark', 'shadow-sm', 'text-primary');
                    b.classList.add('text-text-muted', 'hover:text-primary');
                });
                btn.classList.add('active', 'bg-white', 'dark:bg-surface-dark', 'shadow-sm', 'text-primary');
                btn.classList.remove('text-text-muted', 'hover:text-primary');

                const tier = btn.getAttribute('data-tier');
                const durations = {
                    weekly: '/wk',
                    monthly: '/mo',
                    yearly: '/yr'
                };

                // Update prices and duration text
                document.querySelectorAll('.price-display').forEach(price => {
                    const newPrice = price.getAttribute(`data-${tier}`);
                    if (newPrice) {
                        price.textContent = newPrice;
                    }
                });

                document.querySelectorAll('.duration-period').forEach(period => {
                    period.textContent = durations[tier];
                });
            });
        });
    }

    if (toggleFeaturesButtons.length > 0) {
        toggleFeaturesButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const card = btn.closest('.plan-card');
                const extraFeatures = card.querySelector('.extra-features');
                const icon = btn.querySelector('.material-symbols-outlined');
                const text = btn.querySelector('span:first-child');

                if (extraFeatures) {
                    const isHidden = extraFeatures.classList.contains('hidden');
                    if (isHidden) {
                        extraFeatures.classList.remove('hidden');
                        icon.style.transform = 'rotate(180deg)';
                        text.textContent = 'Hide extra features';
                    } else {
                        extraFeatures.classList.add('hidden');
                        icon.style.transform = 'rotate(0deg)';
                        text.textContent = 'Show all features';
                    }
                }
            });
        });
    }

    // Product Tabs Logic
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content > div');

    if (tabButtons.length > 0) {
        tabButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const targetTab = btn.getAttribute('data-tab');

                // Update button states
                tabButtons.forEach(b => {
                    b.classList.remove('active', 'text-primary', 'border-primary', 'font-semibold');
                    b.classList.add('text-text-muted', 'border-transparent', 'font-medium');
                });
                btn.classList.add('active', 'text-primary', 'border-primary', 'font-semibold');
                btn.classList.remove('text-text-muted', 'border-transparent', 'font-medium');

                // Update content visibility
                tabContents.forEach(content => {
                    if (content.id === `tab-${targetTab}`) {
                        content.classList.remove('hidden');
                    } else {
                        content.classList.add('hidden');
                    }
                });
            });
        });
    }

    // FAQ Accordion Logic
    const faqToggles = document.querySelectorAll('.faq-toggle');

    if (faqToggles.length > 0) {
        faqToggles.forEach(toggle => {
            toggle.addEventListener('click', () => {
                const item = toggle.closest('.faq-item');
                const isActive = item.classList.contains('active');

                // Close all other items (Optional: comment out if you want multiple open)
                document.querySelectorAll('.faq-item').forEach(i => i.classList.remove('active'));

                if (!isActive) {
                    item.classList.add('active');
                }
            });
        });
    }

    // Real-time FAQ Search
    const faqSearch = document.getElementById('faq-search');
    const faqItems = document.querySelectorAll('.faq-item');

    if (faqSearch && faqItems.length > 0) {
        faqSearch.addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase();

            faqItems.forEach(item => {
                const question = item.querySelector('.faq-toggle span').textContent.toLowerCase();
                const answer = item.querySelector('.faq-body p').textContent.toLowerCase();

                if (question.includes(query) || answer.includes(query)) {
                    item.classList.remove('hidden');
                } else {
                    item.classList.add('hidden');
                }
            });

            // Optional: Show "No results found" message
            const visibleItems = document.querySelectorAll('.faq-item:not(.hidden)');
            let noResults = document.getElementById('faq-no-results');

            if (visibleItems.length === 0) {
                if (!noResults) {
                    noResults = document.createElement('div');
                    noResults.id = 'faq-no-results';
                    noResults.className = 'text-center py-10 text-text-muted text-sm bg-gray-50 dark:bg-white/5 rounded-xl border border-dashed border-gray-200 dark:border-gray-700';
                    noResults.textContent = 'No matching questions found.';
                    faqSearch.closest('.mb-10').after(noResults);
                }
            } else if (noResults) {
                noResults.remove();
            }
        });
    }

    // Product Gallery Logic
    const mainImage = document.getElementById('main-product-image');
    const thumbnailBtns = document.querySelectorAll('.thumbnail-btn');

    if (mainImage && thumbnailBtns.length > 0) {
        thumbnailBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                // Use data-original-src to always show the full-resolution image
                const newSrc = btn.dataset.originalSrc || btn.querySelector('img').src;

                // Update active state
                thumbnailBtns.forEach(b => {
                    b.classList.remove('active', 'border-primary', 'ring-2', 'ring-primary/20');
                    b.classList.add('border-gray-200', 'dark:border-gray-700', 'opacity-70');
                });
                btn.classList.add('active', 'border-primary', 'ring-2', 'ring-primary/20');
                btn.classList.remove('border-gray-200', 'dark:border-gray-700', 'opacity-70');

                // Update main image with fade effect
                mainImage.style.opacity = '0.3';
                setTimeout(() => {
                    mainImage.src = newSrc;
                    mainImage.style.opacity = '1';
                }, 150);
            });
        });
    }

    // Coupon Code Logic
    const couponInput = document.getElementById('coupon-input');
    const applyCouponBtn = document.getElementById('apply-coupon-btn');
    const couponMessage = document.getElementById('coupon-message');

    if (couponInput && applyCouponBtn && couponMessage) {
        applyCouponBtn.addEventListener('click', () => {
            const code = couponInput.value.trim().toUpperCase();

            if (code === '') {
                couponMessage.textContent = 'Please enter a coupon code.';
                couponMessage.className = 'text-[10px] mt-2 text-red-500 block';
                return;
            }

            // Mock validation
            if (code === 'SAVE20') {
                couponMessage.textContent = 'Coupon "SAVE20" applied! 20% discount added.';
                couponMessage.className = 'text-[10px] mt-2 text-green-600 dark:text-green-400 block font-medium';
                couponInput.classList.add('border-green-500', 'ring-1', 'ring-green-500/20');
                couponInput.classList.remove('border-gray-200', 'dark:border-gray-700');
            } else {
                couponMessage.textContent = 'Invalid coupon code. Please try again.';
                couponMessage.className = 'text-[10px] mt-2 text-red-500 block';
                couponInput.classList.add('border-red-500', 'ring-1', 'ring-red-500/20');
                couponInput.classList.remove('border-gray-200', 'dark:border-gray-700');
            }
        });

        // Clear states when typing
        couponInput.addEventListener('input', () => {
            couponMessage.classList.add('hidden');
            couponInput.classList.remove('border-green-500', 'border-red-500', 'ring-1', 'ring-green-500/20', 'ring-red-500/20');
            couponInput.classList.add('border-gray-200', 'dark:border-gray-700');
        });
    }

    // Language Switcher Toggle Logic
    const langBtn = document.getElementById('lang-switcher-btn');
    const langDropdown = document.getElementById('lang-dropdown');
    const langArrow = document.getElementById('lang-arrow');

    if (langBtn && langDropdown) {
        langBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            const isVisible = langDropdown.classList.contains('opacity-100');

            if (isVisible) {
                langDropdown.classList.remove('opacity-100', 'visible');
                langDropdown.classList.add('opacity-0', 'invisible');
                if (langArrow) langArrow.textContent = 'expand_more';
            } else {
                langDropdown.classList.remove('opacity-0', 'invisible');
                langDropdown.classList.add('opacity-100', 'visible');
                if (langArrow) langArrow.textContent = 'expand_less';
            }
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', function () {
            langDropdown.classList.remove('opacity-100', 'visible');
            langDropdown.classList.add('opacity-0', 'invisible');
            if (langArrow) langArrow.textContent = 'expand_more';
        });
    }
});
