<?php
/**
 * Map provider helpers (Google / Mapbox / Neshan).
 */

if ( ! function_exists( 'st_get_map_provider' ) ) {
	/**
	 * @return string google|mapbox|neshan
	 */
	function st_get_map_provider() {
		$option = st()->get_option( 'st_googlemap_enabled', 'on' );
		if ( 'neshan' === $option ) {
			return 'neshan';
		}
		if ( 'off' === $option ) {
			return 'mapbox';
		}
		return 'google';
	}
}

if ( ! function_exists( 'st_is_google_map' ) ) {
	function st_is_google_map() {
		return 'google' === st_get_map_provider();
	}
}

if ( ! function_exists( 'st_is_neshan_map' ) ) {
	function st_is_neshan_map() {
		return 'neshan' === st_get_map_provider();
	}
}

if ( ! function_exists( 'st_is_mapbox_map' ) ) {
	function st_is_mapbox_map() {
		return 'mapbox' === st_get_map_provider();
	}
}

if ( ! function_exists( 'st_get_map_api_token' ) ) {
	function st_get_map_api_token() {
		if ( st_is_neshan_map() ) {
			return (string) st()->get_option( 'st_token_neshan', '' );
		}
		if ( st_is_mapbox_map() ) {
			$token = st()->get_option( 'st_token_mapbox', '' );
			if ( ! empty( $token ) ) {
				return $token;
			}
			return 'pk.eyJ1IjoidGhvYWluZ28iLCJhIjoiY2p3dTE4bDFtMDAweTQ5cm5rMXA5anUwMSJ9.RkIx76muBIvcZ5HDb2g0Bw';
		}
		return '';
	}
}

if ( ! function_exists( 'st_get_neshan_sdk_urls' ) ) {
	/**
	 * Neshan Web SDK — local copy first (faster, works when CDN is blocked).
	 */
	function st_get_neshan_sdk_urls() {
		$local_js = get_template_directory() . '/assets/neshan-sdk/v1.1.1/index.js';
		if ( file_exists( $local_js ) ) {
			$base = get_template_directory_uri() . '/assets/neshan-sdk/v1.1.1/';
			return [
				'js'      => $base . 'index.js',
				'css'     => $base . 'index.css',
				'version' => '1.1.1',
				'local'   => true,
			];
		}

		return [
			'js'      => 'https://static.neshan.org/sdk/mapboxgl/v1.13.2/neshan-sdk/v1.1.1/index.js',
			'css'     => 'https://static.neshan.org/sdk/mapboxgl/v1.13.2/neshan-sdk/v1.1.1/index.css',
			'version' => '1.1.1',
			'local'   => false,
		];
	}
}

if ( ! function_exists( 'st_get_map_marker_icons' ) ) {
	function st_get_map_marker_icons() {
		$base = get_template_directory_uri() . '/v2/images/markers/';
		return [
			'hotel_small' => $base . 'hotel_marker.png',
			'hotel_large' => $base . 'hotel_marker.png',
			'location'    => $base . 'hotel_marker.png',
			'activity'    => $base . 'ico_mapker_activity.png',
			'rental'      => $base . 'ico_mapker_rental.png',
			'tour'        => $base . 'ico_mapker_tour.png',
		];
	}
}

if ( ! function_exists( 'st_get_map_marker_icon' ) ) {
	/**
	 * @param string $post_type st_hotel|st_tours|st_activity|st_rental|location
	 * @param string $size      small|large
	 */
	function st_get_map_marker_icon( $post_type = '', $size = 'small' ) {
		$icons = st_get_map_marker_icons();
		$pt    = str_replace( 'st_', '', (string) $post_type );

		if ( '' === $pt ) {
			if ( is_singular( 'st_hotel' ) || is_page_template( 'template-hotel-search.php' ) ) {
				$pt = 'hotel';
			} elseif ( is_singular( 'st_tours' ) || is_page_template( 'template-tour-search.php' ) ) {
				$pt = 'tours';
			} elseif ( is_singular( 'st_activity' ) || is_page_template( 'template-activity-search.php' ) ) {
				$pt = 'activity';
			} elseif ( is_singular( 'st_rental' ) || is_page_template( 'template-rental-search.php' ) ) {
				$pt = 'rental';
			} else {
				$pt = 'hotel';
			}
		}

		if ( 'large' === $size ) {
			switch ( $pt ) {
				case 'hotel':
					return $icons['hotel_large'];
				case 'tours':
				case 'tour':
					return $icons['tour'];
				case 'activity':
					return $icons['activity'];
				case 'rental':
					return $icons['rental'];
				case 'location':
					return $icons['location'];
				default:
					return $icons['hotel_large'];
			}
		}

		switch ( $pt ) {
			case 'hotel':
				return $icons['hotel_small'];
			case 'tours':
			case 'tour':
				return $icons['tour'];
			case 'activity':
				return $icons['activity'];
			case 'rental':
				return $icons['rental'];
			case 'location':
				return $icons['location'];
			default:
				return $icons['hotel_small'];
		}
	}
}

