/**
 * Half-map initializer for Neshan / Mapbox (new Elementor layouts).
 * Ensures initHalfMap exists even when v3/js/main.js is not enqueued.
 */
(function (window) {
    'use strict';

    function normalizeCoords(mapLat, mapLng) {
        mapLat = parseFloat(mapLat);
        mapLng = parseFloat(mapLng);
        if (isNaN(mapLat) || isNaN(mapLng) || (mapLat === 0 && mapLng === 0)) {
            mapLat = 35.6892;
            mapLng = 51.389;
        }
        return { lat: mapLat, lng: mapLng };
    }

    function initHalfMapNeshan(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, isMapMove) {
        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 = typeof mapEl.data('zoom') !== 'undefined' ? mapEl.data('zoom') : 13;
        }
        if (!mapIcon || (typeof mapIcon === 'string' && mapIcon.length <= 0)) {
            mapIcon = mapEl.data('icon');
        }

        var coords = normalizeCoords(mapLat, mapLng);
        mapLat = coords.lat;
        mapLng = coords.lng;
        mapZoom = parseFloat(mapZoom);
        if (isNaN(mapZoom)) {
            mapZoom = 13;
        }

        var containerId = mapEl.attr('id');
        if (!containerId || !mapEl.get(0)) {
            return;
        }

        if (mapEl.data('st-neshan-map')) {
            try {
                mapEl.data('st-neshan-map').remove();
            } catch (e) {}
            mapEl.removeData('st-neshan-map');
        }

        var createMap = typeof stCreateNeshanMap === 'function'
            ? stCreateNeshanMap
            : function (opts) {
                return (typeof stLoadNeshanSdk === 'function' ? stLoadNeshanSdk() : Promise.resolve()).then(function () {
                    if (!window.nmp_mapboxgl || !window.nmp_mapboxgl.Map) {
                        return null;
                    }
                    var mapOptions = typeof stBuildNeshanMapOptions === 'function'
                        ? stBuildNeshanMapOptions(opts)
                        : null;
                    return mapOptions ? new window.nmp_mapboxgl.Map(mapOptions) : null;
                });
            };

        createMap({
            container: containerId,
            lat: mapLat,
            lng: mapLng,
            zoom: mapZoom
        }).then(function (map) {
            if (!map) {
                return;
            }

            mapEl.data('st-neshan-map', map);

            if (typeof stApplyMapInteractionOptions === 'function') {
                stApplyMapInteractionOptions(map);
            }

            map.on('load', function () {
                var locations = mapData;
                var keys = Object.keys(locations || {});
                if (keys.length) {
                    keys.forEach(function (k) {
                        var location = locations[k];
                        if (!location || location.lat === undefined || location.lng === undefined) {
                            return;
                        }

                        var el = typeof stCreateMapMarkerElement === 'function'
                            ? stCreateMapMarkerElement(location, mapEl, '', mapIcon)
                            : (function () {
                                var node = document.createElement('div');
                                node.className = 'st-map-marker st-map-marker-large';
                                node.style.backgroundImage = 'url(' + (location.icon_mk || mapIcon || '') + ')';
                                node.style.backgroundSize = '100%';
                                node.style.width = '48px';
                                node.style.height = '48px';
                                return node;
                            })();

                        var popup = new window.nmp_mapboxgl.Popup({ offset: [0, -30] })
                            .setHTML(String(location.content_html || ''));

                        new window.nmp_mapboxgl.Marker({ element: el, anchor: 'bottom' })
                            .setLngLat([parseFloat(location.lng), parseFloat(location.lat)])
                            .setPopup(popup)
                            .addTo(map);
                    });
                }

                if (map.resize) {
                    map.resize();
                }
            });
        });
    }

    function stTravelerUseVectorMap() {
        if (typeof stShouldUseNeshanMap === 'function' && stShouldUseNeshanMap()) {
            return true;
        }
        if (typeof stIsNeshanMap === 'function' && stIsNeshanMap()) {
            return true;
        }
        return typeof stIsMapboxMap === 'function' && stIsMapboxMap();
    }

    function initHalfMapVector(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove) {
        if (typeof initHalfMapBox === 'function') {
            return initHalfMapBox(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove);
        }
        if (typeof stShouldUseNeshanMap === 'function' && stShouldUseNeshanMap()) {
            return initHalfMapNeshan(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, isMapMove);
        }
        if (typeof stIsNeshanMap === 'function' && stIsNeshanMap()) {
            return initHalfMapNeshan(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, isMapMove);
        }
        console.warn('[Traveler] Vector map is selected but map scripts are not loaded.');
    }

    var previousInit = window.initHalfMap;

    window.initHalfMapNeshan = initHalfMapNeshan;
    window.initHalfMap = function (mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove) {
        var useVector = stTravelerUseVectorMap();

        if (useVector) {
            return initHalfMapVector(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove);
        }

        if (typeof previousInit === 'function' && previousInit !== window.initHalfMap) {
            return previousInit(mapEl, mapData, mapLat, mapLng, mapZoom, mapIcon, mapVersion, isMapMove);
        }

        console.warn('[Traveler] Google Maps is not loaded. Check Theme Options > Map API.');
    };
})(window);
