<link rel="stylesheet" href="{{ map_css_url }}" />
<script src="{{ map_js_url }}"></script>
<script>
window.alsendoCheckoutRegion = {{ (region ?? '')|json_encode|raw }};
window.alsendoMapConfig = {{ map_config_json|raw }};
window.alsendoPleaseSelectPickupPointMsg = {{ (text_please_select_pickup_point ?? 'Please select the pickup point')|json_encode|raw }};
window.alsendoEuCountryCodes = ['AT','BE','BG','HR','CY','CZ','DK','EE','FI','FR','DE','GR','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','RO','SK','SI','ES','SE'];

document.addEventListener("DOMContentLoaded", function() {
    var mapConfig = window.alsendoMapConfig || {};
    var mapModal = null;
    var initialPointFromSession = {{ initial_point is not null ? initial_point|json_encode|raw : 'null' }};

    function getInitialAddressFromShippingSelect() {
        var select = document.getElementById('input-shipping-address');
        if (!select || select.tagName !== 'SELECT') return null;

        var opt = select.options[select.selectedIndex];
        if (!opt || !opt.value) return null;

        var text = (opt.textContent || opt.innerText || '').trim();
        if (!text) return null;

        var parts = text.split(',').map(function(p) { return p.trim(); }).filter(Boolean);
        if (parts.length < 5) return null;

        var street = parts[1];
        var city = parts[2];
        var country = parts[parts.length - 1];

        return street + ' ' + city + ' ' + country;
    }

    function getInitialAddressFromForm() {
        var cityInput = document.querySelector('input[name="shipping_city"],#shipping_city');
        if (!cityInput) {
            cityInput = document.querySelector('input[name="payment_city"],#payment_city');
        }
        if (!cityInput) return null;

        var postcodeInput = document.querySelector('input[name="shipping_postcode"],#shipping_postcode');
        if (!postcodeInput) {
            postcodeInput = document.querySelector('input[name="payment_postcode"],#payment_postcode');
        }
        if (!postcodeInput) return null;

        var countrySelect = document.querySelector('select[name="shipping_country_id"],#shipping_country_id,#input-shipping-country');
        if (!countrySelect) {
            countrySelect = document.querySelector('select[name="payment_country_id"],#payment_country_id,#input-payment-country');
        }
        if (!countrySelect || countrySelect.tagName !== 'SELECT') return null;

        var streetInput = document.querySelector('input[name="shipping_address_1"],#shipping_address_1');
        if (!streetInput || !(streetInput.value || '').trim()) {
            streetInput = document.querySelector('input[name="payment_address_1"],#payment_address_1');
        }

        var street = streetInput ? (streetInput.value || '').trim() : '';
        var city = (cityInput.value || '').trim();
        var postalCode = (postcodeInput.value || '').trim();

        if (!city || !postalCode) return null;

        var selectedOption = countrySelect.options[countrySelect.selectedIndex];
        var country = selectedOption ? (selectedOption.innerHTML || selectedOption.textContent || '').trim() : '';
        if (!country) return null;

        var result = [];
        if (street) result.push(street);
        result.push(city);
        result.push(postalCode);
        result.push(country);

        return result.join(' ');
    }

    function resolveOperator(alias) {
        var aliases = mapConfig.operatorAliases || {};
        if (!alias) return null;
        var key = alias.toLowerCase();
        if (aliases[key]) return aliases[key];
        return alias.toUpperCase();
    }

    window.alsendoOpenMap = function(operator, countryCodesOverride) {
        var resolvedOperator = resolveOperator(operator);
        var operators = null;
        if (resolvedOperator) {
            operators = [{ operator: resolvedOperator, checked: true }];
        } else if (mapConfig.operators) {
            operators = mapConfig.operators.map(function(op) { return { operator: op }; });
        }

        var countryCodes = countryCodesOverride;
        if (countryCodes == null || (Array.isArray(countryCodes) && countryCodes.length === 0) || (typeof countryCodes === 'string' && countryCodes === '')) {
            countryCodes = (mapConfig.countryCodes && (Array.isArray(mapConfig.countryCodes) ? mapConfig.countryCodes.length : 1)) ? mapConfig.countryCodes : (window.alsendoEuCountryCodes || []);
        }

        if (typeof countryCodes === 'string') {
            countryCodes = [countryCodes];
        }

        if (mapModal) {
            document.body.removeChild(mapModal);
            mapModal = null;
        }

        mapModal = document.createElement('div');
        mapModal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;align-items:center;justify-content:center;';
        mapModal.onclick = function(e) {
            if (e.target === mapModal) {
                document.body.removeChild(mapModal);
                mapModal = null;
            }
        };

        var modalContent = document.createElement('div');
        modalContent.style.cssText = 'width:90%;height:90%;background:#fff;border-radius:8px;overflow:hidden;position:relative;';

        var closeButton = document.createElement('button');
        closeButton.innerHTML = '&times;';
        closeButton.type = 'button';
        closeButton.style.cssText = 'position:absolute;top:10px;right:10px;z-index:10000;background:#fff;border:1px solid #ccc;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:18px;line-height:1;';
        closeButton.onclick = function() {
            document.body.removeChild(mapModal);
            mapModal = null;
        };

        var mapContainer = document.createElement('div');
        mapContainer.id = 'alsendo-checkout-map-' + Date.now();
        mapContainer.style.cssText = 'width:100%;height:100%;';

        modalContent.appendChild(closeButton);
        modalContent.appendChild(mapContainer);
        mapModal.appendChild(modalContent);
        document.body.appendChild(mapModal);

        var widgetOptions = {
            operators: operators,
            posType: 'DELIVERY',
            language: mapConfig.language,
            countryCodes: countryCodes,
            codeSearch: mapConfig.codeSearch !== false,
            testMode: mapConfig.testMode || false,
            callback: function(point) {
                var pointData = {
                    code: point.code || '',
                    operator: point.operator || '',
                    name: point.description || point.street || '',
                    street: point.street || '',
                    postalCode: point.postalCode || '',
                    city: point.city || '',
                    province: point.province || '',
                    latitude: point.latitude || null,
                    longitude: point.longitude || null,
                    hasCod: !!point.cod,
                    raw: point
                };

                var hiddenInput = document.getElementById('shipping_point');
                var displayInput = document.getElementById('shipping_point_display');
                if (hiddenInput) hiddenInput.value = JSON.stringify(pointData);
                if (displayInput) {
                    displayInput.value = pointData.code + ' - ' + (pointData.name || pointData.street || '');
                    displayInput.style.display = 'block';
                }

                document.body.removeChild(mapModal);
                mapModal = null;

                var mapDiv = document.getElementById("checkout-shipping-map");
                if (mapDiv) {
                    var existingError = mapDiv.querySelector(".pickup-point-error");
                    if (existingError) existingError.remove();
                }

                if (typeof window.alsendoUpdateConfirmButtonState === 'function') {
                    window.alsendoUpdateConfirmButtonState();
                }

                var lang = typeof window.alsendoGetLanguageCode === 'function' ? window.alsendoGetLanguageCode() : 'en-gb';
                fetch("index.php?route=extension/alsendo/api/shipping_info.storeSelectedPickupPoint&language=" + lang, {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: "pickup_point=" + JSON.stringify(pointData)
                }).then(function(r) { return r.json(); }).catch(function(err) { console.error(err); });
            }
        };

        if (mapConfig.operatorMarkers) {
            widgetOptions.operatorMarkers = true;
        }

        if (mapConfig.mapOptions && typeof mapConfig.mapOptions === 'object') {
            widgetOptions.mapOptions = mapConfig.mapOptions;
        }

        function getFallbackInitialAddress() {
            var fallbackAddress = getInitialAddressFromForm();
            if (!fallbackAddress) {
                fallbackAddress = getInitialAddressFromShippingSelect();
            }
            if (!fallbackAddress && initialPointFromSession !== null) {
                fallbackAddress = initialPointFromSession;
            }

            return fallbackAddress;
        }

        function applyInitialAddress(initialAddress) {
            if (initialAddress) {
                widgetOptions.initialAddress = initialAddress;
                if (!widgetOptions.mapOptions) widgetOptions.mapOptions = {};
                widgetOptions.mapOptions.zoom = 15;
            }

            if (
                window?.alsendoCheckoutRegion === 'poland' &&
                typeof initialAddress === 'string' &&
                !initialAddress.toLowerCase().includes('poland')
            ) {
                widgetOptions?.operators?.forEach(op => {
                    if (op?.operator === 'DHL') {
                        op.operator = 'DHL_PARCEL';
                    }
                });
            }
        }

        function initMapWidget() {
            setTimeout(function() {
                if (typeof BPWidget !== 'undefined') {
                    BPWidget.init(mapContainer, widgetOptions);
                }
            }, 100);
        }

        var language = typeof window.alsendoGetLanguageCode === 'function' ? window.alsendoGetLanguageCode() : 'en-gb';
        fetch("index.php?route=extension/alsendo/event/checkout.getSessionData&language=" + language, {
            method: "GET"
        })
            .then(function(response) { return response.json(); })
            .then(function(sessionData) {
                var postCode = sessionData && typeof sessionData.post_code === 'string' ? sessionData.post_code.trim() : '';
                var country = sessionData && typeof sessionData.country === 'string' ? sessionData.country.trim() : '';
                var initialAddress = (postCode && country) ? (postCode + ' ' + country) : getFallbackInitialAddress();

                applyInitialAddress(initialAddress);
                initMapWidget();
            })
            .catch(function() {
                var initialAddress = getFallbackInitialAddress();
                applyInitialAddress(initialAddress);
                initMapWidget();
            });
    };

    var shippingContainer = document.querySelector("#checkout-shipping-method");

    if (shippingContainer) {

        function checkShippingMethodMap(shippingMethod) {
            if (!shippingMethod || !shippingMethod.startsWith("alsendo.")) {
                hideMap();
                return;
            }

            fetch("index.php?route=extension/alsendo/api/shipping_info.checkHasMap&language=" + getLanguageCode(), {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: "shipping_method=" + encodeURIComponent(shippingMethod)
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    hideMap();
                    clearPickupPointData();
                    if (data.has_map) {
                        showMap(data.operator);
                    }
                } else {
                    hideMap();
                }
            })
            .catch(function(error) {
                hideMap();
            });
        }

        function showMap(operator) {
            var existingMapElement = document.getElementById("checkout-shipping-map");

            if (!existingMapElement) {
                var mapMessageElement = document.createElement("div");
                mapMessageElement.id = "checkout-shipping-map";
                mapMessageElement.className = "mb-3";
                mapMessageElement.innerHTML =
                    '<input type="text" id="shipping_point_display" class="form-control mb-2" readonly style="display: none;">' +
                    '<input type="hidden" id="shipping_point">' +
                    '<button class="btn btn-primary" type="button">' +
                    '<i class="fas fa-map-marker-alt"></i> {{ text_select_pickup_point|e('js') }}' +
                    '</button>';

                var button = mapMessageElement.querySelector("button");
                button.addEventListener("click", function() {
                    var lang = typeof getLanguageCode === 'function' ? getLanguageCode() : 'en-gb';
                    fetch("index.php?route=extension/alsendo/api/shipping_info.getShippingCountryCode&language=" + lang)
                        .then(function(r) { return r.json(); })
                        .then(function(data) {
                            var iso = data && data.iso_code_2;
                            var countryCodes = (iso != null && iso !== '') ? [String(iso).toUpperCase()] : (window.alsendoEuCountryCodes || []);

                            if (typeof window.alsendoOpenMap === 'function') {
                                window.alsendoOpenMap(operator, countryCodes);
                            }
                        })
                        .catch(function() {
                            if (typeof window.alsendoOpenMap === 'function') {
                                window.alsendoOpenMap(operator, window.alsendoEuCountryCodes || []);
                            }
                        });
                });

                var shippingMethodContainer = document.querySelector("#checkout-shipping-method");
                if (shippingMethodContainer) {
                    shippingMethodContainer.insertAdjacentElement('afterend', mapMessageElement);
                }
            } else {
                var btn = existingMapElement.querySelector("button");
                btn.onclick = function() {
                    var lang = typeof getLanguageCode === 'function' ? getLanguageCode() : 'en-gb';
                    fetch("index.php?route=extension/alsendo/api/shipping_info.getShippingCountryCode&language=" + lang)
                        .then(function(r) { return r.json(); })
                        .then(function(data) {
                            var iso = data && data.iso_code_2;
                            var countryCodes = (iso != null && iso !== '') ? [String(iso).toUpperCase()] : (window.alsendoEuCountryCodes || []);
                            if (typeof window.alsendoOpenMap === 'function') {
                                window.alsendoOpenMap(operator, countryCodes);
                            }
                        })
                        .catch(function() {
                            if (typeof window.alsendoOpenMap === 'function') {
                                window.alsendoOpenMap(operator, window.alsendoEuCountryCodes || []);
                            }
                        });
                };
            }
        }

        function hideMap() {
            var existingMessage = document.getElementById("checkout-shipping-map");
            if (existingMessage) {
                existingMessage.remove();
            }
            updateConfirmButtonState();
        }

        function getLanguageCode() {
            var urlParams = new URLSearchParams(window.location.search);
            return urlParams.get("language") || "en-gb";
        }

        function clearPickupPointData() {
            fetch("index.php?route=extension/alsendo/api/shipping_info.storeSelectedPickupPoint&language=" + getLanguageCode(), {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" }
            })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    var displayInput = document.getElementById('shipping_point_display');
                    if (!displayInput) return;
                    if (displayInput.style.display === 'none') return;

                    displayInput.removeAttribute('value');
                    displayInput.style.display = 'none';

                    var hiddenInput = document.getElementById('shipping_point');
                    if (hiddenInput) hiddenInput.value = '';
                    updateConfirmButtonState();
                })
                .catch(function(err) { console.error(err); });
        }

        function getCurrentShippingMethod() {
            var radio = document.querySelector("input[name=shipping_method]:checked");
            if (radio && radio.value) return radio.value;
            var codeInput = document.getElementById("input-shipping-code");
            if (codeInput && codeInput.value) return codeInput.value;
            return null;
        }

        document.addEventListener("change", function(e) {
            if (e.target && e.target.name === "shipping_method") {
                checkShippingMethodMap(e.target.value);
            }
            if (e.target && e.target.id === "input-shipping-code") {
                checkShippingMethodMap(e.target.value);
            }
            if (e.target && e.target.tagName === "SELECT" && (e.target.id === "input-payment-address" || e.target.id === "input-shipping-address")) {
                hideMap();
            }
        });

        document.addEventListener('click', function (e) {
            var btn = e.target.closest('button');
            if (!btn) return;

            if (btn.id === 'button-register') {
                hideMap();
                return;
            }

            if (btn.id !== 'button-shipping-method') {
                return;
            }

            setTimeout(function () {
                var method = getCurrentShippingMethod();
                if (method) {
                    checkShippingMethodMap(method);
                }
            }, 300);
        });

        var currentMethod = getCurrentShippingMethod();
        if (currentMethod) {
            checkShippingMethodMap(currentMethod);
        }
        setTimeout(function() {
            var delayedMethod = getCurrentShippingMethod();
            if (delayedMethod && !document.getElementById("checkout-shipping-map")) {
                checkShippingMethodMap(delayedMethod);
            }
        }, 800);

        function updateConfirmButtonState() {
            var paymentDiv = document.getElementById("checkout-payment");
            if (!paymentDiv) return;

            var confirmButton = paymentDiv.querySelector("button");
            if (!confirmButton) return;

            var shippingPointInput = document.getElementById("shipping_point");
            if (shippingPointInput) {
                ensurePickupPointMessageElement();
                var hasValue = shippingPointInput.value && shippingPointInput.value.trim() !== '';
                confirmButton.disabled = !hasValue;
                var msgSpan = paymentDiv.querySelector(".alsendo-pickup-required-msg");
                if (msgSpan) {
                    msgSpan.style.display = hasValue ? "none" : "inline";
                }
            } else {
                confirmButton.disabled = false;
                var msgSpan = paymentDiv.querySelector(".alsendo-pickup-required-msg");
                if (msgSpan) msgSpan.style.display = "none";
            }
        }

        function handleConfirmButtonClick(e) {
            var shippingPointInput = document.getElementById("shipping_point");
            if (shippingPointInput) {
                var hasValue = shippingPointInput.value && shippingPointInput.value.trim() !== '';
                if (!hasValue) {
                    e.preventDefault();
                    e.stopPropagation();

                    var mapDiv = document.getElementById("checkout-shipping-map");
                    if (mapDiv) {
                        var existingError = mapDiv.querySelector(".pickup-point-error");
                        if (!existingError) {
                            var errorText = document.createElement("div");
                            errorText.className = "pickup-point-error";
                            errorText.style.color = "red";
                            errorText.style.marginTop = "10px";
                            errorText.textContent = "Please select shipping pickup point";
                            mapDiv.appendChild(errorText);
                        }
                    }
                    return false;
                }
            }
        }

        function ensurePickupPointMessageElement() {
            var paymentDiv = document.getElementById("checkout-payment");
            if (!paymentDiv) return;
            var confirmButton = paymentDiv.querySelector("button");
            if (!confirmButton) return;
            var shippingPointInput = document.getElementById("shipping_point");
            if (!shippingPointInput) return;

            var btnWrapper = confirmButton.closest(".text-end") || confirmButton.parentElement;
            if (!btnWrapper || btnWrapper.hasAttribute("data-alsendo-msg-added")) return;

            btnWrapper.setAttribute("data-alsendo-msg-added", "true");
            btnWrapper.classList.remove("text-end");
            btnWrapper.classList.add("d-flex", "justify-content-end", "align-items-center", "gap-2");

            var msgSpan = document.createElement("span");
            msgSpan.className = "alsendo-pickup-required-msg";
            msgSpan.style.cssText = "display:none; color:#dc3545;";
            msgSpan.textContent = window.alsendoPleaseSelectPickupPointMsg || "Please select the pickup point";
            btnWrapper.insertBefore(msgSpan, confirmButton);
        }

        function initConfirmButtonValidation() {
            var paymentDiv = document.getElementById("checkout-payment");
            if (paymentDiv) {
                var confirmButton = paymentDiv.querySelector("button");
                if (confirmButton && !confirmButton.hasAttribute("data-alsendo-listener")) {
                    confirmButton.setAttribute("data-alsendo-listener", "true");
                    confirmButton.addEventListener("click", handleConfirmButtonClick);
                }
                if (document.getElementById("shipping_point")) {
                    ensurePickupPointMessageElement();
                }
            }
        }

        setInterval(function() {
            initConfirmButtonValidation();
            updateConfirmButtonState();
        }, 500);

        initConfirmButtonValidation();
        updateConfirmButtonState();

        window.alsendoUpdateConfirmButtonState = updateConfirmButtonState;
        window.alsendoGetLanguageCode = getLanguageCode;
    }
});
</script>