if ( ! function_exists( 'st_build_single_item_map_popup_html' ) ) {
	function st_build_single_item_map_popup_html( $post_id = 0 ) {
		if ( ! $post_id ) {
			$post_id = get_the_ID();
		}
		$title   = get_the_title( $post_id );
		$address = (string) get_post_meta( $post_id, 'address', true );
		$link    = get_permalink( $post_id );
		$thumb   = get_the_post_thumbnail( $post_id, 'medium', [ 'class' => 'st-single-map-popup__image', 'loading' => 'lazy', 'decoding' => 'async' ] );

		$html  = '<div class="st-single-map-popup st-single-map-popup-card">';
		if ( $thumb ) {
			$html .= '<a href="' . esc_url( $link ) . '" class="st-single-map-popup__thumb">' . $thumb . '</a>';
		}
		$html .= '<div class="st-single-map-popup__body">';
		$html .= '<div class="st-single-map-popup__title"><a href="' . esc_url( $link ) . '">' . esc_html( $title ) . '</a></div>';
		if ( '' !== $address ) {
			$html .= '<div class="st-single-map-popup__address"><i class="stt-icon-location1"></i> ' . esc_html( $address ) . '</div>';
		}
		$html .= '</div></div>';
		return apply_filters( 'st_single_item_map_popup_html', $html, $post_id );
	}
}

if ( ! function_exists( 'st_build_single_item_map_data' ) ) {
	function st_build_single_item_map_data( $post_id = 0, $args = [] ) {
		if ( ! $post_id ) {
			$post_id = get_the_ID();
		}
		$lat = get_post_meta( $post_id, 'map_lat', true );
		$lng = get_post_meta( $post_id, 'map_lng', true );
		if ( '' === $lat || '' === $lng || ! is_numeric( $lat ) || ! is_numeric( $lng ) ) {
			return [];
		}

		$post_type = get_post_type( $post_id );
		$icon      = ! empty( $args['icon'] ) ? $args['icon'] : st_get_map_marker_icon( $post_type, 'large' );
		$content   = ! empty( $args['content_html'] ) ? $args['content_html'] : st_build_single_item_map_popup_html( $post_id );

		return [
			1 => [
				'id'           => $post_id,
				'post_id'      => $post_id,
				'name'         => get_the_title( $post_id ),
				'post_type'    => $post_type,
				'lat'          => (float) $lat,
				'lng'          => (float) $lng,
				'icon_mk'      => $icon,
				'content_html' => $content,
			],
		];
	}
}

if ( ! function_exists( 'st_encode_single_item_map_data' ) ) {
	function st_encode_single_item_map_data( $post_id = 0, $args = [] ) {
		return wp_json_encode( st_build_single_item_map_data( $post_id, $args ), JSON_FORCE_OBJECT );
	}
}

if ( ! function_exists( 'st_register_map_vendor_scripts' ) ) {
	function st_register_map_vendor_scripts() {
		$neshan = st_get_neshan_sdk_urls();
		wp_register_script(
			'mapbox-gl',
			'https://api.tiles.mapbox.com/mapbox-gl-js/v1.6.0/mapbox-gl.js',
			[],
			'1.6.0',
			false
		);
		wp_register_style(
			'mapbox-gl',
			'https://api.tiles.mapbox.com/mapbox-gl-js/v1.6.0/mapbox-gl.css',
			[],
			'1.6.0'
		);
		wp_register_script(
			'neshan-map-sdk',
			$neshan['js'],
			[],
			$neshan['version'],
			false
		);
		wp_register_style(
			'neshan-map-sdk',
			$neshan['css'],
			[],
			$neshan['version']
		);
		wp_register_script(
			'mapboxv5-geocoder',
			'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.3.0/mapbox-gl-geocoder.min.js',
			[ 'mapbox-gl' ],
			'4.3.0',
			true
		);
		wp_register_style(
			'mapbox-css-geocoder',
			'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.3.0/mapbox-gl-geocoder.css',
			[],
			'4.3.0'
		);
		wp_register_script(
			'st-map-provider',
			get_template_directory_uri() . '/js/st-map-provider.js',
			[ 'jquery' ],
			ST_TRAVELER_VERSION,
			! st_is_neshan_map()
		);
	}
}

