var initRtlMapbox = null;
var markerMapBoxGolbal = [];
var mapMapboxGobal;
var ii = 0;
var mapImg;

function stResolveHalfMapContainerId(mapEl) {
    if (mapEl && mapEl.length && mapEl.attr('id')) {
        return mapEl.attr('id');
    }
    if (mapEl && mapEl.length) {
        var innerMap = mapEl.find('#st-map, [id^="st-map-"], .st-map-canvas').first();
        if (innerMap.length && innerMap.attr('id')) {
            return innerMap.attr('id');
        }
    }
    if (document.getElementById('st-map')) {
        return 'st-map';
    }
    if (document.getElementById('map-search-form')) {
        return 'map-search-form';
    }
    if (document.getElementById('map-search-form-mb')) {
        return 'map-search-form-mb';
    }
    return null;
}

function stTravelerUseNeshanHalfMap() {
    if (typeof stShouldUseNeshanMap === 'function') {
        return stShouldUseNeshanMap();
    }
    return typeof stIsNeshanMap === 'function' && stIsNeshanMap();
}

function stClearHalfMapMarkers() {
    if (!markerMapBoxGolbal || !markerMapBoxGolbal.length) {
        markerMapBoxGolbal = [];
        return;
    }
    markerMapBoxGolbal.forEach(function (marker) {
        if (marker && marker.remove) {
            marker.remove();
        }
    });
    markerMapBoxGolbal = [];
}

function stGetHalfMapInstance(mapEl, containerId) {
    if (!mapEl || !mapEl.length || !containerId) {
        return null;
    }

    var stored = mapEl.data('st-halfmap-instance');
    if (stored && stored.getContainer) {
        try {
            if (stored.getContainer().id === containerId) {
                return stored;
            }
        } catch (e) {}
    }

    if (mapMapboxGobal && mapMapboxGobal.getContainer) {
        try {
            if (mapMapboxGobal.getContainer().id === containerId) {
                return mapMapboxGobal;
            }
        } catch (e) {}
    }

    return null;
}

function initHalfMapBox(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove) {
    if (stTravelerUseNeshanHalfMap()) {
        return initHalfMapBoxNeshan(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove);
    }
    initHalfMapBoxCore(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove);
}

function initHalfMapBoxNeshan(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove) {
    var mapKey = stGetNeshanMapKey();
    if (!mapKey) {
        console.warn('[Traveler] Neshan API key is empty. Set it in Theme Options > Map API.');
        return;
    }
    if (window.nmp_mapboxgl && window.nmp_mapboxgl.Map) {
        initHalfMapBoxCore(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove);
        return;
    }
    stLoadNeshanSdk().then(function () {
        if (!window.nmp_mapboxgl || !window.nmp_mapboxgl.Map) {
            console.warn('[Traveler] Neshan SDK is not available.');
            return;
        }
        initHalfMapBoxCore(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove);
    });
}

