/**
 * Main JavaScript file
 *
 * @package ChaletMontagne
 */

(function($) {
    'use strict';

    /**
     * Mobile menu toggle
     */
    function initMobileMenu() {
        // Create mobile menu toggle button if it doesn't exist
        if (!$('.menu-toggle').length && $('.main-navigation').length) {
            $('.main-navigation').prepend(
                '<button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false" aria-label="' + (chaletMontagneData.menuText || 'Menu') + '">' +
                '<span class="hamburger-bar"></span>' +
                '<span class="hamburger-bar"></span>' +
                '<span class="hamburger-bar"></span>' +
                '</button>'
            );
        }

        // Create fullscreen overlay (appended to body to escape stacking contexts)
        var $overlay = $('<div class="mobile-menu-overlay" aria-hidden="true"></div>');
        var $menuClone = $('.main-navigation > ul').clone(true);
        $overlay.append($menuClone);

        // Add close button inside overlay
        $overlay.prepend(
            '<button class="mobile-menu-close" aria-label="Fermer">' +
            '<span class="hamburger-bar"></span>' +
            '<span class="hamburger-bar"></span>' +
            '</button>'
        );
        $('body').append($overlay);

        var $closeBtn = $overlay.find('.mobile-menu-close');
        var lastFocusedBeforeOpen = null;

        function getFocusable() {
            return $overlay.find('button, a[href]').filter(':visible');
        }

        function trapKeydown(e) {
            if (e.key !== 'Tab') return;
            var $focusable = getFocusable();
            if (!$focusable.length) return;
            var first = $focusable.first()[0];
            var last = $focusable.last()[0];
            var active = document.activeElement;
            if (e.shiftKey && active === first) {
                e.preventDefault();
                last.focus();
            } else if (!e.shiftKey && active === last) {
                e.preventDefault();
                first.focus();
            }
        }

        // Toggle menu on click
        $('.menu-toggle').on('click', function(e) {
            e.stopPropagation();
            lastFocusedBeforeOpen = document.activeElement;
            $overlay.addClass('active');
            $overlay.attr('aria-hidden', 'false');
            $(this).attr('aria-expanded', 'true');
            $('body').addClass('menu-open');
            $overlay.on('keydown', trapKeydown);
            // Move focus into the modal
            setTimeout(function() {
                $closeBtn.focus();
            }, 0);
        });

        // Close overlay
        function closeMenu() {
            $overlay.removeClass('active');
            $overlay.attr('aria-hidden', 'true');
            $('.menu-toggle').attr('aria-expanded', 'false');
            $('body').removeClass('menu-open');
            $overlay.off('keydown', trapKeydown);
            // Restore focus to the toggle (or last focused element if still in DOM)
            if (lastFocusedBeforeOpen && document.body.contains(lastFocusedBeforeOpen)) {
                lastFocusedBeforeOpen.focus();
            } else {
                $('.menu-toggle').focus();
            }
        }

        $overlay.on('click', '.mobile-menu-close', closeMenu);
        $overlay.on('click', 'a', closeMenu);

        // Close menu on Escape key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $overlay.hasClass('active')) {
                closeMenu();
            }
        });
    }

    /**
     * Dropdown menu accessibility
     */
    function initDropdownMenus() {
        // Add aria attributes for accessibility
        $('.main-navigation .menu-item-has-children > a').each(function() {
            $(this).attr('aria-haspopup', 'true');
            $(this).attr('aria-expanded', 'false');
        });

        // Toggle dropdown on touch devices
        $('.main-navigation .menu-item-has-children > a').on('touchstart', function(e) {
            var $parent = $(this).parent();

            // If submenu is already open, follow the link
            if ($parent.hasClass('focus')) {
                return true;
            }

            // Otherwise open the submenu
            e.preventDefault();

            // Close other open menus
            $('.main-navigation .menu-item-has-children').removeClass('focus');

            // Open this menu
            $parent.addClass('focus');
            $(this).attr('aria-expanded', 'true');
        });

        // Close dropdown when clicking outside
        $(document).on('click touchstart', function(e) {
            if (!$(e.target).closest('.main-navigation').length) {
                $('.main-navigation .menu-item-has-children').removeClass('focus');
                $('.main-navigation .menu-item-has-children > a').attr('aria-expanded', 'false');
            }
        });

        // Keyboard navigation
        $('.main-navigation a').on('keydown', function(e) {
            var $this = $(this);
            var $parent = $this.parent();

            // Arrow down - open submenu
            if (e.which === 40 && $parent.hasClass('menu-item-has-children')) {
                e.preventDefault();
                $parent.addClass('focus');
                $this.attr('aria-expanded', 'true');
                $parent.find('ul > li:first-child > a').focus();
            }

            // Arrow up - close submenu
            if (e.which === 38 && $parent.parent().hasClass('sub-menu')) {
                e.preventDefault();
                $parent.parent().parent().removeClass('focus');
                $parent.parent().parent().children('a').attr('aria-expanded', 'false').focus();
            }

            // Escape - close all menus
            if (e.which === 27) {
                $('.main-navigation .menu-item-has-children').removeClass('focus');
                $('.main-navigation .menu-item-has-children > a').attr('aria-expanded', 'false');
            }
        });
    }

    /**
     * Tabs functionality for location pages
     */
    function initTabs() {
        $('.cm2-tab-btn').on('click', function(e) {
            e.preventDefault();

            var $this = $(this);
            var tab = $this.data('tab');

            // Remove active class from all tabs and content
            $('.cm2-tab-btn').removeClass('active');
            $('.cm2-tab-content').removeClass('active');

            // Add active class to clicked tab and corresponding content
            $this.addClass('active');
            $('.cm2-tab-' + tab).addClass('active');

            // Scroll to tabs on mobile
            if ($(window).width() < 768) {
                $('html, body').animate({
                    scrollTop: $('.cm2-location-tabs').offset().top - 80
                }, 300);
            }
        });
    }

    /**
     * Smooth scroll for anchor links
     */
    function initSmoothScroll() {
        $('a[href*="#"]').not('[href="#"]').not('[href="#0"]').not('.skip-link').on('click', function(e) {
            if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') &&
                location.hostname === this.hostname) {

                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

                if (target.length) {
                    e.preventDefault();
                    $('html, body').animate({
                        scrollTop: target.offset().top - 80
                    }, 500);
                }
            }
        });
    }

    /**
     * Skip link: move focus to the main content target
     */
    function initSkipLinkFocus() {
        $('.skip-link').on('click', function() {
            var target = document.getElementById(this.hash.slice(1));
            if (target) {
                target.focus();
            }
        });
    }

    /**
     * Add 'scrolled' class to header on scroll
     */
    function initScrollHeader() {
        $(window).on('scroll', function() {
            if ($(window).scrollTop() > 50) {
                $('.site-header').addClass('scrolled');
            } else {
                $('.site-header').removeClass('scrolled');
            }
        });
    }

    /**
     * Lazy load images
     */
    function initLazyLoad() {
        if ('loading' in HTMLImageElement.prototype) {
            // Native lazy loading supported
            $('img[data-src]').each(function() {
                $(this).attr('src', $(this).data('src')).removeAttr('data-src');
            });
        } else {
            // Fallback for browsers that don't support native lazy loading
            var lazyImages = document.querySelectorAll('img[data-src]');

            if ('IntersectionObserver' in window) {
                var imageObserver = new IntersectionObserver(function(entries) {
                    entries.forEach(function(entry) {
                        if (entry.isIntersecting) {
                            var img = entry.target;
                            img.src = img.dataset.src;
                            img.removeAttribute('data-src');
                            imageObserver.unobserve(img);
                        }
                    });
                });

                lazyImages.forEach(function(img) {
                    imageObserver.observe(img);
                });
            } else {
                // Fallback for very old browsers
                lazyImages.forEach(function(img) {
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                });
            }
        }
    }

    /**
     * Form validation enhancement
     */
    function initFormValidation() {
        $('.cm2-contact-form, .contact-form').on('submit', function(e) {
            var $form = $(this);
            var isValid = true;

            // Remove previous error messages
            $form.find('.field-error').remove();

            // Validate required fields
            $form.find('[required]').each(function() {
                var $field = $(this);
                var value = $field.val().trim();

                if (!value) {
                    isValid = false;
                    $field.addClass('error');
                    $field.after('<span class="field-error">' + (chaletMontagneData.requiredField || 'Ce champ est requis') + '</span>');
                } else {
                    $field.removeClass('error');
                }
            });

            // Validate email
            $form.find('input[type="email"]').each(function() {
                var $field = $(this);
                var email = $field.val().trim();
                var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

                if (email && !emailPattern.test(email)) {
                    isValid = false;
                    $field.addClass('error');
                    $field.after('<span class="field-error">' + (chaletMontagneData.invalidEmail || 'Email invalide') + '</span>');
                }
            });

            if (!isValid) {
                e.preventDefault();
                // Scroll to first error
                $('html, body').animate({
                    scrollTop: $form.find('.error').first().offset().top - 100
                }, 300);
            }
        });

        // Remove error on input
        $(document).on('input', '.error', function() {
            $(this).removeClass('error').next('.field-error').remove();
        });
    }

    /**
     * Gallery lightbox enhancement (if using native WordPress gallery)
     */
    function initGalleryEnhancement() {
        $('.cm2-location-gallery a, .gallery a').attr('data-lightbox', 'gallery');
    }

    /**
     * Back to top button
     */
    function initBackToTop() {
        // Create back to top button
        if (!$('#back-to-top').length) {
            $('body').append('<button id="back-to-top" class="back-to-top" aria-label="' + (window.chaletMontagneData && chaletMontagneData.backToTop || 'Back to top') + '"><span>↑</span></button>');
        }

        $(window).on('scroll', function() {
            if ($(window).scrollTop() > 300) {
                $('#back-to-top').addClass('show');
            } else {
                $('#back-to-top').removeClass('show');
            }
        });

        $(document).on('click', '#back-to-top', function(e) {
            e.preventDefault();
            $('html, body').animate({ scrollTop: 0 }, 500);
        });
    }

    /**
     * Simple scroll animations
     */
    function initScrollAnimations() {
        // Add fade-in effect to elements as they come into view
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('fade-in-up');
                    observer.unobserve(entry.target);
                }
            });
        }, observerOptions);

        // Observe elements
        $('.entry-content > *:not(script):not(style)').each(function() {
            observer.observe(this);
        });

        $('.cm2-location-card, .widget, .footer-widget').each(function() {
            observer.observe(this);
        });
    }

    /**
     * Add loading state to header on page load
     */
    function initHeaderAnimation() {
        $('.site-header').css('transform', 'translateY(-100%)');
        setTimeout(function() {
            $('.site-header').css({
                'transform': 'translateY(0)',
                'transition': 'transform 0.5s ease-out'
            });
        }, 100);
    }

    /**
     * Initialize all functions
     */
    $(document).ready(function() {
        initMobileMenu();
        initDropdownMenus();
        initTabs();
        initSmoothScroll();
        initSkipLinkFocus();
        initScrollHeader();
        initLazyLoad();
        initFormValidation();
        initGalleryEnhancement();
        initBackToTop();
        initScrollAnimations();
        initHeaderAnimation();
    });

})(jQuery);
