window.BillingClientPicker = (function () {
    let clientsCatalog = [];
    let editPattern = '';

    function formatLabel(c) {
        const city = c.city ? ` - ${c.city}` : '';
        return (c.name || '') + city;
    }

    function setCatalog(clients) {
        clientsCatalog = clients || [];
    }

    function addClient(client) {
        const idx = clientsCatalog.findIndex(c => c.id === client.id);
        if (idx >= 0) {
            clientsCatalog[idx] = client;
        } else {
            clientsCatalog.push(client);
            clientsCatalog.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
        }
        if (window.__billingClients) {
            const g = window.__billingClients.findIndex(c => c.id === client.id);
            if (g >= 0) {
                window.__billingClients[g] = client;
            } else {
                window.__billingClients.push(client);
            }
        }
        document.dispatchEvent(new CustomEvent('billing-client-added', { detail: client }));
    }

    function findClient(id) {
        if (id == null || id === '') return null;
        return clientsCatalog.find(c => String(c.id) === String(id)) || null;
    }

    function renderList(picker, filter) {
        const list = picker.querySelector('.billing-unit-picker__list');
        if (!list) return;
        const q = (filter || '').toLowerCase();
        const filtered = clientsCatalog.filter(c => {
            if (!q) return true;
            const hay = `${c.name} ${c.city || ''} ${c.gstin || ''}`.toLowerCase();
            return hay.includes(q);
        });

        list.innerHTML = filtered.map(c => `
            <li class="billing-unit-picker__option billing-client-picker__option" role="option" data-id="${c.id}" tabindex="0">
                <span class="billing-client-picker__name">${escapeHtml(formatLabel(c))}</span>
                <a href="${(editPattern || '').replace('__ID__', c.id)}" class="billing-client-picker__edit" title="Edit client" target="_blank" rel="noopener" onclick="event.stopPropagation()">
                    <i class="ri-pencil-line"></i>
                </a>
            </li>
        `).join('') || '<li class="billing-unit-picker__empty text-muted small px-2 py-2">No clients found</li>';
    }

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

    function selectClient(picker, id) {
        const hidden = picker.querySelector('[data-field="customer_id"]');
        const label = picker.querySelector('.billing-unit-picker__label');
        const client = findClient(id);
        if (hidden) hidden.value = client ? String(client.id) : '';
        if (label) {
            label.textContent = client ? formatLabel(client) : (picker.dataset.placeholder || 'Select Client');
            label.classList.toggle('text-muted', !client);
            label.title = client ? formatLabel(client) : '';
        }
        closeAll();
        if (hidden) {
            hidden.dispatchEvent(new Event('change', { bubbles: true }));
            hidden.dispatchEvent(new CustomEvent('billing-customer-changed', {
                bubbles: true,
                detail: { customerId: client ? client.id : null, customer: client },
            }));
        }
        if (window.BillingGstForm && typeof window.BillingGstForm.applyCustomer === 'function') {
            window.BillingGstForm.applyCustomer(client ? client.id : '');
        }
    }

    function closeAll() {
        document.querySelectorAll('[data-client-picker]').forEach(p => {
            p.querySelector('.billing-unit-picker__dropdown')?.classList.add('d-none');
            p.querySelector('.billing-unit-picker__trigger')?.setAttribute('aria-expanded', 'false');
        });
    }

    function openPicker(picker) {
        closeAll();
        const dd = picker.querySelector('.billing-unit-picker__dropdown');
        const search = picker.querySelector('.billing-unit-picker__search');
        dd?.classList.remove('d-none');
        picker.querySelector('.billing-unit-picker__trigger')?.setAttribute('aria-expanded', 'true');
        renderList(picker, '');
        if (search) {
            search.value = '';
            setTimeout(() => search.focus(), 50);
        }
    }

    function initPicker(picker) {
        if (picker.dataset.initialized) return;
        picker.dataset.initialized = '1';
        editPattern = window.__billingClientEditPattern || editPattern;

        const hidden = picker.querySelector('[data-field="customer_id"]');
        const label = picker.querySelector('.billing-unit-picker__label');
        const placeholder = picker.dataset.placeholder || 'Select Client';
        if (!hidden?.value) {
            if (label) {
                label.textContent = placeholder;
                label.classList.add('text-muted');
            }
        } else {
            const client = findClient(parseInt(hidden.value, 10));
            if (client && label) {
                label.textContent = formatLabel(client);
                label.classList.remove('text-muted');
            }
        }

        picker.querySelector('.billing-unit-picker__trigger')?.addEventListener('click', e => {
            e.preventDefault();
            const dd = picker.querySelector('.billing-unit-picker__dropdown');
            if (dd?.classList.contains('d-none')) openPicker(picker);
            else closeAll();
        });

        picker.querySelector('.billing-unit-picker__search')?.addEventListener('input', e => {
            renderList(picker, e.target.value);
        });

        picker.querySelector('.billing-unit-picker__list')?.addEventListener('click', e => {
            const opt = e.target.closest('.billing-client-picker__option');
            if (!opt) return;
            selectClient(picker, parseInt(opt.dataset.id, 10));
        });

        picker.querySelector('.billing-client-picker__add')?.addEventListener('click', e => {
            e.preventDefault();
            closeAll();
            if (window.BillingQuickClient) {
                BillingQuickClient.open();
            }
        });
    }

    function initAll(root) {
        root = root || document;
        root.querySelectorAll('[data-client-picker]').forEach(initPicker);
    }

    function configure(opts) {
        setCatalog(opts.clients || window.__billingClients || []);
        if (opts.editPattern) editPattern = opts.editPattern;
    }

    document.addEventListener('click', e => {
        if (!e.target.closest('[data-client-picker]')) closeAll();
    });

    return {
        configure,
        setCatalog,
        addClient,
        findClient,
        selectClient,
        initAll,
        initPicker,
        formatLabel,
    };
})();
