(function () {
    const form = document.querySelector('form.billing-item-form');
    if (!form || !window.BillingUnitPicker || !window.__billingUnits) {
        return;
    }

    BillingUnitPicker.configure({
        units: window.__billingUnits,
        storeUrl: window.__billingUnitsStore,
        csrfToken: window.__billingCsrf || document.querySelector('meta[name="csrf-token"]')?.content,
    });
    BillingUnitPicker.initAll(form);

    document.getElementById('form-add-unit')?.addEventListener('submit', async function (e) {
        e.preventDefault();
        const ok = await BillingUnitPicker.submitNewUnit(this);
        if (!ok) {
            return;
        }

        const modal = document.getElementById('modal-add-unit');
        if (window.bootstrap?.Modal) {
            bootstrap.Modal.getOrCreateInstance(modal).hide();
        } else {
            modal?.classList.remove('show');
            modal.style.display = 'none';
            document.body.classList.remove('modal-open');
        }
        this.reset();
    });
})();
