(function() {
    // The customer lookup map (id => contact fields + known addresses) is
    // attached before this file by the job form via wp_add_inline_script.
    var customerData = window.paintopsCustomerPickerData || {};

    // Looked up fresh each time rather than cached once at script-load,
    // this script tag runs before #customerManualFields even exists in the
    // DOM (it's markup further down the page), so caching the element
    // here would permanently cache a null reference and the "+ New
    // Customer" option would silently never reveal the fields.
    function getManualFieldsBox() {
        return document.getElementById('customerManualFields');
    }

    document.addEventListener('change', function(e) {
        if (e.target.id !== 'existingCustomerPicker') return;

        var picked = e.target.value;
        var manualFieldsBox = getManualFieldsBox();

        // "+ New Customer", or resetting back to the blank "-- Select --"
        // option, either way nobody's chosen a known customer, so the
        // manual fields need to be visible (and blank) so there's an
        // actual way to type someone in.
        if (picked === '__new__' || picked === '') {
            document.getElementById('selected_customer_id').value = '';
            ['custFirst', 'custLast', 'custServiceAddress', 'custServiceCity', 'custServiceState', 'custServiceZip', 'custPhone', 'custEmail'].forEach(function(fieldId) {
                var field = document.getElementById(fieldId);
                if (field) field.value = '';
            });
            if (manualFieldsBox) manualFieldsBox.classList.add('show');
            return;
        }

        // Picking a real, known customer fills the fields behind the
        // scenes and keeps them collapsed, BUT the chosen service address
        // must stay visible (Mike's report: it used to vanish entirely),
        // the always-shown address select below is that confirmation.
        if (manualFieldsBox) manualFieldsBox.classList.remove('show');

        if (!customerData[picked]) {
            return;
        }

        document.getElementById('selected_customer_id').value = picked;
        var c = customerData[picked];
        document.getElementById('custFirst').value = c.first || '';
        document.getElementById('custLast').value = c.last || '';
        document.getElementById('custServiceAddress').value = c.address || '';
        document.getElementById('custServiceCity').value = c.city || '';
        document.getElementById('custServiceState').value = c.state || '';
        document.getElementById('custServiceZip').value = c.zip || '';
        document.getElementById('custPhone').value = c.phone || '';
        document.getElementById('custEmail').value = c.email || '';

        // Multiple known addresses (primary + distinct past-job
        // addresses, built server-side): offer a picker when there's
        // more than one. Selecting one fills the address fields;
        // "New address" clears them and opens the manual fields.
        renderAddressPick(c);
    });

    function renderAddressPick(c) {
        var wrap = document.getElementById('customerAddressPickWrap');
        var sel = document.getElementById('customerAddressPick');
        if (!wrap || !sel) return;
        // The lookup only carries an 'addresses' array once a customer has
        // job history; fall back to their primary so a single-address
        // customer still gets the visible confirmation row.
        var list = (c && c.addresses) ? c.addresses : [];
        if (!list.length && c && c.address) {
            list = [{ address: c.address, city: c.city, state: c.state, zip: c.zip }];
        }
        if (!list.length) {
            // Customer with no address on file at all: nothing to confirm,
            // open the manual fields so one can be typed in.
            wrap.style.display = 'none'; sel.innerHTML = '';
            var mf = getManualFieldsBox();
            if (mf) mf.classList.add('show');
            return;
        }
        sel.innerHTML = '';
        list.forEach(function(addr, i) {
            var opt = document.createElement('option');
            opt.value = String(i);
            opt.textContent = addr.address + (addr.city ? ', ' + addr.city : '');
            sel.appendChild(opt);
        });
        var novel = document.createElement('option');
        novel.value = '__newaddr__';
        novel.textContent = '+ New address for this job\u2026';
        sel.appendChild(novel);
        sel.dataset.customer = document.getElementById('selected_customer_id').value;
        wrap.style.display = '';
    }

    document.addEventListener('change', function(e) {
        if (e.target.id !== 'customerAddressPick') return;
        var cid = e.target.dataset.customer;
        var c = customerData[cid];
        if (!c) return;
        var manualFieldsBox = getManualFieldsBox();
        if (e.target.value === '__newaddr__') {
            ['custServiceAddress', 'custServiceCity', 'custServiceState', 'custServiceZip'].forEach(function(fieldId) {
                var f = document.getElementById(fieldId);
                if (f) f.value = '';
            });
            if (manualFieldsBox) manualFieldsBox.classList.add('show');
            var addrField = document.getElementById('custServiceAddress');
            if (addrField) addrField.focus();
            return;
        }
        var addr = (c.addresses || [])[parseInt(e.target.value, 10)];
        if (!addr) return;
        document.getElementById('custServiceAddress').value = addr.address || '';
        document.getElementById('custServiceCity').value = addr.city || '';
        document.getElementById('custServiceState').value = addr.state || '';
        document.getElementById('custServiceZip').value = addr.zip || '';
    });
})();
