    document.addEventListener('DOMContentLoaded', () => {
        const sidebar = document.getElementById('sidebar');
        const menuToggle = document.getElementById('menu-toggle');
        const navLinks = document.querySelectorAll('.nav-link');
        const pages = document.querySelectorAll('.page');
        const pageTitleDisplay = document.getElementById('page-title-display');
        const mainContent = document.getElementById('main-content');

        // Desktop Search Elements
        const desktopSearchButton = document.getElementById('search-button');
        const desktopSearchInput = document.getElementById('search-input');

        // Mobile Search Elements
        const searchToggleMobileBtn = document.getElementById('search-toggle-mobile');
        const mobileSearchContainer = document.getElementById('mobile-search-container');
        const mobileSearchInput = document.getElementById('mobile-search-input');
        const mobileSearchCloseBtn = document.getElementById('mobile-search-close-btn');
        const mobileSearchExecuteBtn = document.getElementById('mobile-search-execute-btn');

        const productModal = document.getElementById('product-modal');
        const closeProductModalBtn = document.getElementById('close-product-modal');
        const addNewProductBtn = document.getElementById('add-new-product-btn');
        const productForm = document.getElementById('product-form');
        const modalTitle = document.getElementById('modal-title');
        const saveProductBtn = document.getElementById('save-product-btn');
        const cancelProductFormBtn = document.getElementById('cancel-product-form');

        if(menuToggle && sidebar) {
            menuToggle.addEventListener('click', () => sidebar.classList.toggle('open'));
        }
        if(mainContent && sidebar && menuToggle) {
            mainContent.addEventListener('click', (e) => {
                if (window.innerWidth <= 991.98 && sidebar.classList.contains('open') &&
                    !sidebar.contains(e.target) && !menuToggle.contains(e.target)) {
                    sidebar.classList.remove('open');
                }
            });
        }

        // Function to navigate to a specific page
        function navigateToPage(pageId) {
            if (!pageId) return;

            // Update URL with page parameter
            const url = new URL(window.location.href);
            url.searchParams.set('page', pageId);
            window.history.pushState({}, '', url);

            // Update active states
            pages.forEach(p => p.classList.remove('active'));
            const targetPage = document.getElementById(`${pageId}-page`);
            if(targetPage) targetPage.classList.add('active');

            navLinks.forEach(n => n.classList.remove('active'));
            const activeLink = document.querySelector(`[data-page="${pageId}"]`);
            if(activeLink) activeLink.classList.add('active');

            // Update page title
            if(pageTitleDisplay && activeLink) {
                const linkText = Array.from(activeLink.childNodes)
                    .filter(node => node.nodeType === Node.TEXT_NODE)
                    .map(node => node.textContent.trim())
                    .join('') || activeLink.textContent.trim();
                pageTitleDisplay.textContent = linkText;
            }

            // Close sidebar on mobile
            if (window.innerWidth <= 991.98 && sidebar && sidebar.classList.contains('open')) {
                sidebar.classList.remove('open');
            }

            // Load page-specific content
            if (pageId === 'product-list') {
                loadProducts();
            } else if (pageId === 'product-requests') {
                loadProductRequests();
            }
        }

        // Handle initial page load from URL parameter
        const urlParams = new URLSearchParams(window.location.search);
        const initialPage = urlParams.get('page');
        if (initialPage) {
            navigateToPage(initialPage);
        }

        // Handle browser back/forward buttons
        window.addEventListener('popstate', () => {
            const urlParams = new URLSearchParams(window.location.search);
            const page = urlParams.get('page');
            if (page) {
                navigateToPage(page);
            } else {
                navigateToPage('dashboard'); // Default to dashboard if no page parameter
            }
        });

        navLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                if (link.getAttribute('href') === 'logout.php') {
                    return;
                }
                
                e.preventDefault();
                const targetPageId = link.getAttribute('data-page');
                navigateToPage(targetPageId);
            });
        });

        // Desktop Search
        if (desktopSearchButton && desktopSearchInput) {
            desktopSearchButton.addEventListener('click', () => {
                if (desktopSearchInput.value);
            });
            desktopSearchInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') desktopSearchButton.click(); });
        }

        // Mobile Search Toggle
        if (searchToggleMobileBtn && mobileSearchContainer && mobileSearchInput) {
            searchToggleMobileBtn.addEventListener('click', () => {
                mobileSearchContainer.classList.toggle('active');
                if (mobileSearchContainer.classList.contains('active')) mobileSearchInput.focus();
            });
        }
        if (mobileSearchCloseBtn && mobileSearchContainer) {
            mobileSearchCloseBtn.addEventListener('click', () => mobileSearchContainer.classList.remove('active'));
        }
        if (mobileSearchExecuteBtn && mobileSearchInput && mobileSearchContainer) {
            mobileSearchExecuteBtn.addEventListener('click', () => {
                if (mobileSearchInput.value) {
                    alert(`Mobile Search: ${mobileSearchInput.value}`);
                    mobileSearchContainer.classList.remove('active');
                }
            });
            mobileSearchInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') mobileSearchExecuteBtn.click(); });
        }


        function openModal(type = 'add', data = null) {
            if (!productForm || !modalTitle || !saveProductBtn || !productModal) return;
            productForm.reset();
            const productIdField = document.getElementById('product-id');
            if (productIdField) productIdField.value = '';

            if (type === 'add') {
                modalTitle.textContent = 'Add New Product';
                saveProductBtn.textContent = 'Save Product';
                saveProductBtn.className = 'btn btn-primary';
                saveProductBtn.onclick = handleSaveProduct;
            } else if (type === 'edit' && data) {
                modalTitle.textContent = 'Edit Product';
                saveProductBtn.textContent = 'Update Product';
                saveProductBtn.className = 'btn btn-primary';
                saveProductBtn.onclick = handleSaveProduct;
                if (productIdField) productIdField.value = data.id;
                // ... populate other fields
            } else if (type === 'review' && data) {
                modalTitle.textContent = 'Review Product Request';
                saveProductBtn.innerHTML = '<i class="fas fa-check"></i> Approve & Add';
                saveProductBtn.className = 'btn btn-success';
                saveProductBtn.onclick = handleReviewApprove;
                if (productIdField) productIdField.value = `req-${data.id}`;
                // ... populate other fields
            }
            productModal.style.display = 'flex';

            // অ্যান্ড্রয়েড অ্যাপকে জানান যে Modal খোলা হয়েছে
            if (window.Android) {
                window.Android.onModalOpen();
            }
        }

        function closeModal() {
            if(productModal) productModal.style.display = 'none';

            // অ্যান্ড্রয়েড অ্যাপকে জানান যে Modal বন্ধ হয়েছে
            if (window.Android) {
                window.Android.onModalClose();
            }
        }

        if(addNewProductBtn) addNewProductBtn.addEventListener('click', () => openModal('add'));
        if(closeProductModalBtn) closeProductModalBtn.addEventListener('click', closeModal);
        if(cancelProductFormBtn) cancelProductFormBtn.addEventListener('click', closeModal);
        if(productModal) productModal.addEventListener('click', (e) => { if (e.target == productModal) closeModal(); });

        function handleSaveProduct(e) { 
            e.preventDefault();
        }
        function handleReviewApprove(e) { 
            e.preventDefault();
        }

        function setupImageInputToggle(parentElement) {
            if (!parentElement) return;
            parentElement.querySelectorAll('.image-input-toggle input[type="radio"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    const group = this.closest('.form-group');
                    if (!group) return;
                    const fileInput = group.querySelector('input[type="file"]');
                    const urlInput = group.querySelector('input[type="url"]');
                    if (fileInput && urlInput) {
                        fileInput.style.display = (this.value === 'upload') ? 'block' : 'none';
                        urlInput.style.display = (this.value === 'url') ? 'block' : 'none';
                        if (this.value === 'upload') urlInput.value = ''; else fileInput.value = '';
                    }
                });
            });
        }
        if (productForm) setupImageInputToggle(productForm);

        document.body.addEventListener('click', function(event) {
            const target = event.target;
            const editBtn = target.closest('.edit-product-btn'); if (editBtn) { openModal('edit', { id: editBtn.dataset.id }); return; }
            const reviewBtn = target.closest('.review-request-btn'); if (reviewBtn) { openModal('review', { id: reviewBtn.dataset.id }); return; }
            const scanBtn = target.closest('.scan-barcode-btn'); if (scanBtn) { 
                document.getElementById('barcode-scanner-modal').style.display = 'block';
                setTimeout(startScanner, 500);
                return; 
            }
        });

        const modalForm = productModal?.querySelector('#product-form');
        if (modalForm) {
            const altSectionsHTML = [1, 2, 3].map(i => `
                <div class="alternative-section"><h5>Alternative Product ${i}</h5><div class="form-grid">
                <div class="form-group"><label>Alternative Img ${i}</label><input type="file" id="altIF${i}" accept="image/*"></div>
                <div class="form-group"><label for="altN${i}">Alternative Name ${i}</label><input class="name-fix" type="text" id="altN${i}"></div>
                <div class="form-group "><label for="altB${i}">Alternative Brand ${i}</label><input class="alt-fix" type="text" id="altB${i}"></div>
                <div class="form-group"><label for="altBC${i}">Alternative Barcode ${i}</label><div class="input-group"><input type="text" id="altBC${i}"><button type="button" class="btn btn-secondary scan-barcode-btn"><i class="fas fa-barcode"></i> Scan</button></div></div>
                </div></div>`).join('');
            const moreInfo = modalForm.querySelector('.form-group-full');
            if (moreInfo) moreInfo.insertAdjacentHTML('afterend', altSectionsHTML); else modalForm.insertAdjacentHTML('beforeend', altSectionsHTML);
        }

        function submitForm() {
            const formData = new FormData();
            formData.append('action', action);

            // Add request_id for review action
            if (action === 'review' && form.dataset.requestId) {
                formData.append('request_id', form.dataset.requestId);
            }

            if (action === 'edit') {
                formData.append('original_id', form.dataset.originalId);
            }

            // Get image file
            const imageFile = document.getElementById('productImageFile').files[0];
            if (imageFile) {
                formData.append('productImageFile', imageFile);
            }

            // Add main product data
            formData.append('name', productName);
            formData.append('brand', document.getElementById('productBrand').value);
            formData.append('category', document.getElementById('productCategory').value);
            formData.append('subcategory', document.getElementById('productSubCategory').value);
            formData.append('barcode', barcode);
            formData.append('moreinfo', document.getElementById('productMoreInfo').value);

            // Add alternative products data
            for (let i = 1; i <= 3; i++) {
                const altImage = document.getElementById(`altIF${i}`);
                const altName = document.getElementById(`altN${i}`);
                const altBrand = document.getElementById(`altB${i}`);
                const altBarcode = document.getElementById(`altBC${i}`);

                if (altImage && altName && altBrand && altBarcode) {
                    const altImageFile = altImage.files[0];
                    if (altImageFile) {
                        formData.append(`altimg${i}`, altImageFile);
                    }
                    
                    formData.append(`altname${i}`, altName.value || '');
                    formData.append(`altbrand${i}`, altBrand.value || '');
                    formData.append(`altbarcode${i}`, altBarcode.value.trim() || '');
                } else {
                    // Always add the alternative product data, even if some fields don't exist
                    // This ensures that any available data is sent to the backend
                    const altImageFile = altImage ? altImage.files[0] : null;
                    if (altImageFile) {
                        formData.append(`altimg${i}`, altImageFile);
                    }
                    
                    formData.append(`altname${i}`, altName ? (altName.value || '') : '');
                    formData.append(`altbrand${i}`, altBrand ? (altBrand.value || '') : '');
                    formData.append(`altbarcode${i}`, altBarcode ? (altBarcode.value.trim() || '') : '');
                }
            }

            // Determine which endpoint to use based on action
            const endpoint = action === 'review' ? 'src/approve_product_request.php' : 'src/product_operations.php';

            // Send the request
            fetch(endpoint, {
                method: 'POST',
                body: formData
            })
        }
    });
