<script>
document.addEventListener('DOMContentLoaded', function () {
    initGlAccountPicker();
});

function initGlAccountPicker() {
    var picker = document.getElementById('glAccountPicker');
    if (!picker) {
        return;
    }

    var tree = [];
    var selected = new Set();
    var allLedger = false;

    try {
        var treeElData = document.getElementById('glAccountPickerTreeData');
        tree = JSON.parse(treeElData?.textContent || '[]');
        JSON.parse(picker.dataset.selected || '[]').forEach(function (id) {
            if (id) {
                selected.add(String(id));
            }
        });
        allLedger = picker.dataset.allLedger === 'true' || picker.dataset.allLedger === '1';
    } catch (error) {
        tree = [];
        selected = new Set();
    }

    var toggleBtn = document.getElementById('glAccountPickerToggle');
    var menu = document.getElementById('glAccountPickerMenu');
    var treeEl = document.getElementById('glAccountPickerTree');
    var searchInput = document.getElementById('glAccountPickerSearch');
    var emptyEl = document.getElementById('glAccountPickerEmpty');
    var labelEl = document.getElementById('glAccountPickerLabel');
    var inputsEl = document.getElementById('glAccountPickerInputs');
    var allLedgerInput = document.getElementById('glAllLedgerInput');
    var allLedgerCheckbox = document.getElementById('glAccountPickerAllLedger');
    var clearBtn = document.getElementById('glAccountPickerClear');
    var expanded = new Set();
    var labelMap = {};
    var portalClass = 'voucher-account-picker-menu--portal';

    function walk(nodes, fn) {
        nodes.forEach(function (node) {
            fn(node);
            if (node.children && node.children.length) {
                walk(node.children, fn);
            }
        });
    }

    walk(tree, function (node) {
        if (node.selectable && node.value) {
            labelMap[node.value] = (node.code ? '[' + node.code + '] ' : '') + node.name;
        } else if (node.children && node.children.length) {
            expanded.add(String(node.id));
        }
    });

    function escapeHtml(value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function syncInputs() {
        if (!inputsEl) {
            return;
        }

        inputsEl.innerHTML = '';
        var allInput = document.createElement('input');
        allInput.type = 'hidden';
        allInput.name = 'all_ledger';
        allInput.id = 'glAllLedgerInput';
        allInput.value = allLedger ? '1' : '';
        inputsEl.appendChild(allInput);
        allLedgerInput = allInput;

        if (!allLedger) {
            Array.from(selected).sort(function (a, b) {
                return Number(a) - Number(b);
            }).forEach(function (id) {
                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'account_ids[]';
                input.value = id;
                inputsEl.appendChild(input);
            });
        }
    }

    function syncLabel() {
        if (!labelEl) {
            return;
        }

        if (allLedger) {
            labelEl.textContent = 'All Ledger';
            return;
        }

        if (selected.size === 0) {
            labelEl.textContent = 'Select account(s)';
            return;
        }

        if (selected.size === 1) {
            var only = Array.from(selected)[0];
            labelEl.textContent = labelMap[only] || '1 account selected';
            return;
        }

        labelEl.textContent = selected.size + ' accounts selected';
    }

    function nodeMatches(node, term) {
        if (!term) {
            return true;
        }

        var haystack = ((node.code || '') + ' ' + (node.name || '') + ' ' + (node.type_label || '')).toLowerCase();
        return haystack.indexOf(term) !== -1;
    }

    function subtreeMatches(node, term) {
        if (!term) {
            return true;
        }

        if (nodeMatches(node, term)) {
            return true;
        }

        return (node.children || []).some(function (child) {
            return subtreeMatches(child, term);
        });
    }

    function renderNodes(nodes, depth) {
        return nodes.map(function (node) {
            var id = String(node.id);
            var term = (searchInput?.value || '').trim().toLowerCase();
            var hasChildren = !!(node.children && node.children.length);

            if (term && !subtreeMatches(node, term)) {
                return '';
            }

            if (!node.selectable) {
                var groupChildren = renderNodes(node.children || [], depth + 1);
                if (!groupChildren) {
                    return '';
                }

                return `
                    <div class="voucher-account-picker-item voucher-account-picker-item-group" style="padding-left:${depth * 16}px">
                        <button type="button" class="voucher-account-picker-toggle-btn ${hasChildren ? '' : 'is-hidden'}" data-gl-account-expand="${id}" aria-label="Expand">
                            <i class="bi ${expanded.has(id) ? 'bi-chevron-down' : 'bi-chevron-right'}" style="font-size:11px"></i>
                        </button>
                        <div class="voucher-account-picker-group">${escapeHtml(node.name)}</div>
                    </div>
                    <div class="${expanded.has(id) ? '' : 'd-none'}" data-gl-account-children="${id}">
                        ${groupChildren}
                    </div>
                `;
            }

            var childHtml = hasChildren && expanded.has(id) ? renderNodes(node.children, depth + 1) : '';
            var isSelected = selected.has(node.value);

            return `
                <div class="voucher-account-picker-item voucher-account-picker-row ${isSelected ? 'is-selected' : ''}"
                     style="padding-left:${depth * 16}px">
                    <button type="button" class="voucher-account-picker-toggle-btn ${hasChildren ? '' : 'is-hidden'}" data-gl-account-expand="${id}" aria-label="Expand">
                        <i class="bi ${expanded.has(id) ? 'bi-chevron-down' : 'bi-chevron-right'}" style="font-size:11px"></i>
                    </button>
                    <label class="gl-account-picker-choice">
                        <input type="checkbox" value="${escapeHtml(node.value)}" data-gl-account-checkbox ${isSelected ? 'checked' : ''} ${allLedger ? 'disabled' : ''}>
                    </label>
                    <span class="voucher-account-picker-code">${escapeHtml(node.code || '—')}</span>
                    <span class="voucher-account-picker-name">${escapeHtml(node.name || '')}</span>
                    <span class="voucher-account-picker-type">${escapeHtml(node.type_label || '')}</span>
                </div>
                ${hasChildren ? `<div class="${expanded.has(id) ? '' : 'd-none'}" data-gl-account-children="${id}">${childHtml}</div>` : ''}
            `;
        }).join('');
    }

    function renderTree() {
        if (!treeEl) {
            return;
        }

        var html = renderNodes(tree, 0);
        treeEl.innerHTML = html;
        var hasRows = html.trim() !== '';
        emptyEl?.classList.toggle('d-none', hasRows);
        treeEl.classList.toggle('d-none', !hasRows);
    }

    function positionMenu() {
        if (!toggleBtn || !menu) {
            return;
        }

        var rect = toggleBtn.getBoundingClientRect();
        var minWidth = Math.max(rect.width, 560);
        menu.style.position = 'fixed';
        menu.style.left = Math.max(8, Math.min(rect.left, window.innerWidth - minWidth - 8)) + 'px';
        menu.style.minWidth = minWidth + 'px';
        menu.style.maxWidth = Math.min(720, window.innerWidth - 16) + 'px';
        menu.style.zIndex = '1200';

        menu.classList.remove('d-none');
        var menuHeight = menu.offsetHeight || 420;
        var top = rect.bottom + 4;
        if (top + menuHeight > window.innerHeight - 8) {
            top = Math.max(8, rect.top - menuHeight - 4);
        }
        menu.style.top = top + 'px';
    }

    function openMenu() {
        if (!menu || !toggleBtn) {
            return;
        }

        document.body.appendChild(menu);
        menu.classList.add(portalClass);
        menu.classList.remove('d-none');
        toggleBtn.setAttribute('aria-expanded', 'true');
        positionMenu();
        searchInput?.focus();
    }

    function closeMenu() {
        if (!menu || !toggleBtn) {
            return;
        }

        menu.classList.add('d-none');
        menu.classList.remove(portalClass);
        toggleBtn.setAttribute('aria-expanded', 'false');
        menu.style.position = '';
        menu.style.top = '';
        menu.style.left = '';
        menu.style.minWidth = '';
        menu.style.maxWidth = '';
        menu.style.zIndex = '';

        if (menu.parentElement !== picker) {
            picker.appendChild(menu);
        }
    }

    toggleBtn?.addEventListener('click', function (event) {
        event.preventDefault();
        event.stopPropagation();
        var isOpen = menu && !menu.classList.contains('d-none') && menu.classList.contains(portalClass);
        if (isOpen) {
            closeMenu();
            return;
        }
        openMenu();
    });

    document.addEventListener('click', function (event) {
        if (!picker.contains(event.target) && !menu?.contains(event.target)) {
            closeMenu();
        }
    });

    window.addEventListener('resize', function () {
        if (menu && menu.classList.contains(portalClass) && !menu.classList.contains('d-none')) {
            positionMenu();
        }
    });

    treeEl?.addEventListener('click', function (event) {
        var expandBtn = event.target.closest('[data-gl-account-expand]');
        if (expandBtn) {
            event.preventDefault();
            event.stopPropagation();
            var nodeId = expandBtn.getAttribute('data-gl-account-expand');
            if (expanded.has(nodeId)) {
                expanded.delete(nodeId);
            } else {
                expanded.add(nodeId);
            }
            renderTree();
        }
    });

    treeEl?.addEventListener('change', function (event) {
        var checkbox = event.target.closest('[data-gl-account-checkbox]');
        if (!checkbox || allLedger) {
            return;
        }

        if (checkbox.checked) {
            selected.add(checkbox.value);
        } else {
            selected.delete(checkbox.value);
        }

        syncInputs();
        syncLabel();
        renderTree();
    });

    allLedgerCheckbox?.addEventListener('change', function () {
        allLedger = allLedgerCheckbox.checked;
        if (allLedger) {
            selected.clear();
        }
        syncInputs();
        syncLabel();
        renderTree();
    });

    searchInput?.addEventListener('input', function () {
        if (searchInput.value.trim()) {
            walk(tree, function (node) {
                if (node.children && node.children.length) {
                    expanded.add(String(node.id));
                }
            });
        }
        renderTree();
    });

    clearBtn?.addEventListener('click', function () {
        allLedger = false;
        selected.clear();
        if (allLedgerCheckbox) {
            allLedgerCheckbox.checked = false;
        }
        if (searchInput) {
            searchInput.value = '';
        }
        syncInputs();
        syncLabel();
        renderTree();
    });

    document.getElementById('glReportFilterForm')?.addEventListener('submit', function (event) {
        if (!allLedger && selected.size === 0) {
            event.preventDefault();
            window.alert('Please select All Ledger or at least one account.');
        }
    });

    syncInputs();
    syncLabel();
    renderTree();
}
</script>
<?php /**PATH /home/duiclick/public_html/test.duiclick.com/resources/views/reports/general-ledger/_account-picker-scripts.blade.php ENDPATH**/ ?>