function initHalfMapBoxCore(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove) {
    var popupPos = mapEl.data('popup-position');
    if (!mapData || (typeof mapData.length !== 'undefined' && mapData.length <= 0)) {
        mapData = mapEl.data('data_show');
    }
    if (!mapLat || (typeof mapLat === 'string' && mapLat.length <= 0)) {
        mapLat = mapEl.data('lat');
    }
    if (!mapLng || (typeof mapLng === 'string' && mapLng.length <= 0)) {
        mapLng = mapEl.data('lng');
    }
    if (!mapZoom || (typeof mapZoom === 'string' && mapZoom.length <= 0)) {
        mapZoom = mapEl.data('zoom');
    }
    if (!mapIcon || (typeof mapIcon === 'string' && mapIcon.length <= 0)) {
        mapIcon = mapEl.data('icon');
    }

    mapLat = parseFloat(mapLat);
    mapLng = parseFloat(mapLng);
    mapZoom = parseFloat(mapZoom);
    if (isNaN(mapLat) || isNaN(mapLng) || (mapLat === 0 && mapLng === 0)) {
        mapLat = 35.6892;
        mapLng = 51.3890;
    }
    if (isNaN(mapZoom)) {
        mapZoom = 13;
    }

    var isNeshan = stTravelerUseNeshanHalfMap();
    var mapboxLib = isNeshan ? window.nmp_mapboxgl : window.mapboxgl;

    if (isNeshan && (!mapboxLib || !mapboxLib.Map) && window.nmp_mapboxgl && window.nmp_mapboxgl.Map) {
        mapboxLib = window.nmp_mapboxgl;
    }

    if (!mapboxLib || !mapboxLib.Map) {
        console.warn('[Traveler] Map library is not loaded.');
        return;
    }

    if (isNeshan) {
        if (!stGetNeshanMapKey()) {
            console.warn('[Traveler] Neshan API key is empty. Set it in Theme Options > Map API.');
            return;
        }
    } else {
        var mapCfg = typeof stGetMapConfig === 'function' ? stGetMapConfig() : (typeof st_params !== 'undefined' ? st_params : {});
        if (!mapCfg.token_mapbox) {
            console.warn('[Traveler] Mapbox token is empty. Set it in Theme Options > Map API.');
            return;
        }
        if (mapboxLib && typeof mapboxLib.accessToken !== 'undefined') {
            mapboxLib.accessToken = mapCfg.token_mapbox;
        }
    }

    var icon_map = mapIcon;
    if (!icon_map) {
        var icon_mapbox = (typeof stGetMapConfig === 'function' ? stGetMapConfig() : (typeof st_params !== 'undefined' ? st_params : {})).st_icon_mapbox;
        icon_map = icon_mapbox || 'https://i.imgur.com/MK4NUzI.png';
    }

    if (typeof isMapMove === 'undefined') {
        isMapMove = false;
    }

    if (!isNeshan && typeof st_params.text_rtl_mapbox !== 'undefined' && initRtlMapbox == null && typeof mapboxLib.setRTLTextPlugin === 'function') {
        mapboxLib.setRTLTextPlugin(st_params.text_rtl_mapbox);
        initRtlMapbox = 1;
    }

    function stBuildHalfMapOptions(containerId) {
        if (isNeshan && typeof stBuildNeshanMapOptions === 'function') {
            return stBuildNeshanMapOptions({
                container: containerId,
                lat: mapLat,
                lng: mapLng,
                zoom: mapZoom
            });
        }
        return {
            container: containerId,
            style: 'mapbox://styles/mapbox/light-v10?optimize=true',
            center: [mapLng, mapLat],
            zoom: mapZoom
        };
    }

    var containerId = stResolveHalfMapContainerId(mapEl);
    if (!containerId) {
        console.warn('[Traveler] Map container element was not found.');
        return;
    }

    var existingMap = stGetHalfMapInstance(mapEl, containerId);

    if (!isMapMove) {
        if (existingMap) {
            mapMapboxGobal = existingMap;
        } else {
            var primaryOptions = stBuildHalfMapOptions(containerId);
            if (!primaryOptions) {
                return;
            }
            mapMapboxGobal = new mapboxLib.Map(primaryOptions);
            mapEl.data('st-halfmap-instance', mapMapboxGobal);
            if (typeof stApplyMapInteractionOptions === 'function') {
                stApplyMapInteractionOptions(mapMapboxGobal);
            }
            mapMapboxGobal.on('load', function () {
                if (mapMapboxGobal.resize) {
                    mapMapboxGobal.resize();
                }
            });
            if (typeof stAttachMapResizeObserver === 'function') {
                var containerEl = document.getElementById(containerId);
                if (containerEl) {
                    stAttachMapResizeObserver(mapMapboxGobal, containerEl);
                }
            }
        }

        var mobileEl = jQuery('#map-search-form-mb');
        if (mobileEl.length && containerId !== 'map-search-form-mb') {
            var mobileMap = stGetHalfMapInstance(mobileEl, 'map-search-form-mb');
            if (!mobileMap) {
                var mobileOptions = stBuildHalfMapOptions('map-search-form-mb');
                if (mobileOptions) {
                    mobileMap = new mapboxLib.Map(mobileOptions);
                    mobileEl.data('st-halfmap-instance', mobileMap);
                    if (typeof stApplyMapInteractionOptions === 'function') {
                        stApplyMapInteractionOptions(mobileMap);
                    }
                }
            }
        }
    } else if (existingMap) {
        mapMapboxGobal = existingMap;
    }

    if (!mapMapboxGobal) {
        return;
    }

    if (isMapMove && mapMapboxGobal.getLayer && mapMapboxGobal.getLayer('markers_' + ii)) {
        mapMapboxGobal.removeLayer('markers_' + ii);
        ii++;
    }

    if (!mapEl.data('st-halfmap-nav-added') && !isNeshan && mapMapboxGobal.addControl && mapboxLib.NavigationControl) {
        mapMapboxGobal.addControl(new mapboxLib.NavigationControl({ showCompass: false }), 'bottom-right');
        mapEl.data('st-halfmap-nav-added', true);
    }
    if (typeof stApplyMapInteractionOptions === 'function') {
        stApplyMapInteractionOptions(mapMapboxGobal);
    } else if (mapMapboxGobal.scrollZoom && mapMapboxGobal.scrollZoom.enable) {
        mapMapboxGobal.scrollZoom.enable();
        if (mapMapboxGobal.scrollZoom.setWheelZoomRate) {
            mapMapboxGobal.scrollZoom.setWheelZoomRate(0.012);
        }
        if (mapMapboxGobal.dragRotate && mapMapboxGobal.dragRotate.disable) {
            mapMapboxGobal.dragRotate.disable();
        }
        if (mapMapboxGobal.touchZoomRotate && mapMapboxGobal.touchZoomRotate.disableRotation) {
            mapMapboxGobal.touchZoomRotate.disableRotation();
        }
    }

    function stPlaceHalfMapMarkers() {
        stClearHalfMapMarkers();

        var bounds = new mapboxLib.LngLatBounds();
        var hasBounds = false;

        jQuery.map(mapData || {}, function (location, i) {
            var item_map = InitItemmap(location, i);
            if (!location || location.lat === undefined || location.lng === undefined) {
                return;
            }

            var el = typeof stCreateMapMarkerElement === 'function'
                ? stCreateMapMarkerElement(location, mapEl, mapVersion, icon_map)
                : (function () {
                    var fallback = document.createElement('div');
                    fallback.innerHTML = '<div class="inner" data-marker-id="' + location.id + '">' + jQuery(location.content_adv_html).find('.item_price_map span').text() + '</div>';
                    fallback.className = 'stt-price-label';
                    return fallback;
                })();

            var popup = new mapboxLib.Popup({ offset: [0, -30], maxWidth: '320px', closeOnClick: true, anchor: 'bottom' })
                .setHTML(item_map.properties.description);

            markerMapBoxGolbal[i] = new mapboxLib.Marker({ element: el, anchor: 'bottom' })
                .setLngLat(item_map.geometry.coordinates)
                .setPopup(popup)
                .addTo(mapMapboxGobal);
            bounds.extend(item_map.geometry.coordinates);
            hasBounds = true;
        });

        if (mapMapboxGobal.resize) {
            mapMapboxGobal.resize();
        }
        if (hasBounds && !bounds.isEmpty() && mapMapboxGobal.fitBounds) {
            mapMapboxGobal.fitBounds(bounds, {
                padding: { top: 48, bottom: 48, left: 48, right: 48 },
                maxZoom: 15,
                duration: 0
            });
        }
    }

    function stFinalizeHalfMapLayout() {
        if (!mapMapboxGobal) {
            return;
        }
        stPlaceHalfMapMarkers();
    }

    if (mapMapboxGobal.loaded && mapMapboxGobal.loaded()) {
        stFinalizeHalfMapLayout();
    } else {
        mapMapboxGobal.once('load', stFinalizeHalfMapLayout);
    }

    if (typeof stRunAfterMapContainerLayout === 'function') {
        var halfMapContainer = document.getElementById(containerId);
        if (halfMapContainer) {
            stRunAfterMapContainerLayout(halfMapContainer, stFinalizeHalfMapLayout);
        }
    }

    if (mapVersion === 'elementorv2') {
        var toggleMap = jQuery('#st-toggle-map');
        toggleMap.on('click', function () {
            if (jQuery(this).hasClass('open')) {
                mapMapboxGobal.resize();
                mapMapboxGobal.fitBounds(bounds);
            } else {
                mapMapboxGobal.on('idle', function () {
                    mapMapboxGobal.resize();
                });
                mapMapboxGobal.fitBounds(bounds);
            }
        });

        mapMapboxGobal.on('dragend', function () {
            var moveLat = mapMapboxGobal.getCenter().lat;
            var moveLng = mapMapboxGobal.getCenter().lng;
            if (jQuery('#st-move-map').length && jQuery('#st-move-map').is(':checked')) {
                var distance = getMapDistanceMapbox(mapMapboxGobal);
                jQuery('#st-map-coordinate').val(moveLat + '_' + moveLng + '_' + distance).trigger('change');
            }
        });

        mapMapboxGobal.on('zoomend', function () {
            var moveLat = mapMapboxGobal.getCenter().lat;
            var moveLng = mapMapboxGobal.getCenter().lng;
            if (jQuery('#st-move-map').length && jQuery('#st-move-map').is(':checked')) {
                var distance = getMapDistanceMapbox(mapMapboxGobal);
                jQuery('#st-map-coordinate').val(moveLat + '_' + moveLng + '_' + distance).trigger('change');
            }
        });
    }
}

