window.BillingUnitPicker = (function () {
    let unitsCatalog = [];
    let storeUrl = '';
    let csrfToken = '';

    function formatLabel(u) {
        const label = `${u.name} (${u.code})`;
        return u.gst ? `${label} - GST` : label;
    }

    function setCatalog(units) {
        unitsCatalog = units || [];
    }

    function configure(opts) {
        storeUrl = opts.storeUrl || '';
        csrfToken = opts.csrfToken || '';
        setCatalog(opts.units || []);
    }

    function findUnit(code) {
        return unitsCatalog.find(u => u.code === code);
    }

    function renderList(picker, filter) {
        const list = picker.querySelector('.billing-unit-picker__list');
        if (!list) return;
        const q = (filter || '').toLowerCase();
        const filtered = unitsCatalog.filter(u =>
            !q || u.label.toLowerCase().includes(q) || u.code.toLowerCase().includes(q) || u.name.toLowerCase().includes(q)
        );

        list.innerHTML = filtered.map(u => `
            <li class="billing-unit-picker__option ${u.gst ? 'is-gst' : ''}" role="option" data-code="${u.code}" tabindex="0">
                ${u.gst ? `<strong>${u.label}</strong>` : u.label}
            </li>
        `).join('') || '<li class="billing-unit-picker__empty text-muted small px-2 py-2">No units found</li>';
    }

    function selectUnit(picker, code) {
        const hidden = picker.querySelector('[data-field="unit"]');
        const label = picker.querySelector('.billing-unit-picker__label');
        const unit = findUnit(code);
        if (hidden) hidden.value = code;
        if (label) {
            label.textContent = unit ? unit.label : code;
            label.classList.remove('text-muted');
        }
        closeAll();
        hidden?.dispatchEvent(new Event('change', { bubbles: true }));
    }

    function closeAll() {
        document.querySelectorAll('.billing-unit-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';

        const hidden = picker.querySelector('[data-field="unit"]');
        const label = picker.querySelector('.billing-unit-picker__label');
        const placeholder = picker.dataset.placeholder || 'Select unit';
        if (hidden?.value) {
            const unit = findUnit(hidden.value);
            if (label) label.textContent = unit ? unit.label : hidden.value;
        } else if (label && picker.dataset.optional) {
            label.textContent = placeholder;
            label.classList.add('text-muted');
        }

        picker.querySelector('.billing-unit-picker__trigger')?.addEventListener('click', e => {
            e.preventDefault();
            e.stopPropagation();
            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-unit-picker__option');
            if (opt?.dataset.code) selectUnit(picker, opt.dataset.code);
        });

        picker.querySelector('.billing-unit-picker__add')?.addEventListener('click', e => {
            e.preventDefault();
            e.stopPropagation();
            const modalEl = document.getElementById('modal-add-unit');
            if (modalEl && window.bootstrap?.Modal) {
                bootstrap.Modal.getOrCreateInstance(modalEl).show();
            } else if (modalEl) {
                modalEl.classList.add('show');
                modalEl.style.display = 'block';
                document.body.classList.add('modal-open');
            }
            window._pendingUnitPicker = picker;
        });
    }

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

    function addUnit(unit) {
        if (!unitsCatalog.find(u => u.code === unit.code)) {
            unitsCatalog.push(unit);
            unitsCatalog.sort((a, b) => a.name.localeCompare(b.name));
        }
        if (window._pendingUnitPicker) {
            selectUnit(window._pendingUnitPicker, unit.code);
            window._pendingUnitPicker = null;
        }
        initAll();
    }

    async function submitNewUnit(form) {
        const fd = new FormData(form);
        const res = await fetch(storeUrl, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: fd,
        });
        const data = await res.json();
        if (data.success) {
            setCatalog(data.units);
            addUnit(data.unit);
            return true;
        }
        return false;
    }

    document.addEventListener('click', e => {
        if (!e.target.closest('.billing-unit-picker')) closeAll();
    });

    return { configure, initAll, initPicker, setCatalog, addUnit, submitNewUnit, formatLabel };
})();
