/**
 * Main Theme JavaScript Actions
 *
 * @package Theme_An_Phat
 */

document.addEventListener('DOMContentLoaded', function () {
    // --- 1. MOBILE MENU TOGGLE ---
    const menuToggle = document.querySelector('.menu-toggle');
    const mobileNavigation = document.getElementById('mobile-navigation');

    if (menuToggle && mobileNavigation) {
        menuToggle.addEventListener('click', function () {
            const expanded = menuToggle.getAttribute('aria-expanded') === 'true' || false;
            menuToggle.setAttribute('aria-expanded', !expanded);

            if (!expanded) {
                mobileNavigation.style.display = 'block';
                menuToggle.innerHTML = '<i class="fa-solid fa-xmark fa-lg"></i>';
            } else {
                mobileNavigation.style.display = 'none';
                menuToggle.innerHTML = '<i class="fa-solid fa-bars fa-lg"></i>';
            }
        });
    }

    // Close mobile menu when resizing to desktop
    window.addEventListener('resize', function () {
        if (window.innerWidth >= 992 && mobileNavigation) {
            mobileNavigation.style.display = 'none';
            if (menuToggle) {
                menuToggle.setAttribute('aria-expanded', 'false');
                menuToggle.innerHTML = '<i class="fa-solid fa-bars fa-lg"></i>';
            }
        }
    });


    // --- 2. SCROLL REVEAL ANIMATION (Intersection Observer) ---
    const revealElements = document.querySelectorAll('.scroll-reveal, .scroll-reveal-right');

    if ('IntersectionObserver' in window && revealElements.length > 0) {
        const revealObserver = new IntersectionObserver(function (entries, observer) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('scroll-reveal-active');
                    revealObserver.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.15,
            rootMargin: '0px 0px -50px 0px'
        });

        revealElements.forEach(function (el) {
            revealObserver.observe(el);
        });
    } else {
        // Fallback for older browsers
        revealElements.forEach(function (el) {
            el.classList.add('scroll-reveal-active');
        });
    }


    // --- 3. CUSTOM BOOTSTRAP-LIKE TAB SWITCHER FOR PARTNERS ---
    const tabButtons = document.querySelectorAll('#partnerTab button');
    const tabPanes = document.querySelectorAll('#partnerTabContent .tab-pane');

    if (tabButtons.length > 0 && tabPanes.length > 0) {
        tabButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                // Remove active classes
                tabButtons.forEach(btn => btn.classList.remove('active'));
                tabPanes.forEach(pane => {
                    pane.classList.remove('show', 'active');
                });

                // Add active state to clicked tab
                button.classList.add('active');
                const targetId = button.getAttribute('data-bs-target');
                const targetPane = document.querySelector(targetId);
                if (targetPane) {
                    targetPane.classList.add('show', 'active');
                }
            });
        });
    }


    // --- 4. AJAX FORM SUBMISSIONS ---

    // Utility: Show alerts
    function showFormAlert(form, type, message) {
        // Remove existing alert
        const existingAlert = form.querySelector('.form-submission-alert');
        if (existingAlert) {
            existingAlert.remove();
        }

        // Create alert box
        const alertBox = document.createElement('div');
        alertBox.className = `form-submission-alert p-3 rounded-3 mb-3 text-sm font-heading ${
            type === 'success' ? 'bg-success text-white' : 'bg-danger text-white'
        }`;
        alertBox.style.marginTop = '1rem';
        alertBox.innerHTML = `<i class="fa-solid ${type === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation'} me-2"></i> ${message}`;

        form.insertBefore(alertBox, form.firstChild);

        // Auto scroll to top of form to see the alert
        form.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    // Form 1: Contact Form
    const contactForm = document.getElementById('contact-form');
    if (contactForm) {
        contactForm.addEventListener('submit', function (e) {
            e.preventDefault();

            const submitBtn = contactForm.querySelector('button[type="submit"]');
            const originalBtnHtml = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i>Đang gửi...';

            const formData = new FormData(contactForm);
            formData.append('action', 'submit_contact_form');
            formData.append('nonce', anphat_ajax.nonce);

            fetch(anphat_ajax.ajax_url, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnHtml;

                if (data.success) {
                    showFormAlert(contactForm, 'success', data.data.message);
                    contactForm.reset();
                } else {
                    showFormAlert(contactForm, 'error', data.data.message || 'Đã xảy ra lỗi, vui lòng thử lại.');
                }
            })
            .catch(error => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnHtml;
                showFormAlert(contactForm, 'error', 'Không thể kết nối máy chủ. Vui lòng thử lại sau.');
            });
        });
    }

    // Form 2: Pharmacovigilance (Cảnh giác dược - ADR Report)
    const adrForm = document.getElementById('adr-report-form');
    if (adrForm) {
        adrForm.addEventListener('submit', function (e) {
            e.preventDefault();

            const submitBtn = adrForm.querySelector('button[type="submit"]');
            const originalBtnHtml = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i>Đang gửi báo cáo...';

            const formData = new FormData(adrForm);
            formData.append('action', 'submit_adr_report');
            formData.append('nonce', anphat_ajax.nonce);

            fetch(anphat_ajax.ajax_url, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnHtml;

                if (data.success) {
                    showFormAlert(adrForm, 'success', data.data.message);
                    adrForm.reset();
                } else {
                    showFormAlert(adrForm, 'error', data.data.message || 'Đã xảy ra lỗi, vui lòng thử lại.');
                }
            })
            .catch(error => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnHtml;
                showFormAlert(adrForm, 'error', 'Không thể kết nối máy chủ. Vui lòng thử lại sau.');
            });
        });
    }

    // Form 3: Job Application Form (Tuyển dụng)
    const jobForm = document.getElementById('job-application-form');
    if (jobForm) {
        jobForm.addEventListener('submit', function (e) {
            e.preventDefault();

            const submitBtn = jobForm.querySelector('button[type="submit"]');
            const originalBtnHtml = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i>Đang nộp hồ sơ...';

            const formData = new FormData(jobForm);
            formData.append('action', 'submit_job_application');
            formData.append('nonce', anphat_ajax.nonce);

            fetch(anphat_ajax.ajax_url, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnHtml;

                if (data.success) {
                    showFormAlert(jobForm, 'success', data.data.message);
                    jobForm.reset();
                } else {
                    showFormAlert(jobForm, 'error', data.data.message || 'Đã xảy ra lỗi, vui lòng thử lại.');
                }
            })
            .catch(error => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnHtml;
                showFormAlert(jobForm, 'error', 'Không thể gửi hồ sơ. Vui lòng kiểm tra định dạng/kích thước CV của bạn.');
            });
        });
    }


    // --- 5. AJAX PRODUCT FILTERING & SEARCH ---
    const filterButtons = document.querySelectorAll('.product-filter-btn');
    const searchInput = document.getElementById('product-search');
    const productGrid = document.getElementById('product-archive-grid');

    if (productGrid) {
        let currentFilter = '';
        let currentSearch = '';

        function fetchProducts() {
            productGrid.style.opacity = '0.5';
            
            const params = new URLSearchParams();
            params.append('action', 'filter_products');
            if (currentFilter) params.append('category', currentFilter);
            if (currentSearch) params.append('search', currentSearch);

            // Fetch request to AJAX endpoint
            fetch(anphat_ajax.ajax_url + '?' + params.toString())
            .then(response => response.text())
            .then(html => {
                productGrid.innerHTML = html;
                productGrid.style.opacity = '1';
            })
            .catch(err => {
                productGrid.style.opacity = '1';
                productGrid.innerHTML = '<div class="col-12 text-center py-5 text-danger"><p>Lỗi tải dữ liệu sản phẩm. Vui lòng tải lại trang.</p></div>';
            });
        }

        // Category Filter buttons
        if (filterButtons.length > 0) {
            filterButtons.forEach(btn => {
                btn.addEventListener('click', function () {
                    filterButtons.forEach(b => b.classList.remove('btn-primary'));
                    filterButtons.forEach(b => b.classList.add('btn-outline-primary'));

                    btn.classList.remove('btn-outline-primary');
                    btn.classList.add('btn-primary');

                    currentFilter = btn.getAttribute('data-category');
                    fetchProducts();
                });
            });
        }

        // Search Input
        if (searchInput) {
            let debounceTimer;
            searchInput.addEventListener('input', function () {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(() => {
                    currentSearch = searchInput.value.trim();
                    fetchProducts();
                }, 400); // Debounce
            });
        }
    }

    // --- 6. SWIPER SLIDER INIT ---
    const productSlider = document.querySelector('.product-slider');
    if (productSlider && typeof Swiper !== 'undefined') {
        new Swiper('.product-slider', {
            slidesPerView: 1,
            spaceBetween: 20,
            loop: true,
            autoplay: {
                delay: 3500,
                disableOnInteraction: false,
            },
            navigation: {
                nextEl: '.featured-products-next',
                prevEl: '.featured-products-prev',
            },
            breakpoints: {
                576: {
                    slidesPerView: 2,
                    spaceBetween: 20,
                },
                992: {
                    slidesPerView: 4,
                    spaceBetween: 16,
                },
                1200: {
                    slidesPerView: 4,
                    spaceBetween: 18,
                }
            }
        });
    }
});