function getMapDistanceMapbox(map) {
    var bounds = map.getBounds();
    var center = bounds.getCenter();
    var ne = bounds.getNorthEast();
    var r = 3963.0;
    var lat1 = center.lat / 57.2958;
    var lon1 = center.lng / 57.2958;
    var lat2 = ne.lat / 57.2958;
    var lon2 = ne.lng / 57.2958;
    var dis = r * Math.acos(Math.sin(lat1) * Math.sin(lat2) +
        Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1));
    return dis;
}

function InitItemmap(item_map, key) {
    var singleObj = {};
    singleObj.type = 'Feature';
    singleObj.geometry = {
        type: 'Point',
        coordinates: [item_map.lng, item_map.lat]
    };
    singleObj.properties = {
        title: item_map.name,
        description: item_map.content_html
    };
    return singleObj;
}

function stIsDesktopHalfMapSearch() {
    return jQuery('#modern-search-result').data('format') === 'halfmap'
        && window.matchMedia('(min-width: 992px)').matches;
}
window.stIsDesktopHalfMapSearch = stIsDesktopHalfMapSearch;

function stGetMapViewPopupContainers() {
    return jQuery('.map-view-popup.style-2:visible .full-map-form, .map-view-popup.style-2:visible .map-full-height, .map-view-popup.style-2:visible #map-search-form, .map-view-popup.style-2:visible #map-search-form-mb');
}