if ( ! function_exists( 'st_enqueue_map_vendor_scripts' ) ) {
	function st_enqueue_map_vendor_scripts() {
		st_register_map_vendor_scripts();
		st_register_legacy_mapbox_handles();
		wp_enqueue_script( 'st-map-provider' );

		if ( st_is_neshan_map() ) {
			wp_enqueue_script( 'mapboxv5' );
			wp_enqueue_style( 'mapbox-css' );
			return;
		}

		if ( st_is_mapbox_map() ) {
			wp_enqueue_script( 'mapbox-gl' );
			wp_enqueue_style( 'mapbox-gl' );
			wp_enqueue_script( 'mapboxv5' );
			wp_enqueue_style( 'mapbox-css' );
		}
	}
}

if ( ! function_exists( 'st_register_legacy_mapbox_handles' ) ) {
	/**
	 * Legacy script handles used across partner/admin templates.
	 */
	function st_register_legacy_mapbox_handles() {
		st_register_map_vendor_scripts();

		if ( st_is_neshan_map() ) {
			$neshan = st_get_neshan_sdk_urls();
			wp_register_script(
				'mapboxv5',
				$neshan['js'],
				[],
				$neshan['version'],
				false
			);
			wp_register_style(
				'mapbox-css',
				$neshan['css'],
				[],
				$neshan['version']
			);
			return;
		}

		wp_register_script(
			'mapboxv5',
			'https://api.tiles.mapbox.com/mapbox-gl-js/v1.6.0/mapbox-gl.js',
			[ 'st-map-provider' ],
			'1.6.0',
			false
		);
		wp_register_style(
			'mapbox-css',
			'https://api.tiles.mapbox.com/mapbox-gl-js/v1.6.0/mapbox-gl.css',
			[],
			'1.6.0'
		);
		wp_register_script(
			'mapboxv5-geocoder',
			'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.3.0/mapbox-gl-geocoder.min.js',
			[ 'mapboxv5' ],
			'4.3.0',
			true
		);
		wp_register_style(
			'mapbox-css-geocoder',
			'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.3.0/mapbox-gl-geocoder.css',
			[],
			'4.3.0'
		);
	}
}

if ( ! function_exists( 'st_get_neshan_map_key' ) ) {
	function st_get_neshan_map_key() {
		$key = (string) st()->get_option( 'st_token_neshan', '' );
		if ( '' !== $key ) {
			return $key;
		}
		return st_get_map_api_token();
	}
}

if ( ! function_exists( 'st_get_google_maps_api_url' ) ) {
	/**
	 * Always use HTTPS (required on production hosts / reverse proxies).
	 */
	function st_get_google_maps_api_url() {
		$gg_api_key = (string) st()->get_option( 'google_api_key', '' );
		$locale     = get_locale();
		$lang       = $locale ? substr( $locale, 0, 2 ) : 'en';

		return add_query_arg(
			[
				'v'         => '3',
				'libraries' => 'places',
				'language'  => $lang,
				'key'       => $gg_api_key,
			],
			'https://maps.googleapis.com/maps/api/js'
		);
	}
}

if ( ! function_exists( 'st_enqueue_google_maps_script' ) ) {
	function st_enqueue_google_maps_script() {
		if ( ! st_is_google_map() ) {
			return;
		}
		$url = st_get_google_maps_api_url();
		wp_register_script( 'gmap-apiv3', $url, [ 'jquery' ], null, true );
		wp_enqueue_script( 'gmap-apiv3' );
	}
}

if ( ! function_exists( 'st_get_map_icon_marker' ) ) {
	function st_get_map_icon_marker() {
		$post_type = '';
		if ( is_singular( 'st_hotel' ) || is_page_template( 'template-hotel-search.php' ) ) {
			$post_type = 'st_hotel';
		} elseif ( is_singular( 'st_tours' ) || is_page_template( 'template-tour-search.php' ) ) {
			$post_type = 'st_tours';
		} elseif ( is_singular( 'st_rental' ) || is_page_template( 'template-rental-search.php' ) ) {
			$post_type = 'st_rental';
		} elseif ( is_singular( 'st_activity' ) || is_page_template( 'template-activity-search.php' ) ) {
			$post_type = 'st_activity';
		}

		$size = is_singular() ? 'large' : 'small';
		return st_get_map_marker_icon( $post_type, $size );
	}
}

