/* ========================
   FICHIER : custom.js
   VERSION AMELIOREE PAR EXPERT UI DESIGNER
   Description :
   Optimisation du code pour les performances, accessibilité 
   et modélisation modulaire. 
   ======================== */

document.addEventListener('DOMContentLoaded', () => {
    /* ========================
       Navigation Mobile Toggle
    ======================== */
    const initMobileMenu = () => {
        const mobileMenuButton = document.querySelector('.mobile-menu-button');
        const navList = document.querySelector('.nav-list');

        if (mobileMenuButton && navList) {
            mobileMenuButton.addEventListener('click', () => {
                navList.classList.toggle('active');
                mobileMenuButton.setAttribute('aria-expanded', navList.classList.contains('active'));
            });

            // Gestion du clavier pour l'accessibilité
            mobileMenuButton.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    navList.classList.toggle('active');
                    mobileMenuButton.setAttribute('aria-expanded', navList.classList.contains('active'));
                }
            });

            // Fermer le menu lorsque l'utilisateur clique en dehors
            document.addEventListener('click', (e) => {
                if (!mobileMenuButton.contains(e.target) && !navList.contains(e.target)) {
                    navList.classList.remove('active');
                    mobileMenuButton.setAttribute('aria-expanded', 'false');
                }
            });
        }
    };

    /* ========================
       Smooth Scrolling pour les ancres
    ======================== */
    const initSmoothScrolling = () => {
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', (e) => {
                e.preventDefault();
                const target = document.querySelector(anchor.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            });
        });
    };

    /* ========================
       Header Scroll Effect
    ======================== */
    const initHeaderScroll = () => {
        const header = document.querySelector('.layout-header');
        let lastScroll = 0;

        window.addEventListener('scroll', () => {
            const currentScroll = window.pageYOffset;
            if (currentScroll <= 0) {
                header.classList.remove('scroll-up');
                header.classList.remove('scroll-shadow');
                return;
            }

            header.classList.toggle('scroll-down', currentScroll > lastScroll);
            header.classList.toggle('scroll-up', currentScroll < lastScroll);
            header.classList.add('scroll-shadow');
            lastScroll = currentScroll;
        });
    };

    /* ========================
       Intersection Observer Animations
    ======================== */
    const initAnimationsOnScroll = () => {
        const elements = document.querySelectorAll('.animate-on-scroll');
        const observerOptions = { threshold: 0.1 };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animated');
                    observer.unobserve(entry.target);
                }
            });
        }, observerOptions);

        elements.forEach(element => observer.observe(element));
    };

    /* ========================
       Form Validation
    ======================== */
    const initFormValidation = () => {
        const forms = document.querySelectorAll('form');

        const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

        const validateInput = (input) => {
            const errorElement = input.parentElement.querySelector('.error-message') || document.createElement('span');
            errorElement.className = 'error-message';

            if (!input.value && input.hasAttribute('required')) {
                errorElement.textContent = 'Ce champ est requis';
            } else if (input.type === 'email' && !validateEmail(input.value)) {
                errorElement.textContent = 'Email invalide';
            } else {
                errorElement.textContent = '';
            }

            if (!input.parentElement.contains(errorElement)) {
                input.parentElement.appendChild(errorElement);
            }
        };

        forms.forEach(form => {
            form.querySelectorAll('input, textarea').forEach(input => {
                input.addEventListener('input', () => validateInput(input));
                input.addEventListener('blur', () => validateInput(input));
            });
        });
    };

    /* ========================
       Boutons Loading State
    ======================== */
    const initLoadingButtons = () => {
        document.querySelectorAll('.loading-button').forEach(button => {
            button.addEventListener('click', () => {
                if (!button.classList.contains('loading')) {
                    button.classList.add('loading');
                    button.disabled = true;
                    button.dataset.originalText = button.textContent;
                    button.textContent = 'Chargement...';

                    setTimeout(() => {
                        button.classList.remove('loading');
                        button.disabled = false;
                        button.textContent = button.dataset.originalText;
                    }, 2000);
                }
            });
        });
    };

    /* ========================
       Lazy Loading d'Images
    ======================== */
    const initLazyLoading = () => {
        const images = document.querySelectorAll('img[data-src]');
        const observerOptions = { threshold: 0.5 };

        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.src = entry.target.dataset.src;
                    observer.unobserve(entry.target);
                }
            });
        }, observerOptions);

        images.forEach(img => imageObserver.observe(img));
    };

    /* ========================
       Service Worker (PWA)
    ======================== */
    const initServiceWorker = () => {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js')
                .then(() => console.log('Service Worker enregistré avec succès'))
                .catch(err => console.error('Erreur Service Worker :', err));
        }
    };

    /* ========================
       INITIALISATION DES FONCTIONS
    ======================== */
    initMobileMenu();
    initSmoothScrolling();
    initHeaderScroll();
    initAnimationsOnScroll();
    initFormValidation();
    initLoadingButtons();
    initLazyLoading();
    initServiceWorker();
});