console.log("manage_undeposited_funds.js loaded.");

document.addEventListener("DOMContentLoaded", function() {
    let selectEl = document.querySelector('select[name="view_mode"]');
    const middlePane = document.getElementById('middlePane');
    const leftPane = document.getElementById('leftPane');
    const overlay = document.getElementById('pullProgressOverlay');
    const countEl = document.getElementById('pullCount');
    let progressTimer;

    function showPullOverlay() {
        if (!overlay || !countEl) return;
        countEl.textContent = '0';
        overlay.style.display = 'flex';
        let n = 0;
        progressTimer = setInterval(() => {
            n += Math.floor(Math.random() * 3) + 1;
            countEl.textContent = n.toString();
        }, 500);
    }

    function hidePullOverlay() {
        if (!overlay) return;
        overlay.style.display = 'none';
        clearInterval(progressTimer);
    }

    if (!selectEl || !middlePane || !leftPane) return;

    const savedViewMode = sessionStorage.getItem('currentViewMode');

    function initializeSelectElement() {
        const newSelect = document.querySelector('select[name="view_mode"]');
        if (!newSelect) return;
        if (selectEl && selectEl !== newSelect) {
            selectEl.removeEventListener('change', handleSelectChange);
        }
        selectEl = newSelect;
        selectEl.addEventListener('change', handleSelectChange);
    }

    async function handleSelectChange() {
        sessionStorage.setItem('currentViewMode', selectEl.value);
        if (['pull', 'fetch_sr', 'fetch_journal'].includes(selectEl.value)) {
            if (!leftPane.querySelector('#pullQBDataWrapper')) {
                await loadLeftPane('pull');
            }
            updateWrapperVisibility();
        } else {
            await loadView(selectEl.value);
            await loadLeftPane(selectEl.value);
        }
    }

    // Restore select dropdown from sessionStorage
    function restoreViewMode() {
        const saved = sessionStorage.getItem('currentViewMode');
        if (saved && ['manage', 'pull', 'make_bank_deposit', 'fetch_sr', 'fetch_journal'].includes(saved)) {
            if (selectEl) selectEl.value = saved;
        }
    }
    restoreViewMode();

    // Helper to inject or remove the date selector
    function injectDateSelector(container, action = 'pull_undeposited', label = 'Confirm Pull') {
        if (!container || container.innerHTML.trim() !== '') return;
        const today = new Date().toISOString().split('T')[0];
        const firstOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1)
            .toISOString().split('T')[0];
        container.innerHTML = `
            <div class="form-row flex-form">
                <div class="col-sm-2">
                    <label>From Date</label>
                    <input type="date" name="from_date" value="${firstOfMonth}" class="form-control" required>
                </div>
                <div class="col-sm-2">
                    <label>To Date</label>
                    <input type="date" name="to_date" value="${today}" class="form-control" required>
                </div>
                <div class="col-sm-2">
                    <button type="button" id="confirmPullBtn" data-action="${action}" class="btn btn-primary w-100">${label}</button>
                </div>
            </div>
        `;
        if (!attachConfirmPullBtn(container)) {
            setTimeout(() => attachConfirmPullBtn(container), 100);
        }
    }

    function removeDateSelector(container) {
        if (container) {
            container.innerHTML = '';
        }
    }

    // Helper to update wrapper and button visibility based on view
    function updateWrapperVisibility() {
        const pullQBDataWrapper = leftPane.querySelector('#pullQBDataWrapper');
        if (!pullQBDataWrapper) return;
        const makeBankDepositBtn = pullQBDataWrapper.querySelector('#makeBankDepositBtn');
        const depositHistoryBtn = pullQBDataWrapper.querySelector('#depositHistoryBtn');
        const dateSelectorContainer = pullQBDataWrapper.querySelector('#dateSelectorContainer');

        if (selectEl.value === 'manage') {
            pullQBDataWrapper.style.display = 'flex';
            if (makeBankDepositBtn) makeBankDepositBtn.style.display = 'block';
            if (depositHistoryBtn) depositHistoryBtn.style.display = 'block';
            removeDateSelector(dateSelectorContainer);
        } else if (['pull', 'fetch_sr', 'fetch_journal'].includes(selectEl.value)) {
            pullQBDataWrapper.style.display = 'flex';
            if (makeBankDepositBtn) makeBankDepositBtn.style.display = 'none';
            if (depositHistoryBtn) depositHistoryBtn.style.display = 'block';

            // Always rebuild the date selector when switching modes
            removeDateSelector(dateSelectorContainer);
            if (selectEl.value === 'fetch_sr') {
                injectDateSelector(dateSelectorContainer, 'fetch_sales_receipts', 'Fetch Sales Receipts');
            } else if (selectEl.value === 'fetch_journal') {
                injectDateSelector(dateSelectorContainer, 'fetch_journal_entries', 'Fetch Journal Entries');
            } else {
                injectDateSelector(dateSelectorContainer);
            }
        } else {
            pullQBDataWrapper.style.display = 'none';
            if (depositHistoryBtn) depositHistoryBtn.style.display = 'none';
            removeDateSelector(dateSelectorContainer);
        }
    }

    // Persist Bulk Find and Deposit form state
    function saveBulkFindState() {
        const wrapper = middlePane.querySelector('#bulkFindDepositWrapper');
        if (!wrapper) return;
        if (wrapper.style.display === 'block') {
            sessionStorage.setItem('bulkFindOpen', '1');
            const textarea = wrapper.querySelector('#bulkFindTextarea');
            const fieldSel = wrapper.querySelector('#bulkFindField');
            if (textarea) sessionStorage.setItem('bulkFindTextSaved', textarea.value);
            if (fieldSel) sessionStorage.setItem('bulkFindFieldSaved', fieldSel.value);
        } else {
            sessionStorage.removeItem('bulkFindOpen');
            sessionStorage.removeItem('bulkFindTextSaved');
            sessionStorage.removeItem('bulkFindFieldSaved');
        }
    }

    // Handle select change (dropdown)
    initializeSelectElement();

    // AJAX: Load partial into middle pane
    async function loadView(mode, fresh = false, extraParams = '') {
        if (mode === 'make_bank_deposit') {
            saveBulkFindState();
        }
        try {
            let url = fresh
                ? `/undepositedfunds/loadView?pane=middle&view=${mode}&fresh=1`
                : `/undepositedfunds/loadView?pane=middle&view=${mode}`;
            if (extraParams) {
                url += `&${extraParams.replace(/^\?/, '')}`;
            }

            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }
            const html = await response.text();
            middlePane.innerHTML = html;

            attachPaginationClick(mode);
            if (mode === 'make_bank_deposit') {
                attachMakeBankDepositLogic();
                attachFilterMenu();
                attachBulkUploadForm();
            }
            attachCloseMakeDepositBtn();
        } catch (err) {
            console.error(`AJAX loadView ${mode} error:`, err);
            middlePane.innerHTML = `<p class="text-danger">Error loading view: ${mode}</p>`;
        }
    }

    // AJAX: Load partial into left pane
    async function loadLeftPane(mode) {
        try {
            let view = 'main_view_selector';
            if (mode === 'make_bank_deposit') {
                view = 'make_bank_deposit';
            }
            const url = `/undepositedfunds/loadView?pane=left&view=${view}`;
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }
            const html = await response.text();
            leftPane.innerHTML = html;
            initializeSelectElement();
            restoreViewMode();
            attachLeftPaneButtonListeners();
            updateWrapperVisibility();
            updateSelectedAmount();
        } catch (err) {
            console.error(`AJAX loadLeftPane ${mode} error:`, err);
            leftPane.innerHTML = `<p class="text-danger">Error loading left pane: ${mode}</p>`;
        }
    }

    // First load: Restore view mode, or default to manage
    if (savedViewMode && !['manage', 'pull', 'fetch_sr', 'fetch_journal'].includes(savedViewMode)) {
        loadView(savedViewMode);
        loadLeftPane(savedViewMode);
    } else {
        attachPaginationClick('manage');
        loadLeftPane(savedViewMode || 'manage');
        if (['pull', 'fetch_sr', 'fetch_journal'].includes(savedViewMode)) {
            updateWrapperVisibility();
        }
    }

    // --- START: Live Update Selected Amount Logic ---
