/**
 * Harvest & Hearth Template - JavaScript
 * Custom scripts for the artisan food brand template
 */

(function() {
    'use strict';

    // Template-specific theme key (matches what's in the HTML)
    var THEME_KEY = window.RSL_THEME_KEY || 'harvest-hearth-theme';

    /**
     * Initialize all template functionality
     */
    function init() {
        initSmoothScroll();
        initNavbarScrollEffect();
        initThemeToggle();
        initFormValidation();
        initCartButtons();
        initScrollIndicator();
        initLazyImages();
    }

    /**
     * Smooth scroll for anchor links
     */
    function initSmoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
            anchor.addEventListener('click', function(e) {
                var targetId = this.getAttribute('href');
                if (targetId === '#') return;

                var targetElement = document.querySelector(targetId);
                if (targetElement) {
                    e.preventDefault();

                    // Close mobile menu if open
                    var navMenu = document.querySelector('.rsl-navbar-menu');
                    var navToggle = document.querySelector('.rsl-navbar-toggle');
                    if (navMenu && navMenu.classList.contains('open')) {
                        navMenu.classList.remove('open');
                        if (navToggle) {
                            navToggle.setAttribute('aria-expanded', 'false');
                        }
                    }

                    // Scroll to target
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });

                    // Update focus for accessibility
                    targetElement.setAttribute('tabindex', '-1');
                    targetElement.focus({ preventScroll: true });
                }
            });
        });
    }

    /**
     * Navbar background change on scroll
     */
    function initNavbarScrollEffect() {
        var navbar = document.querySelector('.hh-navbar');
        if (!navbar) return;

        var scrollThreshold = 50;

        function updateNavbar() {
            if (window.scrollY > scrollThreshold) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        }

        // Throttle scroll events
        var ticking = false;
        window.addEventListener('scroll', function() {
            if (!ticking) {
                window.requestAnimationFrame(function() {
                    updateNavbar();
                    ticking = false;
                });
                ticking = true;
            }
        });

        // Initial check
        updateNavbar();
    }

    /**
     * Theme toggle with template-specific localStorage key
     * Overrides the default theme-toggle.js behavior
     */
    function initThemeToggle() {
        var toggleBtn = document.querySelector('.rsl-theme-toggle');
        if (!toggleBtn) return;

        // Get current theme from our template-specific key
        var currentTheme = localStorage.getItem(THEME_KEY) || 'light';
        document.documentElement.setAttribute('data-theme', currentTheme);

        // Also sync to rsl-theme key so theme-toggle.js doesn't override
        localStorage.setItem('rsl-theme', currentTheme);

        // Remove any existing listeners by cloning the button
        var newToggleBtn = toggleBtn.cloneNode(true);
        toggleBtn.parentNode.replaceChild(newToggleBtn, toggleBtn);

        newToggleBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var isDark = document.documentElement.getAttribute('data-theme') === 'dark';
            var newTheme = isDark ? 'light' : 'dark';

            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem(THEME_KEY, newTheme);
            // Also sync to rsl-theme key
            localStorage.setItem('rsl-theme', newTheme);

            // Announce theme change for screen readers
            announceToScreenReader('Theme changed to ' + newTheme + ' mode');
        });
    }

    /**
     * Basic form validation
     */
    function initFormValidation() {
        var forms = document.querySelectorAll('.hh-contact-form, .hh-form');

        forms.forEach(function(form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();

                var isValid = true;
                var firstInvalid = null;

                // Check required fields
                form.querySelectorAll('[required]').forEach(function(field) {
                    if (!field.value.trim()) {
                        isValid = false;
                        field.classList.add('error');
                        if (!firstInvalid) firstInvalid = field;
                    } else {
                        field.classList.remove('error');
                    }
                });

                // Check email format
                var emailFields = form.querySelectorAll('input[type="email"]');
                emailFields.forEach(function(field) {
                    if (field.value && !isValidEmail(field.value)) {
                        isValid = false;
                        field.classList.add('error');
                        if (!firstInvalid) firstInvalid = field;
                    }
                });

                if (!isValid) {
                    if (firstInvalid) firstInvalid.focus();
                    return;
                }

                // Simulate form submission
                var submitBtn = form.querySelector('button[type="submit"]');
                var originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
                submitBtn.disabled = true;

                setTimeout(function() {
                    submitBtn.innerHTML = '<i class="fas fa-check"></i> Sent!';
                    submitBtn.classList.add('success');

                    // Show success toast if available
                    if (window.RSL && window.RSL.Toast) {
                        window.RSL.Toast.show({
                            header: 'Success!',
                            body: 'Your message has been sent. We\'ll get back to you soon!',
                            position: 'top-right',
                            autoDismiss: 5000
                        });
                    }

                    // Reset form
                    setTimeout(function() {
                        form.reset();
                        submitBtn.innerHTML = originalText;
                        submitBtn.disabled = false;
                        submitBtn.classList.remove('success');
                    }, 2000);
                }, 1500);
            });

            // Clear error on input
            form.querySelectorAll('input, textarea, select').forEach(function(field) {
                field.addEventListener('input', function() {
                    this.classList.remove('error');
                });
            });
        });
    }

    /**
     * Email validation helper
     */
    function isValidEmail(email) {
        var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    /**
     * Cart button interactions
     */
    function initCartButtons() {
        document.querySelectorAll('.hh-btn-cart').forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                e.preventDefault();

                var originalText = this.innerHTML;
                var button = this;

                // Animate button
                this.innerHTML = '<i class="fas fa-check"></i> Added!';
                this.classList.add('added');

                // Show toast notification
                var productCard = this.closest('.hh-product-card');
                var productName = productCard ? productCard.querySelector('.hh-product-name') : null;
                var name = productName ? productName.textContent : 'Item';

                if (window.RSL && window.RSL.Toast) {
                    window.RSL.Toast.show({
                        header: 'Added to Cart',
                        body: name + ' has been added to your cart.',
                        position: 'bottom-right',
                        autoDismiss: 3000
                    });
                }

                // Reset button
                setTimeout(function() {
                    button.innerHTML = originalText;
                    button.classList.remove('added');
                }, 1500);
            });
        });
    }

    /**
     * Scroll indicator click handler
     */
    function initScrollIndicator() {
        var indicator = document.querySelector('.hh-scroll-indicator');
        if (!indicator) return;

        indicator.addEventListener('click', function() {
            var nextSection = document.querySelector('.hh-trust-section');
            if (nextSection) {
                nextSection.scrollIntoView({ behavior: 'smooth' });
            }
        });

        // Make it keyboard accessible
        indicator.setAttribute('role', 'button');
        indicator.setAttribute('tabindex', '0');
        indicator.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                this.click();
            }
        });
    }

    /**
     * Lazy load images using IntersectionObserver
     */
    function initLazyImages() {
        if (!('IntersectionObserver' in window)) return;

        var lazyImages = document.querySelectorAll('img[data-src]');
        if (lazyImages.length === 0) return;

        var imageObserver = new IntersectionObserver(function(entries, observer) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    var img = entry.target;
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                    observer.unobserve(img);
                }
            });
        }, {
            rootMargin: '100px'
        });

        lazyImages.forEach(function(img) {
            imageObserver.observe(img);
        });
    }

    /**
     * Screen reader announcement helper
     */
    function announceToScreenReader(message) {
        var announcement = document.createElement('div');
        announcement.setAttribute('role', 'status');
        announcement.setAttribute('aria-live', 'polite');
        announcement.setAttribute('aria-atomic', 'true');
        announcement.className = 'sr-only';
        announcement.textContent = message;

        document.body.appendChild(announcement);

        setTimeout(function() {
            document.body.removeChild(announcement);
        }, 1000);
    }

    /**
     * Add scrolled navbar styles dynamically
     */
    var navbarScrollStyles = document.createElement('style');
    navbarScrollStyles.textContent = [
        '.hh-navbar.scrolled {',
        '    background: rgba(255, 255, 255, 0.98);',
        '    box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);',
        '}',
        '[data-theme="dark"] .hh-navbar.scrolled {',
        '    background: rgba(28, 25, 23, 0.98);',
        '}',
        '.hh-btn-cart.added {',
        '    background: #228B22 !important;',
        '}',
        '.rsl-field-input.error {',
        '    border-color: #C41E3A !important;',
        '}',
        '.sr-only {',
        '    position: absolute;',
        '    width: 1px;',
        '    height: 1px;',
        '    padding: 0;',
        '    margin: -1px;',
        '    overflow: hidden;',
        '    clip: rect(0, 0, 0, 0);',
        '    white-space: nowrap;',
        '    border: 0;',
        '}'
    ].join('\n');
    document.head.appendChild(navbarScrollStyles);

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
