(function() {
    var mapModal = null;

    function resolveOperator(alias) {
        var config = window.alsendoMapConfig || {};
        var aliases = config.operatorAliases || {};
        if (!alias) return null;
        var key = alias.toLowerCase();
        if (aliases[key]) return aliases[key];
        var upper = alias.toUpperCase();
        var operators = config.operators || [];
        for (var i = 0; i < operators.length; i++) {
            if (operators[i] === upper) return upper;
        }
        return upper;
    }

    window.openPointMapWithStreet = function(pickupInputGroup, operatorNames, posType, region) {
        var cityEl = document.getElementById('city');
        var postalEl = document.getElementById('postal_code');
        var city = (cityEl && cityEl.value) ? String(cityEl.value).trim() : '';
        var postalCode = (postalEl && postalEl.value) ? String(postalEl.value).trim() : '';
        var parts = [postalCode].filter(function(p) { return p !== ''; });
        var address = parts.length ? parts.join(' ') + ' ' + region : region;

        window.openPointMap(pickupInputGroup, operatorNames, posType, address);
    };

    window.openPointMap = function(pickupInputGroup, operatorNames, posType, region) {
        var config = window.alsendoMapConfig || {};
        posType = posType || 'DELIVERY';

        var operators = null;
        if (operatorNames && Array.isArray(operatorNames) && operatorNames.length) {
            operators = operatorNames
                .map(function(op) { return resolveOperator(op); })
                .filter(Boolean)
                .map(function(op) { return { operator: op, checked: operatorNames.length === 1 }; });
            if (!operators.length) operators = null;
        }

        if (!operators && config.operators) {
            operators = config.operators.map(function(op) { return { operator: op }; });
        }

        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-map-' + Date.now();
        mapContainer.style.cssText = 'width:100%;height:100%;';

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

        if (operators) {
            operators.forEach(operator => {
                if (operator.operator === 'CARGUS') {
                    posType = null;
                }
            });
        }

        var hasLocationDetail = region && String(region).trim().split(/\s+/).length > 1;
        var zoomLevel = hasLocationDetail ? 14 : 7;
        var widgetOptions = {
            operators: operators,
            posType: posType,
            language: config.language,
            countryCodes: config.countryCodes,
            codeSearch: config.codeSearch !== false,
            testMode: config.testMode || false,
            initialAddress: region,
            mapOptions: {
                zoom: zoomLevel
            },
            callback: function(point) {
                var normalized = {
                    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 selector = '[data-map-selector="' + pickupInputGroup + '"]';
                document.querySelectorAll(selector).forEach(function(input) {
                    if (input.type === 'hidden') {
                        input.value = JSON.stringify(normalized);
                    } else if (input.type === 'text' || input.getAttribute('readonly') !== null) {
                        input.value = normalized.code + ' - ' + (normalized.name || normalized.street || '');
                    }
                });

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

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

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