/**
 * Inline customer change for Quote Details and Job Details pages.
 * Uses a plain native <select> (always visible, pre-set to current customer).
 * When the user picks a different customer, an inline confirmation banner appears.
 * Confirms → AJAX POST to ChangeCustomer action → success toast.
 * Cancels  → reverts the select to the original value.
 * No TomSelect dependency — Details pages don't load that library.
 */
(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {

        document.querySelectorAll('.cc-select').forEach(function (select) {
            var wrap      = select.closest('[data-cc-wrap]');
            var banner    = wrap.querySelector('.cc-confirm-banner');
            var bannerMsg = wrap.querySelector('.cc-confirm-text');
            var saveBtn   = wrap.querySelector('[data-cc-save]');
            var cancelBtn = wrap.querySelector('[data-cc-cancel]');
            var errorEl   = wrap.querySelector('.cc-error');

            var originalValue = select.value;

            select.addEventListener('change', function () {
                if (select.value === originalValue) {
                    banner.classList.add('d-none');
                    return;
                }
                var name = select.options[select.selectedIndex].text;
                bannerMsg.textContent = 'Change customer to “' + name + '”?';
                banner.classList.remove('d-none');
                if (errorEl) errorEl.classList.add('d-none');
            });

            cancelBtn.addEventListener('click', function () {
                select.value = originalValue;
                banner.classList.add('d-none');
                if (errorEl) errorEl.classList.add('d-none');
            });

            saveBtn.addEventListener('click', async function () {
                var token = (document.querySelector('input[name="__RequestVerificationToken"]') || {}).value;
                saveBtn.disabled = true;

                var formData = new FormData();
                formData.append('id', wrap.dataset.ccId);
                formData.append('customerId', select.value);

                try {
                    var resp = await fetch(wrap.dataset.ccUrl, {
                        method: 'POST',
                        headers: { 'RequestVerificationToken': token || '' },
                        body: formData
                    });

                    if (!resp.ok) throw new Error('HTTP ' + resp.status);
                    var result = await resp.json();

                    if (result.success) {
                        originalValue = select.value;
                        banner.classList.add('d-none');
                        showToast('Customer updated to “' + result.customerName + '”.', 'success');
                    } else {
                        if (errorEl) {
                            errorEl.textContent = result.error || 'Failed to update customer.';
                            errorEl.classList.remove('d-none');
                        }
                    }
                } catch (e) {
                    if (errorEl) {
                        errorEl.textContent = 'Network error. Please try again.';
                        errorEl.classList.remove('d-none');
                    }
                } finally {
                    saveBtn.disabled = false;
                }
            });
        });
    });

    function showToast(msg, type) {
        var t = document.createElement('div');
        t.className = 'toast align-items-center text-bg-' + type + ' border-0 position-fixed bottom-0 end-0 m-3';
        t.style.zIndex = '1100';
        t.setAttribute('role', 'alert');
        t.innerHTML = '<div class="d-flex"><div class="toast-body">' + msg + '</div>'
            + '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div>';
        document.body.appendChild(t);
        new bootstrap.Toast(t, { delay: 3500 }).show();
        t.addEventListener('hidden.bs.toast', function () { t.remove(); });
    }

})();