if ( ! function_exists( 'st_get_map_frontend_config' ) ) {
	function st_get_map_frontend_config() {
		if ( is_rtl() ) {
			$text_rtl_mapbox = 'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js';
		} else {
			$text_rtl_mapbox = '';
		}

		$mapbox_token = '';
		if ( st_is_mapbox_map() ) {
			$mapbox_token = (string) st()->get_option( 'st_token_mapbox', '' );
			if ( '' === $mapbox_token ) {
				$mapbox_token = 'pk.eyJ1IjoidGhvYWluZ28iLCJhIjoiY2p3dTE4bDFtMDAweTQ5cm5rMXA5anUwMSJ9.RkIx76muBIvcZ5HDb2g0Bw';
			}
		}

		return [
			'map_provider'         => st_get_map_provider(),
			'st_googlemap_enabled' => st()->get_option( 'st_googlemap_enabled', 'on' ),
			'token_mapbox'         => $mapbox_token,
			'token_neshan'         => st_get_neshan_map_key(),
			'google_api_key'       => (string) st()->get_option( 'google_api_key', '' ),
			'st_icon_mapbox'       => st_get_map_icon_marker(),
			'map_markers'          => st_get_map_marker_icons(),
			'neshan_sdk'           => st_get_neshan_sdk_urls(),
			'text_rtl_mapbox'      => $text_rtl_mapbox,
		];
	}
}

if ( ! function_exists( 'st_localize_map_provider_config' ) ) {
	function st_localize_map_provider_config() {
		if ( is_admin() ) {
			return;
		}
		$config = st_get_map_frontend_config();
		wp_localize_script( 'st-map-provider', 'st_map_config', $config );
	}
	add_action( 'wp_enqueue_scripts', 'st_localize_map_provider_config', 1000 );
}

if ( ! function_exists( 'st_register_halfmap_scripts' ) ) {
	function st_register_halfmap_scripts() {
		if ( is_admin() || st_is_google_map() ) {
			return;
		}

		wp_register_script(
			'st-halfmap',
			get_template_directory_uri() . '/js/st-halfmap.js',
			[ 'jquery', 'st-map-provider', 'st-filter-mapbox-custom' ],
			ST_TRAVELER_VERSION,
			true
		);
	}
	add_action( 'wp_enqueue_scripts', 'st_register_halfmap_scripts', 997 );
}

if ( ! function_exists( 'st_register_filter_map_scripts' ) ) {
	/**
	 * Re-register half-map filter scripts with correct paths/deps (ionCube bundle may omit initHalfMap).
	 */
	function st_register_filter_map_scripts() {
		if ( is_admin() || st_is_google_map() ) {
			return;
		}

		st_register_halfmap_scripts();
		st_enqueue_map_filter_scripts();

		$uri   = get_template_directory_uri();
		$ver   = ST_TRAVELER_VERSION;
		$deps  = [ 'jquery', 'st-halfmap', 'st-filter-mapbox-custom', 'st-map-provider', 'mapboxv5' ];
		$mapbox_deps = [ 'jquery', 'st-filter-mapbox-custom', 'st-map-provider', 'mapboxv5' ];

		$scripts = [
			'filter-hotel'          => [ $uri . '/v3/js/filter/hotel.js', $deps ],
			'filter-tour'           => [ $uri . '/v3/js/tour.js', $deps ],
			'filter-rental'         => [ $uri . '/v3/js/rental.js', $deps ],
			'filter-activity'       => [ $uri . '/v3/js/activity.js', $deps ],
			'filter-hotel-mapbox'   => [ $uri . '/v3/js/filter/mapbox/filter-hotel-mapbox.js', $mapbox_deps ],
			'filter-tour-mapbox'    => [ $uri . '/v3/js/filter/mapbox/filter-tours-mapbox.js', $mapbox_deps ],
			'filter-rental-mapbox'  => [ $uri . '/v3/js/filter/mapbox/filter-rental-mapbox.js', $mapbox_deps ],
			'filter-activity-mapbox'=> [ $uri . '/v3/js/filter/mapbox/filter-activity-mapbox.js', $mapbox_deps ],
		];

		foreach ( $scripts as $handle => $data ) {
			wp_deregister_script( $handle );
			wp_register_script( $handle, $data[0], $data[1], $ver, true );
		}
	}
	add_action( 'wp_enqueue_scripts', 'st_register_filter_map_scripts', 998 );
}