function updateSelectedAmount() {
        const boxes = middlePane ? middlePane.querySelectorAll('input[type="checkbox"][name="depositCheckbox[]"]') : [];
        const stored = JSON.parse(sessionStorage.getItem('mbdSelections') || '[]');
        const map = {};
        stored.forEach(item => { map[item.id] = item; });
        boxes.forEach(box => {
            const amountAttr = box.getAttribute('data-amount');
            let amount = parseFloat(amountAttr);
            if (isNaN(amount)) amount = 0;
            const row = box.closest('tr');
            const customer = row ? row.querySelector('.truncate-customer')?.textContent.trim() || '' : '';
            if (box.checked) {
                map[box.value] = { id: box.value, customer, amount };
            } else {
                delete map[box.value];
            }
        });
        const selected = Object.values(map);
        let sum = 0;
        selected.forEach(item => { sum += parseFloat(item.amount) || 0; });
        sessionStorage.setItem('mbdSelections', JSON.stringify(selected));

        const display = leftPane ? leftPane.querySelector('#amountSelectedDisplay') : null;
        const listEl = leftPane ? leftPane.querySelector('#selectedDepositsList') : null;

        if (display) {
            const formatted = sum < 0
                ? `-$${Math.abs(sum).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`
                : `$${sum.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
            display.textContent = formatted;
        }

        if (listEl) {
            listEl.innerHTML = '';
            selected.forEach(item => {
                const li = document.createElement('li');
                li.dataset.ufId = item.id;
                li.dataset.amount = item.amount;
                li.dataset.customer = item.customer;
                const money = item.amount < 0
                    ? `-$${Math.abs(item.amount).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`
                    : `$${item.amount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
                li.innerHTML = `<label><input type="checkbox" class="left-deposit-checkbox" data-uf-id="${item.id}" checked> ${item.customer} - ${money}</label>`;
                listEl.appendChild(li);
            });
        }

        const finalizeBtn = leftPane ? leftPane.querySelector('#finalizeDepositBtn') : null;
        if (finalizeBtn) {
            const mode = sessionStorage.getItem('currentViewMode');
            finalizeBtn.style.display = mode === 'make_bank_deposit' ? 'block' : 'none';
            finalizeBtn.disabled = selected.length === 0;
            finalizeBtn.textContent = selected.length > 0 ? `Finalize Deposit (${selected.length})` : 'Finalize Deposit';
        }

        attachLeftCheckboxLogic();
    }

    function attachLeftCheckboxLogic() {
        const boxes = leftPane ? leftPane.querySelectorAll('.left-deposit-checkbox') : [];
        boxes.forEach(box => {
            const newBox = box.cloneNode(true);
            box.parentNode.replaceChild(newBox, box);
            newBox.addEventListener('change', (e) => {
                const ufId = e.target.dataset.ufId;
                const checked = e.target.checked;
                const midBox = document.querySelector(`#middlePane input[name="depositCheckbox[]"][value="${ufId}"]`);
                if (midBox) {
                    midBox.checked = checked;
                    midBox.dispatchEvent(new Event('change'));
                } else {
                    fetch('/undepositedfunds/updateSelected', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: JSON.stringify({ ufId, checked })
                    }).catch(err => console.error('Error updating selection:', err));

                    let store = JSON.parse(sessionStorage.getItem('mbdSelections') || '[]');
                    const li = e.target.closest('li');
                    const amount = parseFloat(li?.dataset.amount || '0');
                    const customer = li?.dataset.customer || '';
                    if (checked) {
                        if (!store.some(item => item.id === ufId)) {
                            store.push({ id: ufId, customer, amount });
                        }
                    } else {
                        store = store.filter(item => item.id !== ufId);
                    }
                    sessionStorage.setItem('mbdSelections', JSON.stringify(store));
                    updateSelectedAmount();
                }
            });
        });
    }

    // --- END: Live Update Selected Amount Logic ---

    // Attach checkbox logic for make deposit view
    function attachMakeBankDepositLogic() {
        const checkboxes = middlePane.querySelectorAll('input[type="checkbox"][name="depositCheckbox[]"]');
        const selectAllBox = middlePane.querySelector('#selectAllVisible');

        const updateSelectAll = () => {
            if (!selectAllBox) return;
            const boxes = middlePane.querySelectorAll('tbody input[name="depositCheckbox[]"]');
            const allChecked = boxes.length > 0 && Array.from(boxes).every(b => b.checked);
            selectAllBox.checked = allChecked;
        };

        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', async (e) => {
                const checked = e.target.checked;
                const ufId = e.target.value;
                try {
                    const res = await fetch('/undepositedfunds/updateSelected', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: JSON.stringify({ ufId, checked })
                    });
                    if (!res.ok) throw new Error(`Failed to update selection: ${res.statusText}`);
                } catch (err) {
                    console.error('Error updating selection:', err);
                }
                let store = JSON.parse(sessionStorage.getItem('mbdSelections') || '[]');
                const row = e.target.closest('tr');
                const amount = parseFloat(e.target.dataset.amount || '0');
                const customer = row ? row.querySelector('.truncate-customer')?.textContent.trim() || '' : '';
                if (checked) {
                    if (!store.some(item => item.id === ufId)) {
                        store.push({ id: ufId, customer, amount });
                    }
                } else {
                    store = store.filter(item => item.id !== ufId);
                }
                sessionStorage.setItem('mbdSelections', JSON.stringify(store));
                updateSelectedAmount();
                updateSelectAll();
            });
        });
        updateSelectedAmount();
        updateSelectAll();

        if (selectAllBox) {
            selectAllBox.addEventListener('change', async () => {
                const boxes = middlePane.querySelectorAll('tbody input[name="depositCheckbox[]"]');
                const ids = Array.from(boxes).map(b => b.value);
                try {
                    const res = await fetch('/undepositedfunds/updateSelectedBulk', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: JSON.stringify({ ids, checked: selectAllBox.checked })
                    });
                    if (!res.ok) throw new Error(`Failed to update: ${res.statusText}`);
                } catch (err) {
                    console.error('Bulk update error:', err);
                }
                boxes.forEach(box => {
                    box.checked = selectAllBox.checked;
                });
                updateSelectedAmount();
            });
        }

        const limitSelect = middlePane.querySelector('#limitSelect');
        if (limitSelect) {
            limitSelect.addEventListener('change', () => {
                const params = new URLSearchParams();
                params.set('limit', limitSelect.value);
                const cust = middlePane.dataset.selectedCustomer || '';
                const memoVal = middlePane.dataset.memoFilter || '';
                const refVal = middlePane.dataset.referenceFilter || '';
                const amtVal = middlePane.dataset.amountFilter || '';
                const typeVal = middlePane.dataset.selectedType || '';
                const from = middlePane.dataset.fromDate || '';
                const to = middlePane.dataset.toDate || '';
                if (cust) params.set('customer', cust);
                if (memoVal) params.set('memo', memoVal);
                if (refVal) params.set('reference', refVal);
                if (amtVal) params.set('amount', amtVal);
                if (typeVal) params.set('type', typeVal);
                if (from) params.set('from_date', from);
                if (to) params.set('to_date', to);
                loadView('make_bank_deposit', false, params.toString());
            });
        }

        // If filters were previously selected, render them
        const customersData = middlePane.querySelector('#makeBankDepositData');
        if (customersData) {
            const customers = JSON.parse(customersData.dataset.customers || '[]');
            const types = JSON.parse(customersData.dataset.types || '[]');
            const selectedCustomer = customersData.dataset.selectedCustomer || '';
            const selectedType = customersData.dataset.selectedType || '';
            const selectedMemo = customersData.dataset.selectedMemo || '';
            const selectedReference = customersData.dataset.selectedReference || '';
            const selectedAmount = customersData.dataset.selectedAmount || '';
            const fromDate = customersData.dataset.fromDate || '';
            const toDate = customersData.dataset.toDate || '';
            middlePane.dataset.selectedCustomer = selectedCustomer;
            middlePane.dataset.selectedType = selectedType;
            middlePane.dataset.memoFilter = selectedMemo;
            middlePane.dataset.referenceFilter = selectedReference;
            middlePane.dataset.amountFilter = selectedAmount;
            middlePane.dataset.fromDate = fromDate;
            middlePane.dataset.toDate = toDate;
            if (selectedCustomer) {
                createCustomerFilter(customers, selectedCustomer);
            }
            if (selectedType) {
                createTypeFilter(types, selectedType);
            }
            if (selectedMemo) {
                createMemoFilter(selectedMemo);
            }
            if (selectedReference) {
                createReferenceFilter(selectedReference);
            }
            if (selectedAmount) {
                createAmountFilter(selectedAmount);
            }
            if (fromDate || toDate) {
                createDateFilter(fromDate, toDate);
            }
        }
    }
    function attachFilterMenu() {
        const icon = middlePane.querySelector("#mbdFilterIcon");
        const menu = middlePane.querySelector("#mbdFilterMenu");
        if (!icon || !menu) return;
        icon.addEventListener("click", (e) => {
            e.stopPropagation();
            menu.classList.toggle("show");
        });
        document.addEventListener("click", function(event) {
            if (!icon.contains(event.target) && !menu.contains(event.target)) {
                menu.classList.remove("show");
            }
        });

        menu.querySelectorAll('a[data-filter="customer"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const dataEl = middlePane.querySelector('#makeBankDepositData');
                if (!dataEl) return;
                const customers = JSON.parse(dataEl.dataset.customers || '[]');
                createCustomerFilter(customers, '');
                menu.classList.remove('show');
            });
        });

        menu.querySelectorAll('a[data-filter="type"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const dataEl = middlePane.querySelector('#makeBankDepositData');
                if (!dataEl) return;
                const types = JSON.parse(dataEl.dataset.types || '[]');
                createTypeFilter(types, '');
                menu.classList.remove('show');
            });
        });

        menu.querySelectorAll('a[data-filter="date"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                createDateFilter('', '');
                menu.classList.remove('show');
            });
        });

        menu.querySelectorAll('a[data-filter="memo"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                createMemoFilter('');
                menu.classList.remove('show');
            });
        });

        menu.querySelectorAll('a[data-filter="reference"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                createReferenceFilter('');
                menu.classList.remove('show');
            });
        });

        menu.querySelectorAll('a[data-filter="amount"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                createAmountFilter('');
                menu.classList.remove('show');
            });
        });
    }

    function createCustomerFilter(customers, selected) {
        const container = middlePane.querySelector('#mbdFilters');
        if (!container || container.querySelector('.customer-filter')) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'filter-item customer-filter';

        const label = document.createElement('label');
        label.textContent = 'Customer:';

        const select = document.createElement('select');
        select.className = 'form-control';
        select.style.width = 'auto';

        const defaultOpt = document.createElement('option');
        defaultOpt.value = '';
        defaultOpt.textContent = '--All--';
        select.appendChild(defaultOpt);

        customers.forEach(name => {
            const opt = document.createElement('option');
            opt.value = name;
            opt.textContent = name;
            if (name === selected) opt.selected = true;
            select.appendChild(opt);
        });

        const remove = document.createElement('span');
        remove.className = 'remove-filter';
        remove.innerHTML = '&#x2716;';

        remove.addEventListener('click', () => {
            wrapper.remove();
            middlePane.dataset.selectedCustomer = '';
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (memoVal) params.set('memo', memoVal);
            loadView('make_bank_deposit', false, params.toString());
        });

        select.addEventListener('change', () => {
            middlePane.dataset.selectedCustomer = select.value;
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (select.value) params.set('customer', select.value);
            if (memoVal) params.set('memo', memoVal);
            loadView('make_bank_deposit', false, params.toString());
        });

        wrapper.appendChild(label);
        wrapper.appendChild(select);
        wrapper.appendChild(remove);
        container.appendChild(wrapper);
    }

    function createTypeFilter(types, selected) {
        const container = middlePane.querySelector('#mbdFilters');
        if (!container || container.querySelector('.type-filter')) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'filter-item type-filter';

        const label = document.createElement('label');
        label.textContent = 'Type:';

        const select = document.createElement('select');
        select.className = 'form-control';
        select.style.width = 'auto';

        const defOpt = document.createElement('option');
        defOpt.value = '';
        defOpt.textContent = '--All--';
        select.appendChild(defOpt);

        types.forEach(t => {
            const opt = document.createElement('option');
            opt.value = t;
            opt.textContent = t;
            if (t === selected) opt.selected = true;
            select.appendChild(opt);
        });

        const remove = document.createElement('span');
        remove.className = 'remove-filter';
        remove.innerHTML = '&#x2716;';

        remove.addEventListener('click', () => {
            wrapper.remove();
            middlePane.dataset.selectedType = '';
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const cust = middlePane.dataset.selectedCustomer || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const from = middlePane.dataset.fromDate || '';
            const to = middlePane.dataset.toDate || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (cust) params.set('customer', cust);
            if (memoVal) params.set('memo', memoVal);
            if (from) params.set('from_date', from);
            if (to) params.set('to_date', to);
            loadView('make_bank_deposit', false, params.toString());
        });

        select.addEventListener('change', () => {
            middlePane.dataset.selectedType = select.value;
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const cust = middlePane.dataset.selectedCustomer || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const from = middlePane.dataset.fromDate || '';
            const to = middlePane.dataset.toDate || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (cust) params.set('customer', cust);
            if (memoVal) params.set('memo', memoVal);
            if (from) params.set('from_date', from);
            if (to) params.set('to_date', to);
            if (select.value) params.set('type', select.value);
            loadView('make_bank_deposit', false, params.toString());
        });

        wrapper.appendChild(label);
        wrapper.appendChild(select);
        wrapper.appendChild(remove);
        container.appendChild(wrapper);
    }

    function createDateFilter(from, to) {
        const container = middlePane.querySelector('#mbdFilters');
        if (!container || container.querySelector('.date-filter')) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'filter-item date-filter';

        const labelFrom = document.createElement('label');
        labelFrom.textContent = 'From:';

        const inputFrom = document.createElement('input');
        inputFrom.type = 'date';
        inputFrom.className = 'form-control';
        inputFrom.style.width = 'auto';
        inputFrom.value = from || '';

        const labelTo = document.createElement('label');
        labelTo.textContent = 'To:';

        const inputTo = document.createElement('input');
        inputTo.type = 'date';
        inputTo.className = 'form-control';
        inputTo.style.width = 'auto';
        inputTo.value = to || '';

        const remove = document.createElement('span');
        remove.className = 'remove-filter';
        remove.innerHTML = '&#x2716;';

        remove.addEventListener('click', () => {
            wrapper.remove();
            middlePane.dataset.fromDate = '';
            middlePane.dataset.toDate = '';
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const cust = middlePane.dataset.selectedCustomer || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const typeVal = middlePane.dataset.selectedType || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (cust) params.set('customer', cust);
            if (memoVal) params.set('memo', memoVal);
            if (typeVal) params.set('type', typeVal);
            loadView('make_bank_deposit', false, params.toString());
        });

        function update() {
            middlePane.dataset.fromDate = inputFrom.value;
            middlePane.dataset.toDate = inputTo.value;
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const cust = middlePane.dataset.selectedCustomer || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const typeVal = middlePane.dataset.selectedType || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (cust) params.set('customer', cust);
            if (memoVal) params.set('memo', memoVal);
            if (typeVal) params.set('type', typeVal);
            if (inputFrom.value) params.set('from_date', inputFrom.value);
            if (inputTo.value) params.set('to_date', inputTo.value);
            loadView('make_bank_deposit', false, params.toString());
        }

        inputFrom.addEventListener('change', update);
        inputTo.addEventListener('change', update);

        wrapper.appendChild(labelFrom);
        wrapper.appendChild(inputFrom);
        wrapper.appendChild(labelTo);
        wrapper.appendChild(inputTo);
        wrapper.appendChild(remove);
        container.appendChild(wrapper);
    }

    function createMemoFilter(value) {
        const container = middlePane.querySelector('#mbdFilters');
        if (!container || container.querySelector('.memo-filter')) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'filter-item memo-filter';

        const label = document.createElement('label');
        label.textContent = 'Memo:';

        const input = document.createElement('input');
        input.type = 'text';
        input.className = 'form-control';
        input.style.width = 'auto';
        input.value = value || '';

        const remove = document.createElement('span');
        remove.className = 'remove-filter';
        remove.innerHTML = '&#x2716;';

        remove.addEventListener('click', () => {
            wrapper.remove();
            middlePane.dataset.memoFilter = '';
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const cust = middlePane.dataset.selectedCustomer || '';
            const typeVal = middlePane.dataset.selectedType || '';
            const from = middlePane.dataset.fromDate || '';
            const to = middlePane.dataset.toDate || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (cust) params.set('customer', cust);
            if (typeVal) params.set('type', typeVal);
            if (from) params.set('from_date', from);
            if (to) params.set('to_date', to);
            loadView('make_bank_deposit', false, params.toString());
        });

        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                middlePane.dataset.memoFilter = input.value.trim();
                const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
                const params = new URLSearchParams();
                if (limitVal) params.set('limit', limitVal);
                const cust = middlePane.dataset.selectedCustomer || '';
                const typeVal = middlePane.dataset.selectedType || '';
                const from = middlePane.dataset.fromDate || '';
                const to = middlePane.dataset.toDate || '';
                if (cust) params.set('customer', cust);
                if (typeVal) params.set('type', typeVal);
                if (from) params.set('from_date', from);
                if (to) params.set('to_date', to);
                if (input.value.trim()) params.set('memo', input.value.trim());
                loadView('make_bank_deposit', false, params.toString());
            }
        });

        wrapper.appendChild(label);
        wrapper.appendChild(input);
        wrapper.appendChild(remove);
        container.appendChild(wrapper);
    }

    function createReferenceFilter(value) {
        const container = middlePane.querySelector('#mbdFilters');
        if (!container || container.querySelector('.reference-filter')) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'filter-item reference-filter';

        const label = document.createElement('label');
        label.textContent = 'Reference:';

        const input = document.createElement('input');
        input.type = 'text';
        input.className = 'form-control';
        input.style.width = 'auto';
        input.value = value || '';

        const remove = document.createElement('span');
        remove.className = 'remove-filter';
        remove.innerHTML = '&#x2716;';

        remove.addEventListener('click', () => {
            wrapper.remove();
            middlePane.dataset.referenceFilter = '';
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const cust = middlePane.dataset.selectedCustomer || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const typeVal = middlePane.dataset.selectedType || '';
            const amountVal = middlePane.dataset.amountFilter || '';
            const from = middlePane.dataset.fromDate || '';
            const to = middlePane.dataset.toDate || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (cust) params.set('customer', cust);
            if (memoVal) params.set('memo', memoVal);
            if (typeVal) params.set('type', typeVal);
            if (amountVal) params.set('amount', amountVal);
            if (from) params.set('from_date', from);
            if (to) params.set('to_date', to);
            loadView('make_bank_deposit', false, params.toString());
        });

        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                middlePane.dataset.referenceFilter = input.value.trim();
                const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
                const params = new URLSearchParams();
                if (limitVal) params.set('limit', limitVal);
                const cust = middlePane.dataset.selectedCustomer || '';
                const memoVal = middlePane.dataset.memoFilter || '';
                const typeVal = middlePane.dataset.selectedType || '';
                const amountVal = middlePane.dataset.amountFilter || '';
                const from = middlePane.dataset.fromDate || '';
                const to = middlePane.dataset.toDate || '';
                if (cust) params.set('customer', cust);
                if (memoVal) params.set('memo', memoVal);
                if (typeVal) params.set('type', typeVal);
                if (amountVal) params.set('amount', amountVal);
                if (from) params.set('from_date', from);
                if (to) params.set('to_date', to);
                if (input.value.trim()) params.set('reference', input.value.trim());
                loadView('make_bank_deposit', false, params.toString());
            }
        });

        wrapper.appendChild(label);
        wrapper.appendChild(input);
        wrapper.appendChild(remove);
        container.appendChild(wrapper);
    }

    function createAmountFilter(value) {
        const container = middlePane.querySelector('#mbdFilters');
        if (!container || container.querySelector('.amount-filter')) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'filter-item amount-filter';

        const label = document.createElement('label');
        label.textContent = 'Amount:';

        const input = document.createElement('input');
        input.type = 'number';
        input.step = '0.01';
        input.className = 'form-control';
        input.style.width = 'auto';
        input.value = value || '';

        const remove = document.createElement('span');
        remove.className = 'remove-filter';
        remove.innerHTML = '&#x2716;';

        remove.addEventListener('click', () => {
            wrapper.remove();
            middlePane.dataset.amountFilter = '';
            const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
            const cust = middlePane.dataset.selectedCustomer || '';
            const memoVal = middlePane.dataset.memoFilter || '';
            const typeVal = middlePane.dataset.selectedType || '';
            const refVal = middlePane.dataset.referenceFilter || '';
            const from = middlePane.dataset.fromDate || '';
            const to = middlePane.dataset.toDate || '';
            const params = new URLSearchParams();
            if (limitVal) params.set('limit', limitVal);
            if (cust) params.set('customer', cust);
            if (memoVal) params.set('memo', memoVal);
            if (typeVal) params.set('type', typeVal);
            if (refVal) params.set('reference', refVal);
            if (from) params.set('from_date', from);
            if (to) params.set('to_date', to);
            loadView('make_bank_deposit', false, params.toString());
        });

        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                middlePane.dataset.amountFilter = input.value.trim();
                const limitVal = middlePane.querySelector('#limitSelect')?.value || '';
                const params = new URLSearchParams();
                if (limitVal) params.set('limit', limitVal);
                const cust = middlePane.dataset.selectedCustomer || '';
                const memoVal = middlePane.dataset.memoFilter || '';
                const typeVal = middlePane.dataset.selectedType || '';
                const refVal = middlePane.dataset.referenceFilter || '';
                const from = middlePane.dataset.fromDate || '';
                const to = middlePane.dataset.toDate || '';
                if (cust) params.set('customer', cust);
                if (memoVal) params.set('memo', memoVal);
                if (typeVal) params.set('type', typeVal);
                if (refVal) params.set('reference', refVal);
                if (from) params.set('from_date', from);
                if (to) params.set('to_date', to);
                if (input.value.trim()) params.set('amount', input.value.trim());
                loadView('make_bank_deposit', false, params.toString());
            }
        });

        wrapper.appendChild(label);
        wrapper.appendChild(input);
        wrapper.appendChild(remove);
        container.appendChild(wrapper);
    }

    function runBulkSelection(lines, field) {
        const rows = middlePane.querySelectorAll('table.uf-table tbody tr');
        const matched = [];
        const unmatched = [];

        lines.forEach(line => {
            let found = false;
            rows.forEach(row => {
                const memo = row.querySelector('.truncate-memo')?.textContent || '';
                const ref  = row.querySelector('.truncate-reference')?.textContent || '';
                const checkbox = row.querySelector('input[type="checkbox"][name="depositCheckbox[]"]');
                let match = false;
                if (field === 'memo') {
                    if (memo.includes(line)) match = true;
                } else if (field === 'reference') {
                    if (ref.includes(line)) match = true;
                } else {
                    if (memo.includes(line) || ref.includes(line)) match = true;
                }
                if (match) {
                    found = true;
                    if (checkbox && !checkbox.checked) {
                        checkbox.checked = true;
                        checkbox.dispatchEvent(new Event('change'));
                    }
                }
            });
            if (found) {
                matched.push(line);
            } else {
                unmatched.push(line);
            }
        });

        updateSelectedAmount();
        return { matched, unmatched };
    }

    function displayBulkResults(matched, unmatched) {
        const wrapper = middlePane.querySelector('#bulkFindDepositWrapper');
        if (!wrapper) return;

        let container = wrapper.querySelector('#bulkResultsContainer');
        if (!container) {
            container = document.createElement('div');
            container.id = 'bulkResultsContainer';
            container.className = 'bulk-find-results';

            const noDiv = document.createElement('div');
            noDiv.className = 'no-match flex-fill';
            const noLabel = document.createElement('div');
            noLabel.id = 'bulkNoMatchLabel';
            const noTa = document.createElement('textarea');
            noTa.id = 'bulkNoMatchTextarea';
            noTa.className = 'form-control';
            noTa.readOnly = true;
            noDiv.appendChild(noLabel);
            noDiv.appendChild(noTa);

            const matchDiv = document.createElement('div');
            matchDiv.className = 'match flex-fill';
            const matchLabel = document.createElement('div');
            matchLabel.id = 'bulkMatchLabel';
            const matchTa = document.createElement('textarea');
            matchTa.id = 'bulkMatchTextarea';
            matchTa.className = 'form-control';
            matchTa.readOnly = true;
            matchDiv.appendChild(matchLabel);
            matchDiv.appendChild(matchTa);

            container.appendChild(noDiv);
            container.appendChild(matchDiv);
            wrapper.appendChild(container);
        }

        container.querySelector('#bulkNoMatchLabel').textContent = `No matches Found for ${unmatched.length} entries`;
        container.querySelector('#bulkMatchLabel').textContent = `Matches Found for ${matched.length} entries`;
        container.querySelector('#bulkNoMatchTextarea').value = unmatched.join('\n');
        container.querySelector('#bulkMatchTextarea').value = matched.join('\n');

        const textarea = wrapper.querySelector('#bulkFindTextarea');
        if (textarea) textarea.style.display = 'none';
        container.style.display = 'flex';
    }

    function resetBulkResults() {
        const wrapper = middlePane.querySelector('#bulkFindDepositWrapper');
        if (!wrapper) return;
        const container = wrapper.querySelector('#bulkResultsContainer');
        const textarea = wrapper.querySelector('#bulkFindTextarea');
        if (container) container.style.display = 'none';
        if (textarea) textarea.style.display = '';
    }

    function attachBulkUploadForm() {
        const icon = middlePane.querySelector('#mbdUploadIcon');
        const wrapper = middlePane.querySelector('#bulkFindDepositWrapper');
        if (!icon || !wrapper) return;

        if (sessionStorage.getItem('bulkFindOpen') === '1') {
            wrapper.style.display = 'block';
            const textarea = wrapper.querySelector('#bulkFindTextarea');
            const fieldSel = wrapper.querySelector('#bulkFindField');
            if (textarea) textarea.value = sessionStorage.getItem('bulkFindTextSaved') || '';
            if (fieldSel) fieldSel.value = sessionStorage.getItem('bulkFindFieldSaved') || 'memo';
        }

        icon.addEventListener('click', () => {
            resetBulkResults();
            wrapper.style.display = 'block';
            sessionStorage.setItem('bulkFindOpen', '1');
        });

        const backBtn = wrapper.querySelector('#bulkGoBack');
        if (backBtn) {
            backBtn.addEventListener('click', () => {
                wrapper.style.display = 'none';
                resetBulkResults();
                sessionStorage.removeItem('bulkFindOpen');
                sessionStorage.removeItem('bulkFindTextSaved');
                sessionStorage.removeItem('bulkFindFieldSaved');
            });
        }

        const processBtn = wrapper.querySelector('#bulkProcess');
        if (processBtn) {
            processBtn.addEventListener('click', async () => {
                const textarea = wrapper.querySelector('#bulkFindTextarea');
                const fieldSel = wrapper.querySelector('#bulkFindField');
                if (!textarea || !fieldSel) return;
                const lines = textarea.value.split(/\r?\n/).map(t => t.trim()).filter(t => t);
                if (lines.length === 0) return;

                sessionStorage.setItem('bulkFindLines', JSON.stringify(lines));
                sessionStorage.setItem('bulkFindField', fieldSel.value);
                sessionStorage.setItem('bulkFindProcess', '1');
                sessionStorage.setItem('bulkFindOpen', '1');

                const params = new URLSearchParams();
                params.set('limit', 'ALL');
                const currentCustomer = middlePane.dataset.selectedCustomer || '';
                const memoVal = middlePane.dataset.memoFilter || '';
                if (currentCustomer) params.set('customer', currentCustomer);
                if (memoVal) params.set('memo', memoVal);
                await loadView('make_bank_deposit', false, params.toString());
            });
        }

        if (sessionStorage.getItem('bulkFindProcess') === '1') {
            const lines = JSON.parse(sessionStorage.getItem('bulkFindLines') || '[]');
            const field = sessionStorage.getItem('bulkFindField') || 'memo';
            sessionStorage.removeItem('bulkFindProcess');
            sessionStorage.removeItem('bulkFindLines');
            sessionStorage.removeItem('bulkFindField');
            const result = runBulkSelection(lines, field);
            displayBulkResults(result.matched, result.unmatched);
            const ta = wrapper.querySelector('#bulkFindTextarea');
            const fs = wrapper.querySelector('#bulkFindField');
            if (ta) ta.value = lines.join('\n');
            if (fs) fs.value = field;
            wrapper.style.display = 'block';
            sessionStorage.setItem('bulkFindOpen', '1');
        }
    }


    // Attach pagination click handling
    function attachPaginationClick(currentMode) {
        const paginationLinks = middlePane.querySelectorAll('.pagination a');
        paginationLinks.forEach(link => {
            link.addEventListener('click', async (evt) => {
                evt.preventDefault();
                const href = link.getAttribute('href') || '';
                const params = href.replace(/^\?/, '');
                await loadView(currentMode, false, params);
            });
        });
    }

    // Attach listeners for left pane buttons
    function attachLeftPaneButtonListeners() {
        const makeBankDepositBtn = leftPane.querySelector('#makeBankDepositBtn');
        const depositHistoryBtn = leftPane.querySelector('#depositHistoryBtn');
        const finalizeDepositBtn = leftPane.querySelector('#finalizeDepositBtn');
        const dateSelectorContainer = leftPane.querySelector('#dateSelectorContainer');

        // When loading the left pane while in pull or fetch modes, ensure selector exists
        if (['pull', 'fetch_sr', 'fetch_journal'].includes(selectEl.value)) {
            if (selectEl.value === 'fetch_sr') {
                injectDateSelector(dateSelectorContainer, 'fetch_sales_receipts', 'Fetch Sales Receipts');
            } else if (selectEl.value === 'fetch_journal') {
                injectDateSelector(dateSelectorContainer, 'fetch_journal_entries', 'Fetch Journal Entries');
            } else {
                injectDateSelector(dateSelectorContainer);
            }
        }

        // "Make Bank Deposit" button logic
        if (makeBankDepositBtn) {
            makeBankDepositBtn.addEventListener('click', async () => {
                sessionStorage.setItem('currentViewMode', 'make_bank_deposit');
                await loadView('make_bank_deposit', true);
                await loadLeftPane('make_bank_deposit');
            });
        }

        if (depositHistoryBtn) {
            depositHistoryBtn.addEventListener('click', () => {
                window.location.href = '/deposithistory';
            });
        }

        if (finalizeDepositBtn) {
            finalizeDepositBtn.addEventListener('click', () => {
                fetch('/undepositedfunds/createDeposit', {
                    method: 'POST',
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                .then(async r => {
                    let j;
                    try { j = await r.json(); } catch (e) { j = {}; }
                    if (!r.ok || !j.success) {
                        alert("Error creating deposit: " + (j.error || r.statusText));
                        return;
                    }
                    console.log('QBO payload', j.payload);
                    console.log('Created Deposit', j.deposit);
                    const cd = JSON.parse(sessionStorage.getItem('consoleData') || '[]');
                    cd.push({ type: 'deposit', data: j.deposit });
                    sessionStorage.setItem('consoleData', JSON.stringify(cd));
                    alert(`Deposit ${j.depositId} created`);
                    sessionStorage.removeItem('mbdSelections');
                    location.reload();
                });
            });
        }
        // Attach cancel (red X) after loading left pane
        attachCloseMakeDepositBtn();
        updateWrapperVisibility();
    }

    // Confirm Pull button handler (date selector)
    function attachConfirmPullBtn(dateSelectorContainer) {
        const confirmBtn = dateSelectorContainer.querySelector('#confirmPullBtn');
        const fromDate = dateSelectorContainer.querySelector('input[name="from_date"]');
        const toDate = dateSelectorContainer.querySelector('input[name="to_date"]');
        if (!confirmBtn || !fromDate || !toDate) {
            console.warn('ConfirmPullBtn or date inputs not found in dateSelectorContainer');
            return false;
        }

        // Remove any existing listeners to prevent duplicates
        confirmBtn.removeEventListener('click', handleConfirmPull);
        confirmBtn.addEventListener('click', handleConfirmPull);

        const action = confirmBtn.dataset.action || 'pull_undeposited';

        function handleConfirmPull() {
            if (!fromDate.value || !toDate.value) {
                alert('Please select both From Date and To Date');
                return;
            }
            showPullOverlay();
            fetch('/undepositedfunds', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: new URLSearchParams({
                    action: action,
                    from_date: fromDate.value,
                    to_date: toDate.value
                })
            })
            .then(response => {
                if (!response.ok) throw new Error(`Network error: ${response.statusText}`);
                return response.text();
            })
            .then(data => {
                hidePullOverlay();
                window.location.reload();
            })
            .catch(err => {
                hidePullOverlay();
                alert('Error pulling data: ' + err.message);
            });
        }
        return true;
    }

    // Red X/cancel handler for make deposit view (ALWAYS attach directly from leftPane)
    function attachCloseMakeDepositBtn() {
        const closeBtn = leftPane.querySelector('#closeMakeDepositBtn');
        if (!closeBtn) return;
        closeBtn.addEventListener('click', async () => {
            console.log('RED X CLICKED'); // Debug: remove this line if not needed
            await fetch('/undepositedfunds/clearSelected', { method: 'POST' });
            sessionStorage.removeItem('mbdSelections');
            sessionStorage.setItem('currentViewMode', 'manage');
            await loadView('manage', true);
            await loadLeftPane('manage');
            if (selectEl) selectEl.value = 'manage';
            updateWrapperVisibility();
        });
    }

    // If the current default is make_bank_deposit, load it
    if (selectEl.value === 'make_bank_deposit') {
        loadView('make_bank_deposit');
        loadLeftPane('make_bank_deposit');
    }
});
