function updateShipmentContainersVisibility() {
    const $initial = $('#initial-service-id');
    const $shipment = $('#shipment-selected-service');
    if ($shipment.length) {
        $shipment.val($initial.val() || '').addClass('form-control');
    }

    const $courier = $('#courier-services-container');
    const $pickupDate = $('#shipment-preferred-pickup-date-container');
    const $pickupPoint = $('#shipment-pickup-point-container');
    const selectedPickupType = $('#selected_pickup_type').val();

    if ($courier.length && $pickupDate.length && $pickupPoint.length) {
        $courier.hide();
        $pickupDate.hide();
        $pickupPoint.hide();

        if (selectedPickupType === 'SELF') $pickupPoint.show();
        else if (selectedPickupType === 'COURIER') $pickupDate.show();
    }
}

function selectCourierService(button) {
    const deliveryToPoint = button.getAttribute('data-is-delivery-to-point') === 'true';
    const mapOperator = button.getAttribute('data-map-operator');

    if (deliveryToPoint && mapOperator) {
        const shippingPickupSelectButton = document.getElementById('shipping-pickup-point-select-btn');
        if (shippingPickupSelectButton) {
            shippingPickupSelectButton.style.display = 'inline-block';
            shippingPickupSelectButton.style.cursor = 'pointer';
            shippingPickupSelectButton.setAttribute('data-map-operator', mapOperator);
        }
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('get-quote-button');
    const container = document.getElementById('courier-services-container');
    const containerInner = document.getElementById('courier-services-container-inner');

    const userTokenEl = document.getElementById('user-token');
    const orderIdEl = document.getElementById('order-id');
    if (!userTokenEl || !orderIdEl) return;

    const userToken = userTokenEl.value;
    const orderId = orderIdEl.value;

    btn.addEventListener('click', function () {
        const alsendoOrderForm = $('#alsendo-order-form');

        const isOutside = btn.dataset.quoteOutsideForm === 'true';
        const data = isOutside ? { order_id: orderId, by_order_id: true } : alsendoOrderForm.serialize();
        const url = 'index.php?route=extension/alsendo/alsendo_order.getQuote&user_token=' + userToken;

        container.style.display = 'none';
        btn.disabled = true;

        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (json) {
                const formOrSection = document.getElementById('alsendo-order-form') || document.getElementById('alsendo-order-section');
                if (json && typeof json === 'object' && !Array.isArray(json) && json.success === false && json.errors && typeof json.errors === 'object' && Object.keys(json.errors).length > 0) {
                    if (formOrSection) {
                        formOrSection.querySelectorAll('.input-validation-error').forEach(function(input) { input.classList.remove('input-validation-error'); });
                        formOrSection.querySelectorAll('small.validation-error-message').forEach(function(el) { el.remove(); });
                        for (var field in json.errors) {
                            if (!json.errors.hasOwnProperty(field)) continue;
                            var message = json.errors[field];
                            var msgText = Array.isArray(message) ? (message[0] || '') : message;
                            var input = formOrSection.querySelector('[name="' + field + '"]') || formOrSection.querySelector('[id="' + field.replace(/_/g, '-') + '"]');
                            if (input) {
                                input.classList.add('input-validation-error');
                                var errorEl = document.createElement('small');
                                errorEl.className = 'validation-error-message text-danger d-block';
                                errorEl.textContent = msgText;
                                input.insertAdjacentElement('afterend', errorEl);
                            }
                        }
                    }
                    showInfoModal(json.error || '');
                    btn.disabled = false;
                    return;
                }
                if (json && typeof json === 'object' && !Array.isArray(json) && json.error) {
                    showInfoModal(json.error);
                    btn.disabled = false;
                    return;
                }

                setTimeout(() => { btn.disabled = false; }, 500);

                var items = (json && typeof json === 'object' && Array.isArray(json.data)) ? json.data : (Array.isArray(json) ? json : (json && typeof json === 'object' ? [json] : []));
                items = items.filter(function(item) { return !item.no_price; });
                if (items.length === 0) {
                    var noQuoteMessage = (typeof ALSENDO_TEXT_NO_QUOTE_AVAILABLE !== 'undefined' && ALSENDO_TEXT_NO_QUOTE_AVAILABLE)
                        ? ALSENDO_TEXT_NO_QUOTE_AVAILABLE
                        : 'No quote available for the provided order parameters.';
                    showInfoModal(noQuoteMessage);
                    return;
                }

                containerInner.innerHTML = '';
                container.style.display = 'block';

                items.forEach(function(item, index) {
                    const isFirst = index === 0;
                    const div = document.createElement('div');
                    div.setAttribute('role', 'button');
                    div.classList.add('courier-service');
                    div.classList.add('combobox-btn');
                    div.dataset.group = 'shipment-selected-service';
                    div.dataset.isDeliveryToPoint = item.is_delivery_to_point;
                    div.dataset.mapOperator = item.map_operator;
                    div.dataset.value = item.service_id;
                    div.onclick = function() {
                        const hiddenInput = document.getElementById('shipment-selected-service');
                        if (hiddenInput) {
                            hiddenInput.value = item.service_id;
                        }

                        containerInner.querySelectorAll('.courier-service').forEach(el => {
                            el.classList.remove('active');
                            el.style.border = '';
                        });
                        div.classList.add('active');
                        if (div.dataset.isDefault === 'true') {
                            div.style.border = '2px solid #28a745';
                        }

                        selectCourierService(this);
                    };

                    const logo = document.createElement('div');
                    logo.style.height = '6em';
                    logo.style.overflow = 'hidden';
                    logo.style.padding = '1em';
                    const img = document.createElement('img');
                    img.src = item.logo_url || '';
                    img.style.width = '50%';
                    img.style.height = 'auto';
                    img.alt = 'Courier logo';
                    img.onerror = function() {
                        logo.style.display = 'none';
                        name.style.paddingTop = '77px';
                    };
                    logo.appendChild(img);

                    const name = document.createElement('div');
                    name.style.overflow = 'hidden';
                    name.style.whiteSpace = 'wrap';
                    name.style.textOverflow = 'ellipsis';
                    name.style.fontSize = '1em';
                    name.style.padding = '0 1em';
                    name.textContent = item.service_name;

                    const net = document.createElement('div');
                    net.style.height = '1.5em';
                    net.style.overflow = 'hidden';
                    net.style.fontSize = '1em';
                    net.style.padding = '0 1em';
                    net.style.fontWeight = 'bold';

                    const gross = document.createElement('div');
                    gross.style.height = '1.5em';
                    gross.style.overflow = 'hidden';
                    gross.style.fontSize = '1em';
                    gross.style.padding = '0 1em';
                    gross.style.marginBottom = '1em';

                    if (item.no_price) {
                        var priceNa = (typeof ALSENDO_TEXT_PRICE_NA !== 'undefined' ? ALSENDO_TEXT_PRICE_NA : 'price N/A');
                        net.innerHTML = '<small style="color:#999">' + priceNa + '</small>';
                        gross.textContent = '';
                    } else {
                        net.textContent = item.price_net_display;
                        gross.textContent = item.price_gross_display;
                    }

                    div.appendChild(logo);
                    div.appendChild(name);
                    div.appendChild(net);
                    div.appendChild(gross);

                    if (isFirst) {
                        div.dataset.isDefault = 'true';
                        div.style.border = '2px solid #28a745';
                        div.style.position = 'relative';
                        var badge = document.createElement('span');
                        badge.textContent = 'default';
                        badge.style.cssText = 'position:absolute;top:4px;right:4px;font-size:9px;background:#28a745;color:#fff;padding:1px 6px;border-radius:3px;text-transform:uppercase;';
                        div.appendChild(badge);
                    }

                    containerInner.appendChild(div);
                });

                var firstBtn = containerInner.querySelector('.courier-service');
                if (firstBtn) {
                    firstBtn.click();
                }
            },
            error: function (xhr, status, error) {
                console.log(error);
                setTimeout(() => { btn.disabled = false; }, 500);
            }
        });
    });

});
