    // js/script.js

    // প্রয়োজনীয় ফাংশনগুলি ইম্পোর্ট করুন
    import { showLogin, showDashboard, resetReviewForm, resetAddForm, renderRequestsList, setupAllImageInputs, resetWarnings, setFormSubmittingState, setupModalCloseHandlers } from './ui.js';
    import { apiLogin, apiLogout, apiCheckAuth, apiFetchRequests, apiFetchRequestById, apiApproveRequest, apiAddProduct, apiDeleteRequest, apiCheckDuplicate } from './api.js';
    import { setupScannerModalHandlers, handleScanButtonClick, startScanner, stopScanner } from './scanner.js'; // Scanner functions
    // import { escapeHTML, formatImageUrlForDisplay, fileToBase64 } from './helpers.js'; // Helpers are used internally by other modules or UI

    // --- DOM References (Used here for event listeners/direct manipulation) ---
    const loginForm = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const loginBtn = document.getElementById('loginBtn');
    const loginSpinner = document.getElementById('loginSpinner');
    const loginMessage = document.getElementById('loginMessage');
    const logoutBtn = document.getElementById('logoutBtn');

    // Review Modal Specific Elements (for event listeners)
    const reviewForm = document.getElementById("reviewForm");
    const approveBtn = document.getElementById("approveBtn");
    const rejectBtn = document.getElementById("rejectBtn");
    const reviewFormMessage = document.getElementById("reviewFormMessage");
    const requestId = document.getElementById('requestId'); // Used to get ID for review/reject

    // Add Product Modal Specific Elements (for event listeners)
    const addProductBtn = document.getElementById('addProductBtn');
    const addProductForm = document.getElementById('addProductForm');
    const addProductFormMessage = document.getElementById('addProductFormMessage');
    const saveProductBtn = document.getElementById('saveProductBtn');


    // Live duplicate check input fields (Need references here to add listeners)
    const editProductName = document.getElementById('editProductName');
    const editBarcode = document.getElementById('editBarcode');
    const addProductName = document.getElementById('addProductName');
    const addBarcode = document.getElementById('addBarcode');
    const editNameWarning = document.getElementById('editNameWarning');
    const editBarcodeWarning = document.getElementById('editBarcodeWarning');
    const addNameWarning = document.getElementById('addNameWarning');
    const addBarcodeWarning = document.getElementById('addBarcodeWarning');


    // --- State Tracking ---
    // এটি নিশ্চিত করে যে একই রিকোয়েস্ট একাধিকবার পাঠানো হচ্ছে না
    const activeApiRequests = new Set(); // Format: 'action_id' or 'action_new'


    // --- Core Functions ---

    /**
     * প্রোডাক্ট রিকোয়েস্ট লোড করুন এবং UI আপডেট করুন।
     */
    async function loadRequests() {
         // Loading state দেখান
         const requestsListDiv = document.getElementById('requests-list'); // DOM refetch if needed
         const loadingText = document.getElementById('loading-text');
         const noRequestsText = document.getElementById('no-requests');

         if (requestsListDiv) requestsListDiv.innerHTML = ''; // আগের ফলাফল সাফ করুন
         if (loadingText) loadingText.classList.remove('hidden');
         if (noRequestsText) noRequestsText.classList.add('hidden');


        try {
            const requests = await apiFetchRequests(); // api.js থেকে ফাংশন

             // UI আপডেট করুন
             renderRequestsList(requests); // ui.js থেকে ফাংশন

        } catch (error) {
             // Error handling
             console.error('Error loading product requests:', error);
             if (loadingText) loadingText.classList.add('hidden');
             const requestsListDiv = document.getElementById('requests-list');
             if (requestsListDiv) {
                 requestsListDiv.innerHTML = `<div class="p-4 text-center text-red-600">Error loading requests: ${escapeHTML(error.message || 'Unknown error')}</div>`;
             }
            // Authentication required error handled by api.js callApi function
        } finally {
            // Ensure list button listeners are attached after load, even if error
             attachListButtonListeners();
        }
    }

    /**
     * তালিকা থেকে রিভিউ বাটনে ক্লিক হ্যান্ডেল করুন।
     * @param {string} id - রিকোয়েস্ট ID।
     */
    async function handleReviewClick(id) {
        console.log("Review clicked for ID:", id);
        resetReviewForm(); // ui.js থেকে ফাংশন
        resetWarnings('review'); // ui.js থেকে ফাংশন

         const reviewModal = document.getElementById("reviewModal");
        if(reviewModal) reviewModal.style.display = "block";

         const reviewFormMessage = document.getElementById("reviewFormMessage");
         if(reviewFormMessage) {
             setFormSubmittingState(reviewFormMessage, approveBtn, null, true, rejectBtn, 'Loading request details...', 'loading');
             // Temporarily disable buttons while loading
             if (approveBtn) approveBtn.disabled = true;
             if (rejectBtn) rejectBtn.disabled = true;
         }


        try {
            const request = await apiFetchRequestById(id); // api.js থেকে ফাংশন
             console.log("Fetched request details:", request);

             if (reviewFormMessage) setFormSubmittingState(reviewFormMessage, approveBtn, null, false, rejectBtn); // Clear loading message

            if (request) {
                 // Populate review form fields
                const requestId = document.getElementById('requestId');
                const editProductName = document.getElementById('editProductName');
                const editProductBrand = document.getElementById('editProductBrand');
                const editProductCategory = document.getElementById('editProductCategory');
                const editSubCategory = document.getElementById('editSubCategory');
                const editBarcode = document.getElementById('editBarcode');
                const editMoreInfo = document.getElementById('editMoreInfo');
                const editProductImageBase64 = document.getElementById('editProductImageBase64');
                const editProductImageSource = document.getElementById('editProductImageSource');
                const editProductImagePreview = document.getElementById('editProductImagePreview');
                const editProductImageUrl = document.getElementById('editProductImageUrl');
                const editProductImageFile = document.getElementById('editProductImageFile');


                if (requestId) requestId.value = request.id || '';
                if (editProductName) editProductName.value = request.product_name || '';
                if (editProductBrand) editProductBrand.value = request.product_brand || '';
                if (editProductCategory) editProductCategory.value = request.product_category || '';
                if (editSubCategory) editSubCategory.value = request.sub_category || '';
                if (editBarcode) editBarcode.value = request.barcode || '';
                if (editMoreInfo) editMoreInfo.value = request.more_info || '';


                // Main product image handling (populate inputs and preview)
                if (request.product_image_url) {
                     const mainImgSrc = formatImageUrlForDisplay(request.product_image_url); // helpers.js থেকে ফাংশন
                     if(editProductImageBase64) editProductImageBase64.value = request.product_image_url; // Store the URL/Base64 fetched
                     if(editProductImagePreview) {
                          editProductImagePreview.src = mainImgSrc;
                          editProductImagePreview.classList.remove('hidden');
                     }
                     // Infer source type based on format
                      const imageSource = (request.product_image_url.startsWith('http://') || request.product_image_url.startsWith('https://')) ? 'url' : 'file';
                     if(editProductImageSource) editProductImageSource.value = imageSource;


                     // Set the correct input field based on source type
                     if (imageSource === 'url') {
                        if(editProductImageUrl) editProductImageUrl.value = request.product_image_url;
                        if(editProductImageFile) editProductImageFile.value = ''; // Ensure file input is clear
                     } else {
                        // If it's base64 from DB, don't put raw base64 into the URL field.
                        if(editProductImageUrl) editProductImageUrl.value = ''; // Ensure URL input is clear
                        if(editProductImageFile) editProductImageFile.value = ''; // Clear file input
                        // The base64 value is already in editProductImageBase64.value
                     }
                 } else {
                      // No image data from backend
                      if(editProductImageFile) editProductImageFile.value = '';
                      if(editProductImageUrl) editProductImageUrl.value = '';
                      if(editProductImageBase64) editProductImageBase64.value = '';
                      if(editProductImageSource) editProductImageSource.value = 'none';
                       if(editProductImagePreview) {
                           editProductImagePreview.src = '';
                           editProductImagePreview.classList.add('hidden');
                       }
                 }


                // Handle alternative products (populate inputs and previews)
                for (let i = 1; i <= 3; i++) {
                     const nameEl = document.getElementById(`altName${i}`);
                     const brandEl = document.getElementById(`altBrand${i}`);
                     const barcodeEl = document.getElementById(`altBarcode${i}`);
                     const base64El = document.getElementById(`altImageBase64_${i}`);
                     const sourceEl = document.getElementById(`altImageSource_${i}`);
                     const previewEl = document.getElementById(`altImagePreview${i}`);
                     const fileEl = document.getElementById(`altImageFile${i}`);
                     const urlEl = document.getElementById(`altImageUrl${i}`);


                     // Populate if data exists
                     if (nameEl) nameEl.value = request[`alternative_name${i}`] || '';
                     if (brandEl) brandEl.value = request[`alternative_brand${i}`] || '';
                     if (barcodeEl) barcodeEl.value = request[`alternative_barcode${i}`] || '';

                    const altImage = request[`alternative_image${i}`];
                    if (altImage && base64El && previewEl && sourceEl && urlEl && fileEl) {
                         const altImgSrc = formatImageUrlForDisplay(altImage); // helpers.js থেকে ফাংশন
                         base64El.value = altImage; // Store the URL/Base64 fetched
                         previewEl.src = altImgSrc;
                         previewEl.classList.remove('hidden');
                         const altImageSourceType = (altImage.startsWith('http://') || altImage.startsWith('https://')) ? 'url' : 'file'; // Infer source type
                         sourceEl.value = altImageSourceType;


                         // Set the correct input field based on source type
                         if (altImageSourceType === 'url') {
                            urlEl.value = altImage;
                            fileEl.value = '';
                         } else {
                             urlEl.value = '';
                             fileEl.value = '';
                            // base64 value is already in base64El.value
                         }
                    } else {
                         // No image data for this alternative
                          if(fileEl) fileEl.value = '';
                          if(urlEl) urlEl.value = '';
                          if(base64El) base64El.value = '';
                          if(sourceEl) sourceEl.value = 'none';
                           if(previewEl) {
                               previewEl.src = '';
                               previewEl.classList.add('hidden');
                           }
                    }
                }

                // Enable buttons after data load
                 if (approveBtn) approveBtn.disabled = false;
                 if (rejectBtn) rejectBtn.disabled = false;


            } else {
                 // Request not found or other non-auth error
                 if(reviewModal) reviewModal.style.display = "none"; // Close modal if request not found
                 alert('Failed to load request details: ' + (request ? request.message : 'Request not found.'));
            }
        } catch (error) {
            console.error('Error loading request details:', error);
             if(reviewModal) reviewModal.style.display = "none"; // Close modal on error
             alert('Error loading request details: ' + (error.message || 'Unknown error'));
        }
    }

    /**
     * তালিকা থেকে বা মডাল থেকে ডিলিট/রিজেক্ট কনফার্মেশন এবং হ্যান্ডলিং।
     * @param {string} id - রিকোয়েস্ট ID।
     * @param {HTMLElement|null} buttonElement - যে বাটন ক্লিক করা হয়েছে (তালিকা থেকে হলে), মডাল থেকে হলে null।
     */
    function deleteRequestWithConfirm(id, buttonElement = null) {
        if (!id) {
            if (reviewFormMessage && !buttonElement) { // Only show message in modal if called from modal
                reviewFormMessage.textContent = 'No request selected for deletion.';
                 reviewFormMessage.className = 'form-message error';
            } else if (buttonElement) {
                // No specific message needed for list item delete confirmation
            }
            return;
        }

        if (confirm('Are you sure you want to delete/reject this product request? This action cannot be undone.')) {
             // মেসেজ এরিয়া সাফ করুন অ্যাকশনের আগে
             if (reviewFormMessage && !buttonElement) {
                reviewFormMessage.textContent = '';
                reviewFormMessage.className = 'form-message';
             }

            // UI স্টেট আপডেট করুন
            if (buttonElement) { // তালিকা থেকে ডিলিট বাটন
                setFormSubmittingState(null, buttonElement, null, true); // শুধুমাত্র বাটন ডিসেবল করুন
            } else { // মডাল থেকে রিজেক্ট বাটন
                 setFormSubmittingState(reviewFormMessage, rejectBtn, document.getElementById('rejectSpinner'), true, approveBtn, 'Deleting request...', 'loading');
            }

            handleDeleteRequest(id, buttonElement);
        }
    }

    /**
     * ব্যাকএন্ডে ডিলিট রিকোয়েস্ট পাঠান এবং UI আপডেট করুন।
     * @param {string} id - রিকোয়েস্ট ID।
     * @param {HTMLElement|null} buttonElement - যে বাটন ক্লিক করা হয়েছে (তালিকা থেকে হলে), মডাল থেকে হলে null।
     */
    async function handleDeleteRequest(id, buttonElement = null) {
         const messageElement = buttonElement ? null : reviewFormMessage; // মডাল থেকে হলে মেসেজ এরিয়া আছে
         const primaryButton = buttonElement || rejectBtn; // মডাল থেকে হলে rejectBtn
         const primarySpinner = buttonElement ? null : document.getElementById('rejectSpinner'); // মডাল থেকে হলে rejectSpinner
         const secondaryButton = buttonElement ? null : approveBtn; // মডাল থেকে হলে approveBtn

         const requestKey = `delete_request_${id}`;
         if (activeApiRequests.has(requestKey)) {
              console.log("Delete request already in progress:", requestKey);
             return;
         }
         activeApiRequests.add(requestKey);


         try {
             const result = await apiDeleteRequest(id); // api.js থেকে ফাংশন

             if (result.success) {
                 if (messageElement) {
                      setFormSubmittingState(messageElement, primaryButton, primarySpinner, false, secondaryButton, result.message || 'Request deleted successfully!', 'success');
                 } else {
                      console.log('Request deleted successfully:', result.message);
                 }

                 // তালিকা থেকে আইটেম সরান
                 const requestsListDiv = document.getElementById('requests-list');
                 const itemToRemove = requestsListDiv?.querySelector(`.product-row[data-id="${id}"]`);
                 if (itemToRemove) {
                     itemToRemove.remove();
                     console.log(`Removed item with ID: ${id}`);
                 } else {
                      console.warn(`Item with ID ${id} not found in list for removal.`);
                 }

                 // তালিকা খালি কিনা চেক করুন
                 const noRequestsText = document.getElementById('no-requests');
                  if (requestsListDiv && noRequestsText) {
                      if (requestsListDiv.children.length === 0) {
                         noRequestsText.classList.remove('hidden');
                      } else {
                         noRequestsText.classList.add('hidden'); // Ensure it's hidden if items are present
                      }
                  }


                 // মডাল বন্ধ করুন যদি মডাল থেকে রিজেক্ট করা হয়
                 if (!buttonElement) {
                     setTimeout(() => {
                         const reviewModal = document.getElementById("reviewModal");
                         if(reviewModal) reviewModal.style.display = "none";
                         resetReviewForm(); // ui.js থেকে ফাংশন
                     }, 1500); // ছোট বিলম্ব
                 }

             } else {
                 // Backend ত্রুটি
                 if (messageElement) {
                     setFormSubmittingState(messageElement, primaryButton, primarySpinner, false, secondaryButton, `Error: ${escapeHTML(result.message || 'Failed to delete request.')}`, 'error');
                 } else {
                     console.error('Error deleting request:', result.message);
                     alert('Error deleting request: ' + escapeHTML(result.message || 'Unknown error'));
                 }
             }

         } catch (error) {
             // নেটওয়ার্ক বা API ত্রুটি (যেমন auth error handled by api.js)
             console.error('Network or API error during deletion:', error);
             if (messageElement) {
                 setFormSubmittingState(messageElement, primaryButton, primarySpinner, false, secondaryButton, `Error: ${escapeHTML(error.message || 'Network error')}`, 'error');
             } else {
                  alert('Network error during deletion: ' + (error.message || 'Unknown error'));
             }

         } finally {
             activeApiRequests.delete(requestKey);
             // যদি সফলভাবে ডিলিট হয় এবং মডাল থেকে হয়, বাটন ইতিমধ্যেই রিসেট হয়ে গেছে (মডাল বন্ধ হবে)।
             // যদি ত্রুটি হয় বা তালিকা থেকে ডিলিট হয়, বাটন রিসেট করতে হবে।
             if (buttonElement) { // তালিকা থেকে ডিলিট বাটন
                  setFormSubmittingState(null, buttonElement, null, false); // বাটন পুনরায় সক্রিয় করুন
             } else if (!result?.success) { // মডাল থেকে রিজেক্ট এবং সফল না হলে
                  setFormSubmittingState(messageElement, primaryButton, primarySpinner, false, secondaryButton);
             }
         }
    }


    // Helper function for live duplicate checking
    let duplicateCheckTimeout;
    async function checkDuplicateLive(value, type, warningSpanElement) {
        if (!warningSpanElement) return;
        warningSpanElement.classList.add('hidden'); // Hide initially
        warningSpanElement.textContent = ''; // Clear text

        const trimmedValue = value ? value.trim() : '';
        if (trimmedValue === '' || trimmedValue.length < 3) { // Add min length check (optional but good for performance)
             // Clear any existing debounce timeout if input becomes empty
             if (duplicateCheckTimeout) {
                 clearTimeout(duplicateCheckTimeout);
             }
            return; // Don't check empty or very short fields
        }

         // Debounce: Clear previous timeout if user types again quickly
         if (duplicateCheckTimeout) {
             clearTimeout(duplicateCheckTimeout);
         }

        duplicateCheckTimeout = setTimeout(async () => {
            try {
                // Determine which field to check based on type
                const productName = (type === 'name') ? trimmedValue : '';
                const barcode = (type === 'barcode') ? trimmedValue : '';

                const data = await apiCheckDuplicate(productName, barcode); // api.js থেকে ফাংশন

                if (data.success) {
                    let isDuplicate = false;
                    if (type === 'name' && data.isDuplicateName) {
                        isDuplicate = true;
                    } else if (type === 'barcode' && data.isDuplicateBarcode) {
                        isDuplicate = true;
                    }

                    if (isDuplicate) {
                        warningSpanElement.textContent = `Duplicate ${type === 'name' ? 'Name' : 'Barcode'}!`;
                        warningSpanElement.classList.remove('hidden');
                    } else {
                         // যদি এখন ডুপ্লিকেট না হয়, নিশ্চিত করুন warning লুকানো আছে
                         warningSpanElement.classList.add('hidden');
                    }

                } else {
                    // API কল সফল হয়নি, কিন্তু ডুপ্লিকেট চেকিং ত্রুটি হয়েছে
                     console.warn("Duplicate check API returned success: false", data.message);
                     // Optionally show a minor warning or log it
                     // warningSpanElement.textContent = 'Check Error';
                     // warningSpanElement.classList.remove('hidden');
                }
            } catch (error) {
                console.error('Network or API error during live duplicate check:', error);
                 // নেটওয়ার্ক ত্রুটি বা callApi থেকে আসা error হ্যান্ডেল করুন
                 // warningSpanElement.textContent = 'Network Error'; // Optional: Show network error to user
                 // warningSpanElement.classList.remove('hidden');
            }
         }, 400); // Debounce time in milliseconds
    }


    // --- Event Listeners Setup ---

    // Login form listener
    if (loginForm) {
        loginForm.addEventListener('submit', async function(event) {
            event.preventDefault();
             const username = usernameInput.value;
             const password = passwordInput.value;

             // UI স্টেট: লোডিং
             setFormSubmittingState(loginMessage, loginBtn, loginSpinner, true, null, '', 'form-message');


            try {
                const result = await apiLogin(username, password); // api.js থেকে ফাংশন

                if (result.success) {
                    // UI স্টেট: সাফল্য
                     setFormSubmittingState(loginMessage, loginBtn, loginSpinner, false, null, result.message || 'Login successful!', 'success');
                    setTimeout(showDashboard, 500); // UI আপডেট করুন
                } else {
                    // UI স্টেট: ব্যর্থতা
                    setFormSubmittingState(loginMessage, loginBtn, loginSpinner, false, null, escapeHTML(result.message || 'Login failed.'), 'error');
                }
            } catch (error) {
                // নেটওয়ার্ক বা API ত্রুটি
                console.error('Login error:', error);
                 setFormSubmittingState(loginMessage, loginBtn, loginSpinner, false, null, `Login error: ${escapeHTML(error.message || 'Unknown error')}`, 'error');
            }
        });
    }


    // Logout button listener
    if (logoutBtn) {
        logoutBtn.addEventListener('click', async function() {
             // UI স্টেট: লোডিং
            setFormSubmittingState(null, logoutBtn, document.getElementById('logoutSpinner'), true); // এখানে loginMessage ব্যবহার করা হচ্ছে না

            try {
                 const result = await apiLogout(); // api.js থেকে ফাংশন
                 // Logout successful response always has success: true from backend
                 // UI স্টেট: সাফল্য (লগইন স্ক্রিন দেখাবে)
                 setTimeout(showLogin, 500); // UI আপডেট করুন
            } catch (error) {
                // নেটওয়ার্ক বা API ত্রুটি (unlikely for logout but possible)
                console.error('Logout error:', error);
                alert('Logout failed: ' + (error.message || 'Unknown error')); // Use alert for simplicity on logout
                // UI স্টেট রিসেট করুন যেহেতু লগআউট ব্যর্থ হয়েছে
                 setFormSubmittingState(null, logoutBtn, document.getElementById('logoutSpinner'), false);
            }
        });
    }


    // Add Product button listener
    if (addProductBtn) {
        addProductBtn.addEventListener('click', function() {
            resetAddForm(); // ui.js থেকে ফাংশন
            resetWarnings('add'); // ui.js থেকে ফাংশন
            const addProductModal = document.getElementById('addProductModal');
            if(addProductModal) addProductModal.style.display = "block";
        });
    }


    // Review Form Submission Listener (Approve)
    if (reviewForm) {
        reviewForm.addEventListener('submit', async function(event) {
            event.preventDefault();
             if (!requestId.value) {
                 setFormSubmittingState(reviewFormMessage, approveBtn, null, false, rejectBtn, 'No request selected for approval.', 'error');
                 return;
             }
              // Basic client-side validation before submitting
             if (!editProductName.value.trim()) {
                  setFormSubmittingState(reviewFormMessage, approveBtn, null, false, rejectBtn, 'Product Name is required for approval.', 'error');
                  return;
             }

             // UI স্টেট: লোডিং
             setFormSubmittingState(reviewFormMessage, approveBtn, document.getElementById('approveSpinner'), true, rejectBtn, 'Approving request...', 'loading');

            const formData = new FormData(reviewForm); // ফর্ম ডেটা নিন
             // Backend action handled by callApi
             // formData.append('action', 'approve_request'); // No need to add action here

            try {
                 const result = await apiApproveRequest(formData); // api.js থেকে ফাংশন

                if (result.success) {
                     // UI স্টেট: সাফল্য
                     setFormSubmittingState(reviewFormMessage, approveBtn, document.getElementById('approveSpinner'), false, rejectBtn, result.message || 'Approved successfully!', 'success');
                     // মডাল বন্ধ করা এবং তালিকা আপডেট করা handleDeleteRequest/handleFormSubmission এর success ব্লকে করা হয়
                     // এখানে শুধু মেসেজ ও স্টেট আপডেট করে exit করব, মডাল ক্লোজ/রিসেট setTimeout এ হবে
                     // loadRequests(); // তালিকা রিলোড করার দরকার নেই যদি সফলভাবে আইটেম রিমুভ হয়

                } else {
                    // Backend ত্রুটি
                     setFormSubmittingState(reviewFormMessage, approveBtn, document.getElementById('approveSpinner'), false, rejectBtn, `Error: ${escapeHTML(result.message || 'Approval failed.')}`, 'error');
                }

            } catch (error) {
                 // নেটওয়ার্ক বা API ত্রুটি
                 console.error('Approval error:', error);
                  setFormSubmittingState(reviewFormMessage, approveBtn, document.getElementById('approveSpinner'), false, rejectBtn, `Error: ${escapeHTML(error.message || 'Network error during approval.')}`, 'error');
            } finally {
                 // Final UI state cleanup handled after timeout in success case or here on error
                 // if (!result?.success) { // Only re-enable buttons if not closing modal
                 //     setFormSubmittingState(reviewFormMessage, approveBtn, document.getElementById('approveSpinner'), false, rejectBtn);
                 // }
            }
        });
    }

    // Reject Button Listener (Review Form)
    if (rejectBtn) {
        rejectBtn.addEventListener('click', function() {
             const id = requestId.value; // UI থেকে রিকোয়েস্ট ID নিন
            deleteRequestWithConfirm(id, null); // null মানে এটি মডাল থেকে কল করা হয়েছে
        });
    }

    // Add Product Form Submission Listener
    if (addProductForm) {
         addProductForm.addEventListener('submit', async function(event) {
             event.preventDefault();

             // Basic client-side validation
             if (!addProductName.value.trim()) {
                 setFormSubmittingState(addProductFormMessage, saveProductBtn, null, false, null, 'Product Name is required.', 'error');
                 return;
             }

              // UI স্টেট: লোডিং
              setFormSubmittingState(addProductFormMessage, saveProductBtn, document.getElementById('saveProductSpinner'), true, null, 'Saving product...', 'loading');


             const formData = new FormData(addProductForm); // ফর্ম ডেটা নিন
              // Backend action handled by callApi
             // formData.append('action', 'add_product'); // No need to add action here

             try {
                 const result = await apiAddProduct(formData); // api.js থেকে ফাংশন

                 if (result.success) {
                      // UI স্টেট: সাফল্য
                     setFormSubmittingState(addProductFormMessage, saveProductBtn, document.getElementById('saveProductSpinner'), false, null, result.message || 'Product added successfully!', 'success');
                     // মডাল বন্ধ করা resetAddForm এর setTimeout এ হবে
                 } else {
                     // Backend ত্রুটি
                     setFormSubmittingState(addProductFormMessage, saveProductBtn, document.getElementById('saveProductSpinner'), false, null, `Error: ${escapeHTML(result.message || 'Failed to add product.')}`, 'error');
                 }

             } catch (error) {
                  // নেটওয়ার্ক বা API ত্রুটি
                  console.error('Add product error:', error);
                   setFormSubmittingState(addProductFormMessage, saveProductBtn, document.getElementById('saveProductSpinner'), false, null, `Error: ${escapeHTML(error.message || 'Network error during add product.')}`, 'error');
             } finally {
                 // Final UI state cleanup handled after timeout in success case or here on error
                 // if (!result?.success) { // Only re-enable button if not closing modal
                 //      setFormSubmittingState(addProductFormMessage, saveProductBtn, document.getElementById('saveProductSpinner'), false, null);
                 // }
             }
         });
    }

    // Event delegation for list buttons (Review and Delete)
    // Attach listener to the requestsListDiv container
    function attachListButtonListeners() {
         const requestsListDiv = document.getElementById('requests-list');
         if (!requestsListDiv) return;

         // Prevent adding multiple listeners
         requestsListDiv.removeEventListener('click', handleListButtonClick); // Remove previous if exists
         requestsListDiv.addEventListener('click', handleListButtonClick);
         console.log("Delegated list button listeners attached.");
    }

    // Handler for list buttons
    function handleListButtonClick(event) {
        const target = event.target;
        const reviewBtn = target.closest('.review-button');
        const deleteBtn = target.closest('.delete-button');

        if (reviewBtn && reviewBtn.dataset.id) {
            console.log("Review button clicked for ID:", reviewBtn.dataset.id);
            handleReviewClick(reviewBtn.dataset.id); // Call async review handler
        } else if (deleteBtn && deleteBtn.dataset.id) {
             console.log("Delete button clicked for ID:", deleteBtn.dataset.id);
             // Call delete with the button element reference
            deleteRequestWithConfirm(deleteBtn.dataset.id, deleteBtn);
        }
    }


    // Live duplicate check listeners (using blur event)
    if(editProductName) editProductName.addEventListener('blur', function() { checkDuplicateLive(this.value, 'name', editNameWarning); });
    if(editBarcode) editBarcode.addEventListener('blur', function() { checkDuplicateLive(this.value, 'barcode', editBarcodeWarning); });
    if(addProductName) addProductName.addEventListener('blur', function() { checkDuplicateLive(this.value, 'name', addNameWarning); });
    if(addBarcode) addBarcode.addEventListener('blur', function() { checkDuplicateLive(this.value, 'barcode', addBarcodeWarning); });


    // Scan button listeners (using event delegation on document.body as they are in modals)
    // HandleScanButtonClick is imported from scanner.js
     document.body.addEventListener('click', handleScanButtonClick); // Add listener to document body


    // --- Initial Application Load ---
    document.addEventListener('DOMContentLoaded', async () => {
        console.log("DOM fully loaded and parsed. Initializing application.");

        // UI Component setups
         setupAllImageInputs(); // ui.js থেকে ফাংশন
         setupModalCloseHandlers(); // ui.js থেকে ফাংশন
         setupScannerModalHandlers(); // scanner.js থেকে ফাংশন

        // Check authentication status on load
        try {
            const isAuthenticated = await apiCheckAuth(); // api.js থেকে ফাংশন
             console.log("Authentication check result:", isAuthenticated);
            if (isAuthenticated) {
                showDashboard(); // ui.js থেকে ফাংশন - this will trigger loadRequests()
                 loadRequests(); // Dashboard loading happens here
            } else {
                showLogin(); // ui.js থেকে ফাংশন
            }
        } catch (error) {
            console.error("Initial authentication check failed:", error);
             // In case of critical error preventing auth check, default to login view
            showLogin(); // ui.js থেকে ফাংশন
            // Optionally show a persistent error message on login screen if auth check failed
            // loginMessage.textContent = `Authentication check failed: ${error.message}`;
            // loginMessage.classList.add('error');
        }

         // Note: list button listeners are attached *after* requests are loaded (inside loadRequests or finally block)

    });