function stRefreshMapViewPopupMaps(payload, options) {
    payload = payload || {};
    options = options || {};
    var containers = stGetMapViewPopupContainers();
    if (!containers.length) {
        return;
    }

    var mapData = payload;
    var mapLat;
    var mapLng;
    var mapIcon;
    if (payload && payload.data_map && (payload.map_lat_center !== undefined || payload.map_icon)) {
        mapData = payload.data_map;
        mapLat = payload.map_lat_center;
        mapLng = payload.map_lng_center;
        mapIcon = payload.map_icon;
    } else if (payload && payload.data_map) {
        mapData = payload.data_map;
    }
    var mapVersion = options.version || '';
    var isMapMove = options.move_map || false;

    function runRefresh() {
        containers.each(function () {
            var t = jQuery(this);
            var instance = t.data('st-halfmap-instance');
            if (instance && instance.resize) {
                instance.resize();
            }
            if (mapData && (typeof initHalfMapBox === 'function' || typeof initHalfMap === 'function')) {
                if (typeof initHalfMapBox === 'function') {
                    initHalfMapBox(t, mapData, mapLat, mapLng, '', mapIcon, mapVersion, isMapMove);
                } else {
                    initHalfMap(t, mapData, mapLat, mapLng, '', mapIcon, mapVersion, isMapMove);
                }
            }
            instance = t.data('st-halfmap-instance');
            if (instance && instance.resize) {
                instance.resize();
            }
        });
    }

    runRefresh();
    if (typeof stRunAfterMapContainerLayout === 'function') {
        containers.each(function () {
            stRunAfterMapContainerLayout(this, runRefresh);
        });
    } else {
        setTimeout(runRefresh, 120);
        setTimeout(runRefresh, 450);
    }
}
window.stRefreshMapViewPopupMaps = stRefreshMapViewPopupMaps;

function clickPoup(mapLng, mapLat) {
    if (typeof stIsNeshanMap === 'function' && stIsNeshanMap()) {
        if (typeof stCreateNeshanMap === 'function') {
            stCreateNeshanMap({
                container: 'map-search-form',
                lat: mapLat,
                lng: mapLng,
                zoom: 6
            });
            return;
        }
    }
    var map = new mapboxgl.Map({
        container: 'map-search-form',
        style: 'mapbox://styles/mapbox/light-v10?optimize=true',
        center: [mapLng, mapLat],
        zoom: 6
    });
    if (typeof stApplyMapInteractionOptions === 'function') {
        stApplyMapInteractionOptions(map);
    }
}