if ( ! function_exists( 'st_register_single_detail_map_scripts' ) ) {
	/**
	 * Single hotel/tour/rental detail pages — ensure map SDK loads before single-hotel-detail.js.
	 */
	function st_register_single_detail_map_scripts() {
		if ( is_admin() || st_is_google_map() ) {
			return;
		}

		$uri  = get_template_directory_uri();
		$ver  = ST_TRAVELER_VERSION;
		st_register_halfmap_scripts();

		$deps = [ 'jquery', 'st-map-provider', 'mapboxv5', 'st-filter-mapbox-custom', 'st-halfmap' ];

		wp_deregister_script( 'single-hotel-detail' );
		wp_register_script(
			'single-hotel-detail',
			$uri . '/v3/js/single-hotel-detail.js',
			$deps,
			$ver,
			true
		);
	}
	add_action( 'wp_enqueue_scripts', 'st_register_single_detail_map_scripts', 999 );

	function st_enqueue_single_detail_map_scripts() {
		if ( is_admin() || st_is_google_map() ) {
			return;
		}

		if ( ! is_singular( [ 'st_hotel', 'st_tours', 'st_activity', 'st_rental', 'st_cars', 'hotel_room' ] ) ) {
			return;
		}

		st_register_single_detail_map_scripts();
		wp_enqueue_script( 'single-hotel-detail' );
	}
	add_action( 'wp_enqueue_scripts', 'st_enqueue_single_detail_map_scripts', 1002 );
}

if ( ! function_exists( 'st_enqueue_map_filter_scripts' ) ) {
	/**
	 * Half-map search scripts for new/elementor layouts.
	 */
	function st_enqueue_map_filter_scripts() {
		if ( st_is_google_map() ) {
			return;
		}

		wp_register_script(
			'st-filter-mapbox-custom',
			get_template_directory_uri() . '/v3/js/filter/mapbox/custom.js',
			[ 'jquery', 'st-map-provider', 'mapboxv5' ],
			ST_TRAVELER_VERSION,
			true
		);
		wp_enqueue_script( 'st-filter-mapbox-custom' );
	}
}

if ( ! function_exists( 'st_enqueue_map_scripts_frontend' ) ) {
	/**
	 * Always enqueue map SDK on frontend (new layout skips st_add_scripts localize).
	 */
	function st_enqueue_map_scripts_frontend() {
		if ( is_admin() ) {
			return;
		}

		st_register_map_vendor_scripts();
		st_register_legacy_mapbox_handles();

		if ( st_is_google_map() ) {
			st_enqueue_google_maps_script();
			wp_enqueue_script( 'st-map-provider' );
			return;
		}

		if ( st_is_neshan_map() ) {
			wp_enqueue_style( 'mapbox-css' );
			wp_enqueue_script( 'mapboxv5' );
			wp_enqueue_script( 'st-map-provider' );
			global $wp_scripts;
			if ( $wp_scripts instanceof WP_Scripts && isset( $wp_scripts->registered['st-map-provider'] ) ) {
				if ( ! in_array( 'mapboxv5', $wp_scripts->registered['st-map-provider']->deps, true ) ) {
					$wp_scripts->registered['st-map-provider']->deps[] = 'mapboxv5';
				}
			}
		} else {
			st_enqueue_map_vendor_scripts();
			wp_enqueue_script( 'st-map-provider' );
		}

		st_enqueue_map_filter_scripts();

		if ( st_is_neshan_map() ) {
			foreach ( [ 'mapbox-js', 'mapbox-gl' ] as $handle ) {
				wp_dequeue_script( $handle );
				wp_deregister_script( $handle );
				wp_dequeue_style( $handle );
				wp_deregister_style( $handle );
			}
		}
	}
	add_action( 'wp_enqueue_scripts', 'st_enqueue_map_scripts_frontend', 999 );
}

