window.BillingQuickClient = (function () {
    let contactIndex = 0;
    let onSaved = null;

    function options() {
        return window.__billingClientOptions || {};
    }

    function fillSelect(el, items, selected, leadingHtml) {
        if (!el) return;
        el.innerHTML = leadingHtml || '';
        if (Array.isArray(items)) {
            items.forEach(v => {
                const opt = document.createElement('option');
                opt.value = v;
                opt.textContent = v;
                if (v === selected) opt.selected = true;
                el.appendChild(opt);
            });
            return;
        }
        Object.entries(items).forEach(([k, label]) => {
            const opt = document.createElement('option');
            opt.value = k;
            opt.textContent = label;
            if (k === selected) opt.selected = true;
            el.appendChild(opt);
        });
    }

    function initModalOptions() {
        const opts = options();
        fillSelect(document.getElementById('quick_gst_treatment'), opts.gstTreatments || {}, '', '<option value="">Select a GST Treatment</option>');
        fillSelect(document.getElementById('quick_currency'), opts.currencies || ['INR'], 'INR');
        fillSelect(document.getElementById('quick_country'), opts.countries || ['India'], 'India');
        fillSelect(document.getElementById('quick_shipping_country'), opts.countries || ['India'], 'India');

        const stateEl = document.getElementById('quick_state');
        const shipStateEl = document.getElementById('quick_shipping_state');
        [stateEl, shipStateEl].forEach(sel => {
            if (!sel) return;
            sel.innerHTML = '<option value="">Select State</option>';
            (opts.indianStates || []).forEach(state => {
                const opt = document.createElement('option');
                opt.value = state;
                opt.textContent = state;
                sel.appendChild(opt);
            });
        });
    }

    function resetForm() {
        const form = document.getElementById('form-quick-client');
        form?.reset();
        document.getElementById('quick-extra-contacts').innerHTML = '';
        contactIndex = 0;
        const shipFields = document.getElementById('quick-shipping-fields');
        if (shipFields) shipFields.classList.add('d-none');
        const shipCb = document.getElementById('quick_has_shipping');
        if (shipCb) shipCb.checked = false;
        document.querySelectorAll('#quickClientAccordion .accordion-collapse.show').forEach(el => {
            if (window.bootstrap?.Collapse) {
                bootstrap.Collapse.getOrCreateInstance(el, { toggle: false }).hide();
            }
        });
        const err = document.getElementById('quick-client-errors');
        if (err) {
            err.classList.add('d-none');
            err.innerHTML = '';
        }
        initModalOptions();
    }

    function showErrors(messages) {
        const err = document.getElementById('quick-client-errors');
        if (!err) return;
        if (!messages.length) {
            err.classList.add('d-none');
            return;
        }
        err.classList.remove('d-none');
        err.innerHTML = messages.map(m => `<div>${m}</div>`).join('');
    }

    function collectFormData(form) {
        const fd = new FormData(form);
        const data = {};
        fd.forEach((val, key) => {
            if (key.startsWith('additional_contacts')) return;
            data[key] = val;
        });
        data.also_use_as_vendor = form.querySelector('[name="also_use_as_vendor"]')?.checked ? 1 : 0;
        data.client_wise_item_price = form.querySelector('[name="client_wise_item_price"]')?.checked ? 1 : 0;
        data.has_shipping_address = form.querySelector('[name="has_shipping_address"]')?.checked ? 1 : 0;

        const contacts = [];
        form.querySelectorAll('.quick-extra-contact-row').forEach(row => {
            const name = row.querySelector('[name*="[name]"]')?.value?.trim();
            const phone = row.querySelector('[name*="[phone]"]')?.value?.trim();
            const email = row.querySelector('[name*="[email]"]')?.value?.trim();
            if (name || phone || email) {
                contacts.push({ name, phone, email });
            }
        });
        data.additional_contacts = contacts;
        return data;
    }

    async function submitForm(e) {
        e.preventDefault();
        const form = document.getElementById('form-quick-client');
        const url = window.__billingClientQuickStore;
        if (!form || !url) return;

        showErrors([]);
        const data = collectFormData(form);
        const res = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': window.__billingCsrf || '',
                'X-Requested-With': 'XMLHttpRequest',
            },
            body: JSON.stringify(data),
        });

        const json = await res.json().catch(() => ({}));
        if (!res.ok) {
            const msgs = json.errors
                ? Object.values(json.errors).flat()
                : [json.message || 'Could not save client.'];
            showErrors(msgs);
            return;
        }

        if (json.customer && window.BillingClientPicker) {
            BillingClientPicker.addClient(json.customer);
            const picker = document.querySelector('[data-client-picker]');
            if (picker) {
                BillingClientPicker.selectClient(picker, json.customer.id);
            }
        }

        const modalEl = document.getElementById('modal-quick-client');
        if (modalEl && window.bootstrap?.Modal) {
            bootstrap.Modal.getOrCreateInstance(modalEl).hide();
        }
        resetForm();
        if (typeof onSaved === 'function') {
            onSaved(json.customer);
        }
    }

    function open(callback) {
        onSaved = callback || null;
        resetForm();
        const modalEl = document.getElementById('modal-quick-client');
        if (modalEl && window.bootstrap?.Modal) {
            bootstrap.Modal.getOrCreateInstance(modalEl).show();
        }
    }

    function bindEvents() {
        document.getElementById('form-quick-client')?.addEventListener('submit', submitForm);

        document.getElementById('quick_has_shipping')?.addEventListener('change', function () {
            const fields = document.getElementById('quick-shipping-fields');
            const collapse = document.getElementById('qcShipping');
            fields?.classList.toggle('d-none', !this.checked);
            if (this.checked && collapse && window.bootstrap?.Collapse) {
                bootstrap.Collapse.getOrCreateInstance(collapse, { toggle: false }).show();
            }
        });

        document.getElementById('quick-btn-add-contact')?.addEventListener('click', () => {
            const wrap = document.getElementById('quick-extra-contacts');
            const html = `
                <div class="quick-extra-contact-row border rounded p-2 mb-2" data-index="${contactIndex}">
                    <div class="row g-2">
                        <div class="col-md-4">
                            <label class="form-label small">Contact person</label>
                            <input type="text" name="additional_contacts[${contactIndex}][name]" class="form-control form-control-sm">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small">Contact phone</label>
                            <input type="text" name="additional_contacts[${contactIndex}][phone]" class="form-control form-control-sm">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small">Contact email</label>
                            <input type="email" name="additional_contacts[${contactIndex}][email]" class="form-control form-control-sm">
                        </div>
                    </div>
                </div>`;
            wrap.insertAdjacentHTML('beforeend', html);
            contactIndex++;
        });

        document.getElementById('quick-btn-fetch-gstin')?.addEventListener('click', () => {
            const gstin = document.getElementById('quick_gstin')?.value?.trim();
            if (!gstin || gstin.length !== 15) {
                alert('Please enter a valid 15-character GSTIN.');
                return;
            }
            alert('GSTIN fetch API can be connected here. For now, please enter details manually.');
        });
    }

    document.addEventListener('DOMContentLoaded', () => {
        initModalOptions();
        bindEvents();
    });

    return { open, resetForm };
})();
