document.addEventListener('DOMContentLoaded', function () {
    const galleries = document.querySelectorAll('.awt-book-gallery');

    galleries.forEach(gallery => {
        const filterContainer = gallery.querySelector('.awt-book-filters');
        const bookGrid = gallery.querySelector('.awt-book-grid-container');
        const paginationContainer = gallery.querySelector('.awt-pagination');
        const resultCount = gallery.querySelector('.awt-files-result-count');
        const sortSelect = gallery.querySelector('.awt-sort-books');
        const applyBtn = gallery.querySelector('.awt-apply-filters');
        const resetBtn = gallery.querySelector('.awt-reset-filters');

        // Config
        const ajaxUrlInput = gallery.querySelector('#awt-ajax-url') || document.getElementById('awt-ajax-url') || gallery.querySelector('input[id*="awt-ajax-url"]');
        // Fallback for ajax URL if it was converted to class or kept as ID but we need to find it. 
        // In render.php we kept id="awt-ajax-url" but it's hidden input. Since ID must be unique, we should have changed it to class or scoped it. 
        // Checking render.php from previous step: <input type="hidden" id="awt-items-per-page" ...> was changed to class="awt-items-per-page".
        // But <input type="hidden" id="awt-ajax-url" ...> was NOT changed in the multi_replace_file_content.
        // Wait, I should check if I missed that. 
        // In the previous multi_replace, I changed `awt-items-per-page` to class. I did NOT change `awt-ajax-url`.
        // This means if multiple blocks exist, there will strictly be duplicate IDs for `awt-ajax-url`. 
        // However, usually they all contain the same URL. So `document.getElementById` is fine for the URL if they are all identical.
        // BUT `itemsPerPage` can be different per block.

        // Let's assume ajaxUrl is same for all manually or find the first one.
        const ajaxUrl = document.getElementById('awt-ajax-url') ? document.getElementById('awt-ajax-url').value : '/wp-admin/admin-ajax.php';

        const itemsPerPageInput = gallery.querySelector('.awt-items-per-page');
        const itemsPerPage = itemsPerPageInput ? itemsPerPageInput.value : 12;

        // Mobile Filter Logic
        const mobileToggle = gallery.querySelector('#awt-mobile-filter-toggle');
        const mobileClose = gallery.querySelector('#awt-mobile-filter-close');
        const filterBackdrop = gallery.querySelector('#awt-filter-backdrop'); // In render.php we used ID but if multiple blocks, IDs duplicate. 
        // We should select by closest to gallery to handle potential duplicates if ID was reused, though ID *should* be unique. 
        // Given structure: toggle and backdrop are siblings in a wrapper inside gallery.

        function openDrawer() {
            if (filterContainer) {
                filterContainer.classList.remove('-translate-x-full');
                if (filterBackdrop) filterBackdrop.classList.remove('hidden');
                document.body.style.overflow = 'hidden';
            }
        }

        function closeDrawer() {
            if (filterContainer) {
                filterContainer.classList.add('-translate-x-full');
                if (filterBackdrop) filterBackdrop.classList.add('hidden');
                document.body.style.overflow = '';
            }
        }

        if (mobileToggle) {
            mobileToggle.addEventListener('click', (e) => {
                e.preventDefault();
                openDrawer();
            });
        }

        if (mobileClose) {
            mobileClose.addEventListener('click', (e) => {
                e.preventDefault();
                closeDrawer();
            });
        }

        if (filterBackdrop) {
            filterBackdrop.addEventListener('click', closeDrawer);
        }

        if (!bookGrid) return;

        // Custom Dropdown Logic
        const dropdowns = gallery.querySelectorAll('.awt-custom-dropdown');
        dropdowns.forEach(dropdown => {
            const trigger = dropdown.querySelector('.awt-dropdown-trigger');
            const content = dropdown.querySelector('.awt-dropdown-content');
            const icon = dropdown.querySelector('.dropdown-icon') || dropdown.querySelector('svg'); // Fallback
            const search = dropdown.querySelector('.awt-dropdown-search');
            const labelSpan = dropdown.querySelector('.select-label');
            const checkboxes = dropdown.querySelectorAll('input[type="checkbox"]');

            // Get Label text (e.g. "Genres") from the header label
            const headerLabel = dropdown.querySelector('label.block');
            const labelText = headerLabel ? headerLabel.textContent.trim() : 'Option';

            // Initial Icon State (Collapsed = Point Down = Rotate 180 if icon is Up Chevron)
            if (icon) icon.style.transform = 'rotate(180deg)';

            const updateLabel = () => {
                const checked = Array.from(checkboxes).filter(c => c.checked);
                if (checked.length === 0) {
                    labelSpan.textContent = `Select ${labelText}`;
                    labelSpan.classList.add('text-secondary');
                    labelSpan.classList.remove('text-primary');
                } else if (checked.length === 1) {
                    // Use data-label if available, else value
                    let name = checked[0].getAttribute('data-label') || checked[0].value;
                    labelSpan.textContent = name;
                    labelSpan.classList.remove('text-secondary');
                    labelSpan.classList.add('text-primary');
                } else {
                    labelSpan.textContent = `${labelText} (${checked.length})`;
                    labelSpan.classList.remove('text-secondary');
                    labelSpan.classList.add('text-primary');
                }
            };

            // Bind Checkbox Change
            checkboxes.forEach(cb => cb.addEventListener('change', updateLabel));

            // Toggle
            trigger.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();

                // Close other dropdowns in this gallery
                dropdowns.forEach(d => {
                    if (d !== dropdown) {
                        const c = d.querySelector('.awt-dropdown-content');
                        const i = d.querySelector('.dropdown-icon') || d.querySelector('svg');
                        if (c) c.classList.add('hidden');
                        if (i) i.style.transform = 'rotate(180deg)';
                    }
                });

                content.classList.toggle('hidden');

                // Rotate Icon
                if (icon) {
                    // Hidden = Collapsed = 180deg
                    // Visible = Expanded = 0deg
                    icon.style.transform = content.classList.contains('hidden') ? 'rotate(180deg)' : 'rotate(0deg)';
                }

                // Focus Search
                if (!content.classList.contains('hidden') && search) {
                    setTimeout(() => search.focus(), 50);
                }
            });

            // Search Filter
            if (search) {
                search.addEventListener('input', (e) => {
                    const term = e.target.value.toLowerCase();
                    const items = dropdown.querySelectorAll('.awt-dropdown-list label');
                    items.forEach(item => {
                        const text = item.textContent.toLowerCase();
                        item.style.display = text.includes(term) ? 'flex' : 'none';
                    });
                });
            }
        });

        // Close on Outside Click (Scoped to Document but handles this gallery's dropdowns)
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.awt-custom-dropdown')) {
                dropdowns.forEach(d => {
                    const c = d.querySelector('.awt-dropdown-content');
                    const i = d.querySelector('.dropdown-icon') || d.querySelector('svg');
                    if (c && !c.classList.contains('hidden')) {
                        c.classList.add('hidden');
                        if (i) i.style.transform = 'rotate(180deg)';
                    }
                });
            }
        });

        // Accordion Logic (Legacy for Price, Rating etc)
        if (filterContainer) {
            const triggers = filterContainer.querySelectorAll('.awt-accordion-trigger');
            triggers.forEach(trigger => {
                trigger.addEventListener('click', () => {
                    const content = trigger.nextElementSibling;
                    const icon = trigger.querySelector('svg');

                    content.classList.toggle('hidden');
                    if (icon) {
                        icon.style.transform = content.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
                        // Note: Legacy accordion icons might behave differently (Up vs Down default). 
                        // Existing code was: visible ? 0 : 180. 
                        // Original code said: const icon_chevron_up. 
                        // Original JS: hidden ? 180 : 0.  (Collapsed = 180/Down).
                        // So I will stick to that logic to match legacy.
                        icon.style.transform = content.classList.contains('hidden') ? 'rotate(180deg)' : 'rotate(0deg)';
                    }
                });
            });
        }

        const loadMoreBtn = gallery.querySelector('#awt-load-more-btn');

        // Filtering Function
        function fetchBooks(page = 1, append = false) {
            // Collect Data - Scope to THIS gallery
            const searchInput = gallery.querySelector('.awt-filter-search');
            const search = searchInput ? searchInput.value : '';

            const genreInputs = gallery.querySelectorAll('input[name="genre[]"]:checked');
            const genres = Array.from(genreInputs).map(cb => cb.value);

            const authorInputs = gallery.querySelectorAll('input[name="author[]"]:checked');
            const authors = Array.from(authorInputs).map(cb => cb.value);

            const seriesInputs = gallery.querySelectorAll('input[name="series[]"]:checked');
            const series = Array.from(seriesInputs).map(cb => cb.value);

            const formatInputs = gallery.querySelectorAll('input[name="format[]"]:checked');
            const formats = Array.from(formatInputs).map(cb => cb.value);

            const langInputs = gallery.querySelectorAll('input[name="language[]"]:checked');
            const languages = Array.from(langInputs).map(cb => cb.value);

            const pubInputs = gallery.querySelectorAll('input[name="publisher[]"]:checked');
            const publishers = Array.from(pubInputs).map(cb => cb.value);

            const yearInputs = gallery.querySelectorAll('input[name="year[]"]:checked');
            const years = Array.from(yearInputs).map(cb => cb.value);

            const ageInputs = gallery.querySelectorAll('input[name="age[]"]:checked');
            const ages = Array.from(ageInputs).map(cb => cb.value);

            const ratingInputs = gallery.querySelectorAll('input[name="rating[]"]:checked');
            const ratings = Array.from(ratingInputs).map(cb => cb.value);

            const isbnInput = gallery.querySelector('.awt-filter-isbn');
            const isbn = isbnInput ? isbnInput.value : '';

            // Price - now multi-select
            const priceInputs = gallery.querySelectorAll('input[name="price[]"]:checked');
            const prices = Array.from(priceInputs).map(cb => cb.value);

            const sort = sortSelect ? sortSelect.value : 'date_desc';

            // Visual Loading State
            if (!append) bookGrid.style.opacity = '0.5';
            if (loadMoreBtn && append) loadMoreBtn.textContent = 'Loading...';

            const data = new URLSearchParams();
            data.append('action', 'awt_filter_books');
            data.append('search', search);
            data.append('genres', genres.join(','));
            data.append('authors', authors.join(','));
            data.append('series', series.join(','));

            data.append('formats', formats.join(','));
            data.append('languages', languages.join(','));
            data.append('publishers', publishers.join(','));
            data.append('isbn', isbn);
            data.append('years', years.join(','));
            data.append('ages', ages.join(','));
            data.append('ratings', ratings.join(','));

            data.append('price', prices.join(','));
            data.append('sort', sort);
            data.append('page', page);
            data.append('items_per_page', itemsPerPage);

            // Pagination Type
            const paginationTypeInput = gallery.querySelector('.awt-pagination-type');
            const paginationType = paginationTypeInput ? paginationTypeInput.value : 'numbers';
            data.append('pagination_type', paginationType);

            // Context
            const currentTaxInput = gallery.querySelector('#awt-current-tax') || document.getElementById('awt-current-tax');
            const currentTermInput = gallery.querySelector('#awt-current-term') || document.getElementById('awt-current-term');
            if (currentTaxInput && currentTermInput) {
                data.append('current_tax', currentTaxInput.value);
                data.append('current_term', currentTermInput.value);
            }

            fetch(ajaxUrl, {
                method: 'POST',
                body: data
            })
                .then(response => response.json())
                .then(response => { // Changed variable name to 'response' for clarity
                    if (response.success) {
                        // Extract the actual data payload
                        const data = response.data;

                        // HTML Update Logic
                        if (append) {
                            bookGrid.insertAdjacentHTML('beforeend', data.html);
                        } else {
                            bookGrid.innerHTML = data.html;
                        }

                        // Pagination Handling
                        if (paginationType === 'load_more') {
                            if (loadMoreBtn) {
                                const maxPages = data.max_pages || 1;

                                // Handling Filter Reset (Not Append)
                                if (!append) {
                                    loadMoreBtn.textContent = 'Load More Books';
                                    loadMoreBtn.setAttribute('data-page', 1);
                                }

                                // Visibility Check
                                if (page >= maxPages) {
                                    loadMoreBtn.style.display = 'none';
                                } else {
                                    loadMoreBtn.style.display = 'inline-block';
                                    loadMoreBtn.setAttribute('data-page', page);
                                    // UX Fix: Reset button text
                                    loadMoreBtn.textContent = 'Load More Books';
                                }
                            }
                        } else {
                            // Numeric
                            if (paginationContainer) paginationContainer.innerHTML = data.pagination;
                        }

                        // Update count text logic
                        const total = data.count;
                        const start = 1; // Always start from 1 visually if appending? No, if paging. 
                        // Actually count text logic:
                        // If append (Load More), we are showing 1 to (page * itemsPerPage).
                        // If numeric, we are showing ((page-1)*items+1) to (page*items).

                        let endCount = Math.min(page * itemsPerPage, total);
                        let startCount = (page - 1) * itemsPerPage + 1;

                        if (loadMoreBtn) {
                            // Context of Load More: We show ALL loaded so far? Or just "Showing X - Y"?
                            // Usually "Showing 1 - Y".
                            startCount = 1;
                        }

                        if (resultCount) {
                            resultCount.innerHTML = `Showing <span class="font-bold text-primary">${total > 0 ? startCount : 0} - ${endCount}</span> of <span class="font-bold text-primary">${total}</span> Results`;
                        }

                    } else {
                        if (!append) bookGrid.innerHTML = '<p class="text-center col-span-3 text-gray-500">Error loading books.</p>';
                    }
                    bookGrid.style.opacity = '1';
                })
                .catch(err => {
                    console.error(err);
                    bookGrid.style.opacity = '1';
                    if (loadMoreBtn) loadMoreBtn.textContent = 'Load More Books';
                });
        }

        // Load More Listener
        if (loadMoreBtn) {
            loadMoreBtn.addEventListener('click', (e) => {
                e.preventDefault();
                const page = parseInt(loadMoreBtn.getAttribute('data-page')) || 1;
                fetchBooks(page + 1, true);
            });
        }

        // Event Listeners
        if (applyBtn) {
            applyBtn.addEventListener('click', () => {
                fetchBooks(1);
                closeDrawer();
            });
        }

        if (resetBtn) {
            resetBtn.addEventListener('click', () => {
                const sInput = gallery.querySelector('.awt-filter-search');
                if (sInput) sInput.value = '';

                const iInput = gallery.querySelector('.awt-filter-isbn');
                if (iInput) iInput.value = '';

                gallery.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
                // Price removed (now checkbox)

                // Fetch
                fetchBooks(1);
                closeDrawer();
            });
        }

        if (sortSelect) {
            sortSelect.addEventListener('change', () => fetchBooks(1));
        }

        // Pagination Delegation
        if (paginationContainer) {
            paginationContainer.addEventListener('click', (e) => {
                const btn = e.target.closest('.awt-page-link');
                if (btn) {
                    e.preventDefault();
                    const page = btn.getAttribute('data-page');
                    fetchBooks(page);
                }
            });
        }
    });
    // ===============================================
    // NEW CODE HERE (WooCommerce Button Animation)
    // ===============================================
    if (typeof jQuery !== 'undefined') {
        jQuery(document.body).on('added_to_cart', function (event, fragments, cart_hash, $button) {

            // ফিক্স: বাটনটি DOM এ আসার জন্য ৫০ms অপেক্ষা করা
            setTimeout(function () {
                // jQuery অবজেক্ট থেকে Vanilla JS নোড বের করা
                const button = $button && $button[0] ? $button[0] : null;

                if (button) {
                    // ১. র‍্যাপার খোঁজা
                    const wrapper = button.closest('.rswpbs-book-loop-btn');

                    if (wrapper) {
                        // ২. 'View Cart' বাটন খোঁজা
                        const viewCartBtn = wrapper.querySelector('.added_to_cart');

                        if (viewCartBtn) {
                            // ৩. বাটনটি শো করা
                            viewCartBtn.style.display = 'flex';
                            viewCartBtn.style.opacity = '1';

                            // ৪. ৩ সেকেন্ড পর লুকিয়ে ফেলা
                            setTimeout(() => {
                                // ফেইড আউট ইফেক্ট
                                viewCartBtn.style.transition = 'opacity 0.5s ease';
                                viewCartBtn.style.opacity = '0';

                                // ট্রানজিশন শেষ হলে ডিসপ্লে নান করা
                                setTimeout(() => {
                                    viewCartBtn.style.display = 'none';
                                    viewCartBtn.style.opacity = '1'; // রিসেট
                                    viewCartBtn.style.transition = ''; // রিসেট
                                }, 500); // 0.5s transition time

                            }, 3000); // ৩০০০ মিলিসেকন্ড = ৩ সেকেন্ড
                        } else {
                            // ডিবাগিং: যদি বাটন না পাওয়া যায়
                            console.log('View Cart button not found yet inside wrapper');
                        }
                    }
                }
            }, 50); // <-- এই ৫০ms ডিলে গুরুত্বপূর্ণ
        });
    }
});