if ( ! function_exists( 'st_ensure_map_filter_script_deps' ) ) {
	/**
	 * Ensure half-map filter scripts load after vector map helpers.
	 */
	function st_ensure_map_filter_script_deps() {
		if ( is_admin() || st_is_google_map() ) {
			return;
		}

		st_enqueue_map_filter_scripts();

		global $wp_scripts;
		if ( ! $wp_scripts instanceof \WP_Scripts ) {
			return;
		}

		$filter_handles = [
			'filter-hotel',
			'filter-tour',
			'filter-rental',
			'filter-activity',
			'filter-hotel-mapbox',
			'filter-tour-mapbox',
			'filter-rental-mapbox',
			'filter-activity-mapbox',
		];

		foreach ( $filter_handles as $handle ) {
			if ( ! isset( $wp_scripts->registered[ $handle ] ) ) {
				continue;
			}
			if ( ! in_array( 'st-halfmap', $wp_scripts->registered[ $handle ]->deps, true ) ) {
				$wp_scripts->registered[ $handle ]->deps[] = 'st-halfmap';
			}
			if ( st_is_neshan_map() && ! in_array( 'mapboxv5', $wp_scripts->registered[ $handle ]->deps, true ) ) {
				$wp_scripts->registered[ $handle ]->deps[] = 'mapboxv5';
			}
			if ( ! in_array( 'st-filter-mapbox-custom', $wp_scripts->registered[ $handle ]->deps, true ) ) {
				$wp_scripts->registered[ $handle ]->deps[] = 'st-filter-mapbox-custom';
			}
			if ( ! in_array( 'st-map-provider', $wp_scripts->registered[ $handle ]->deps, true ) ) {
				$wp_scripts->registered[ $handle ]->deps[] = 'st-map-provider';
			}
		}
	}
	add_action( 'wp_enqueue_scripts', 'st_ensure_map_filter_script_deps', 1001 );
}

if ( ! function_exists( 'st_register_price_filter_script' ) ) {
	/**
	 * Persian digits and LTR number blocks for ionRangeSlider price filters.
	 */
	function st_register_price_filter_script() {
		if ( is_admin() ) {
			return;
		}

		wp_register_script(
			'st-price-filter',
			get_template_directory_uri() . '/js/st-price-filter.js',
			[ 'jquery' ],
			'1.0.1',
			true
		);
		wp_enqueue_script( 'st-price-filter' );
	}
	add_action( 'wp_enqueue_scripts', 'st_register_price_filter_script', 996 );
}

if ( ! function_exists( 'st_print_price_filter_styles' ) ) {
	function st_print_price_filter_styles() {
		if ( is_admin() ) {
			return;
		}

		echo '<style id="st-price-filter-styles">
.range-slider .irs .irs-from,
.range-slider .irs .irs-to,
.st-style-elementor .range-slider .irs .irs-from,
.st-style-elementor .range-slider .irs .irs-to{
    direction:rtl;
    white-space:nowrap;
}
.st-price-filter-num{
    direction:ltr;
    unicode-bidi:embed;
    display:inline-block;
}
.min-max-value .item-value span .st-price-filter-num{
    direction:ltr;
    unicode-bidi:embed;
}
</style>';
	}
	add_action( 'wp_head', 'st_print_price_filter_styles', 4 );
}

if ( ! function_exists( 'st_print_neshan_map_container_styles' ) ) {
	/**
	 * Map container must have explicit height for vector maps (Neshan/Mapbox canvas).
	 */
	function st_print_neshan_map_container_styles() {
		if ( is_admin() || st_is_google_map() ) {
			return;
		}
		echo '<style id="st-neshan-map-styles">
/* vanilla-js-mapbox: map container must have height */
.st-style-elementor.search-result-page .st-results .page-half-map{min-height:480px}
.st-style-elementor.search-result-page .st-results .page-half-map .col-right.maparea,
.st-style-elementor.search-result-page .st-results .maparea{min-height:calc(100vh - 220px);position:relative}
.st-style-elementor.search-result-page .st-results .maparea #map-search-form,
.st-style-elementor.search-result-page .st-results .maparea .map-full-height,
.st-style-elementor.search-result-page .st-results .maparea .full-map-form{
    position:absolute!important;top:0;left:0;right:0;bottom:0;
    width:100%!important;height:100%!important;min-height:400px
}
#map-search-form,#map-search-form-mb,#st-map,#list_mapbox,#list_map,.map-full-height,.full-map-form,.st-map-box .google-map-mapbox,#st_mapbox_custom{
    width:100%;min-height:400px
}
#map-search-form .mapboxgl-map,#st-map .mapboxgl-map,.map-full-height .mapboxgl-map{height:100%;width:100%}
#map-search-form a,#map-search-form-mb a,#st-map a{text-decoration:none!important;border:none;padding:0;margin:0}
.st-map-marker{display:flex;align-items:flex-end;justify-content:center;cursor:pointer;line-height:0;box-sizing:content-box}
.st-map-marker img{display:block;max-width:none;height:auto;pointer-events:none;flex-shrink:0}
.st-map-marker-small img{width:28px}
.st-map-marker-large img{width:48px}
#map-search-form.mapboxgl-map,#map-search-form .mapboxgl-map,#map-search-form-mb.mapboxgl-map,#map-search-form-mb .mapboxgl-map,.google-map-mapbox .mapboxgl-map,.google-map-mapbox .mapboxgl-canvas-container,.st-map-box .mapboxgl-map,.st-map-wrapper .mapboxgl-map,.map-view-popup.style-2 .mapboxgl-map{direction:ltr!important}
.mapboxgl-marker .st-map-marker{will-change:auto}
.mapboxgl-popup{max-width:320px!important;z-index:2}
.mapboxgl-popup-content{padding:0;border-radius:8px;overflow:hidden}
.st-single-map-popup-card{display:block;min-width:260px;max-width:300px}
.st-single-map-popup-card .st-single-map-popup__thumb{display:block;line-height:0;overflow:hidden}
.st-single-map-popup-card .st-single-map-popup__thumb img{width:100%;height:auto;display:block;object-fit:cover;max-height:160px}
.st-single-map-popup-card .st-single-map-popup__body{padding:10px 12px}
.st-single-map-popup-card .st-single-map-popup__title{font-weight:600;font-size:15px;margin-bottom:4px}
.st-single-map-popup-card .st-single-map-popup__title a{color:inherit;text-decoration:none}
.st-single-map-popup-card .st-single-map-popup__address{color:#5E6D77;font-size:13px}
#st-login-form-page .st-icheck-item,.login-regiter-popup.style-9 .st-icheck-item{position:relative;padding-left:32px}
#st-login-form-page .st-icheck-item label,.login-regiter-popup.style-9 .st-icheck-item label{position:relative;display:block;cursor:pointer;margin-bottom:0}
#st-login-form-page .st-icheck-item label input[type=checkbox],.login-regiter-popup.style-9 .st-icheck-item label input[type=checkbox]{position:absolute;opacity:0;width:0;height:0;margin:0}
#st-login-form-page .st-icheck-item label .checkmark,.login-regiter-popup.style-9 .st-icheck-item label .checkmark{position:absolute;left:-32px;top:3px;margin-right:0}
#st-login-form-page .st-icheck-label-text,.login-regiter-popup.style-9 .st-icheck-label-text{display:inline-block;padding-left:8px}
html[dir=rtl] #st-login-form-page .st-icheck-item,html[dir=rtl] .login-regiter-popup.style-9 .st-icheck-item{padding-left:0;padding-right:32px}
html[dir=rtl] #st-login-form-page .st-icheck-item label .checkmark,html[dir=rtl] .login-regiter-popup.style-9 .st-icheck-item label .checkmark{left:auto;right:-32px}
html[dir=rtl] #st-login-form-page .st-icheck-label-text,html[dir=rtl] .login-regiter-popup.style-9 .st-icheck-label-text{padding-left:0;padding-right:8px}
.st-style-elementor.search-result-page .st-results .page-half-map .col-right.maparea,.st-style-elementor.search-result-page .st-results .maparea{position:relative;overflow:hidden}
.map-view-popup.style-2{position:fixed!important;top:0;left:0;width:100%;height:100%;z-index:999999;box-sizing:border-box}
.map-view-popup.style-2 .full-map-form,.map-view-popup.style-2 #map-search-form{width:100%!important;min-height:320px;height:calc(100vh - 120px);max-height:calc(100vh - 120px);position:relative;overflow:hidden!important;display:block}
#map-search-form,#map-search-form-mb,.map-full-height,.page-half-map .maparea #map-search-form{overflow:hidden!important}
.mapboxgl-map,.mapboxgl-canvas-container{overflow:hidden!important}
.mapboxgl-marker{position:absolute;will-change:transform}
.map-view-popup.style-2 .mapboxgl-map,.map-view-popup.style-2 .mapboxgl-canvas-container,.map-view-popup.style-2 .mapboxgl-canvas{width:100%!important;height:100%!important}
.st-blog .pagination .nav-previous a .post-title,.st-blog .pagination .nav-next a .post-title,.blog-content .pagination .nav-previous a .post-title,.blog-content .pagination .nav-next a .post-title{width:279.66px;height:52px;text-align:right!important;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;line-height:1.3}
.neshan-map-type-controller,.map-type-controller,.mapboxgl-ctrl-bottom-left .map-type-controller{display:none!important}
.map-view-popup.style-2 .st-map-box,.map-view-popup.style-2 .google-map-mapbox{position:relative;min-height:420px;height:60vh;width:100%;overflow:hidden}
.map-view-popup.style-2 #st-map,.map-view-popup.style-2 .st-map-canvas,.map-view-popup.style-2 [id^="st-map-"]{position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%;min-height:420px}
.st-map-box .google-map-mapbox,.st-map-wrapper .google-map-mapbox{position:relative;min-height:320px;height:320px;width:100%;overflow:hidden}
.st-map-box #st-map,.st-map-box .st-map-canvas,.st-map-box [id^="st-map-"],.st-map-wrapper #st-map,.st-map-wrapper .st-map-canvas,.st-map-wrapper [id^="st-map-"]{position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%;min-height:320px}
.st-map-box #st-map,.st-map-wrapper #st-map{width:100%;min-height:320px}
.st-single-map-popup{padding:8px 4px}
.st-single-map-popup__title{font-weight:600;margin-bottom:6px}
.st-single-map-popup__address{color:#5E6D77;font-size:14px}
</style>';
	}
	add_action( 'wp_head', 'st_print_neshan_map_container_styles', 3 );
}

if ( ! function_exists( 'st_print_neshan_resource_hints' ) ) {
	function st_print_neshan_resource_hints() {
		if ( is_admin() || ! st_is_neshan_map() ) {
			return;
		}
		$sdk     = st_get_neshan_sdk_urls();
		$markers = st_get_map_marker_icons();
		echo '<link rel="preload" href="' . esc_url( $sdk['css'] ) . '" as="style">' . "\n";
		echo '<link rel="preload" href="' . esc_url( $sdk['js'] ) . '" as="script">' . "\n";
		foreach ( array_unique( array_values( $markers ) ) as $icon_url ) {
			echo '<link rel="preload" href="' . esc_url( $icon_url ) . '" as="image">' . "\n";
		}
		if ( empty( $sdk['local'] ) ) {
			echo '<link rel="dns-prefetch" href="//static.neshan.org">' . "\n";
		}
	}
	add_action( 'wp_head', 'st_print_neshan_resource_hints', 1 );
}

if ( ! function_exists( 'st_print_map_provider_config' ) ) {
	/**
	 * Patch st_params after ionCube / new-layout footer localize.
	 */
	function st_print_map_provider_config() {
		if ( is_admin() ) {
			return;
		}
		$config = st_get_map_frontend_config();
		printf(
			'<script id="st-map-provider-config">(function(){var c=%s;window.st_map_config=window.st_map_config||{};window.st_params=window.st_params||{};for(var k in c){if(Object.prototype.hasOwnProperty.call(c,k)){window.st_map_config[k]=c[k];window.st_params[k]=c[k];}}})();</script>',
			wp_json_encode( $config )
		);
	}
	add_action( 'wp_head', 'st_print_map_provider_config', 99 );
	add_action( 'wp_footer', 'st_print_map_provider_config', 999 );
}

if ( ! function_exists( 'st_print_map_provider_body_attrs' ) ) {
	/**
	 * Fallback map settings on <body> when legacy scripts overwrite st_params.
	 */
	function st_print_map_provider_body_attrs( $classes ) {
		if ( is_admin() ) {
			return $classes;
		}

		$provider = st_get_map_provider();
		if ( 'neshan' === $provider ) {
			$classes[] = 'st-map-provider-neshan';
		} elseif ( 'mapbox' === $provider ) {
			$classes[] = 'st-map-provider-mapbox';
		}

		return $classes;
	}
	add_filter( 'body_class', 'st_print_map_provider_body_attrs' );

	function st_print_map_provider_body_data_attrs() {
		if ( is_admin() ) {
			return;
		}

		$provider = st_get_map_provider();
		$neshan   = st_get_neshan_map_key();

		printf(
			'<script id="st-map-provider-body-data">document.body.setAttribute("data-st-map-provider","%s");%s</script>',
			esc_attr( $provider ),
			$neshan ? 'document.body.setAttribute("data-st-token-neshan",' . wp_json_encode( $neshan ) . ');' : ''
		);
	}
	add_action( 'wp_body_open', 'st_print_map_provider_body_data_attrs', 1 );
	add_action( 'wp_footer', 'st_print_map_provider_body_data_attrs', 1 );
}
