<?php
namespace TotalTheme\Scripts;

use TotalTheme\Forms\Select_Wrap;
use TotalTheme\Header\Core as Header;
use TotalTheme\Mobile\Menu as Mobile_Menu;
use TotalTheme\Header\Sticky as Sticky_Header;
use TotalTheme\Theme_Icons;

defined( 'ABSPATH' ) || exit;

/**
 * JS Scripts.
 *
 * @package TotalTheme
 * @subpackage Scripts
 * @version 5.5
 */
class JS {

	/**
	 * Returns the correct JS extension for files.
	 */
	public static function js_extension() {
		return WPEX_MINIFY_JS ? '.min.js' : '.js';
	}

	/**
	 * Register Theme scripts.
	 */
	public static function register() {
		$js_extension = self::js_extension();

		// WPEX Superfish
		wp_register_script(
			'wpex-superfish',
			wpex_asset_url( 'js/dynamic/wpex-superfish' . $js_extension ),
			[ 'jquery', 'hoverIntent' ],
			WPEX_THEME_VERSION,
			true
		);

		/**
		 * Filters the superfish js params.
		 *
		 * @param array $params
		 */
		$superfish_params = (array) apply_filters( 'wpex_superfish_params', [
			'delay'    => 600,
			'speed'    => 'fast',
			'speedOut' => 'fast',
		] );

		wp_localize_script(
			'wpex-superfish',
			'wpex_superfish_params',
			$superfish_params
		);

		// Easing.
		wp_register_script(
			'easing',
			wpex_asset_url( 'js/vendors/jquery.easing' . $js_extension ),
			[ 'jquery' ],
			'1.3.2',
			true
		);

		// Comment Reply.
		wp_register_script(
			'wpex-comment-reply',
			wpex_asset_url( 'js/dynamic/wp/wpex-comment-reply' . $js_extension ),
			[],
			'2.7.0',
			true
		);

		// Sidr.
		wp_register_script(
			'wpex-sidr',
			wpex_asset_url( 'js/dynamic/wpex-sidr' . $js_extension ),
			[],
			WPEX_THEME_VERSION,
			true
		);

		// Slider Pro.
		wp_deregister_script( 'slider-pro' ); // prevent issues since the version in Total has some tweaks.
		wp_register_script(
			'slider-pro', // @todo change to wpex-slider-pro to prevent conflicts.
			wpex_asset_url( 'lib/slider-pro/jquery.sliderPro' . $js_extension ),
			[ 'jquery' ],
			WPEX_THEME_VERSION, // modified a bit by Total.
			true
		);

		wp_register_script(
			'wpex-slider-pro-custom-thumbs',
			wpex_asset_url( 'lib/slider-pro/jquery.sliderProCustomThumbnails' . $js_extension ),
			[ 'jquery', 'slider-pro' ],
			WPEX_THEME_VERSION,
			true
		);

		wp_register_script(
			'wpex-slider-pro',
			wpex_asset_url( 'js/dynamic/wpex-slider-pro' . $js_extension ),
			[ 'jquery', 'slider-pro', WPEX_THEME_JS_HANDLE ], // @todo WPEX_THEME_JS_HANDLE no longer needed?
			WPEX_THEME_VERSION,
			true
		);

		$slider_prev_icon = apply_filters( 'wpex_slider_prev_icon', 'material/arrow-back-ios' );
		$slider_next_icon = apply_filters( 'wpex_slider_next_icon', 'material/arrow-forward-ios' );

		wp_localize_script(
			'wpex-slider-pro',
			'wpex_slider_pro_params',
			[
				'i18n' => [
					'NEXT' => esc_html__( 'next Slide', 'total' ),
					'PREV' => esc_html__( 'previous Slide', 'total' ),
					'GOTO' => esc_html__( 'go to slide', 'total' ),
				],
				'previousArrow' => '<div class="sp-arrow sp-previous-arrow" tabindex="0" role="button"><span class="screen-reader-text">' . esc_html__( 'previous slide', 'total' ) . '</span><span class="sp-arrow-inner wpex-flex wpex-items-center wpex-justify-center wpex-w-100 wpex-h-100">' . Theme_Icons::get_icon( $slider_prev_icon ) . '</span></div>',
				'nextArrow' => '<div class="sp-arrow sp-next-arrow" tabindex="0" role="button"><span class="screen-reader-text">' . esc_html__( 'next slide', 'total' ) . '</span></span><span class="sp-arrow-inner wpex-flex wpex-items-center wpex-justify-center wpex-w-100 wpex-h-100">' . Theme_Icons::get_icon( $slider_next_icon ) . '</div>',
			]
		);

		// Social share.
		wp_register_script(
			'wpex-social-share',
			wpex_asset_url( 'js/dynamic/wpex-social-share' . $js_extension ),
			[],
			WPEX_THEME_VERSION,
			true
		);

		// Isotope.
		wp_register_script(
			'isotope',
			wpex_asset_url( 'js/vendors/isotope.pkgd' . $js_extension ),
			[ 'imagesloaded' ],
			'3.0.6',
			true
		);

		wp_register_script(
			'wpex-isotope',
			wpex_asset_url( 'js/dynamic/wpex-isotope' . $js_extension ),
			[ 'isotope' ],
			WPEX_THEME_VERSION,
			true
		);

		wp_localize_script(
			'wpex-isotope',
			'wpex_isotope_params',
			wpex_get_masonry_settings()
		);
	}

	/**
	 * Enqueue Theme scripts.
	 */
	public static function enqueue() {

		// Comment reply.
		if ( is_singular()
			&& comments_open()
			&& get_option( 'thread_comments' )
			&& ! wp_script_is ( 'comment-reply' )
		) {
			wp_enqueue_script( 'wpex-comment-reply' );
		}

		// Sidr Mobile Menu.
		if ( 'sidr' === Mobile_Menu::style() && wpex_has_header_mobile_menu() ) {
			wp_enqueue_script( 'wpex-sidr' );
		}

		// Menu dropdowns.
		if ( 'sfhover' === wpex_header_menu_dropdown_method() && wpex_has_header_menu() ) {
			wp_enqueue_script( 'wpex-superfish' );
		}

		// jQuery easing.
		if ( wpex_get_local_scroll_easing() ) {
			wp_enqueue_script( 'easing' );
		}

		// Load minified theme JS.
		if ( WPEX_MINIFY_JS ) {
			wp_enqueue_script(
				WPEX_THEME_JS_HANDLE,
				wpex_asset_url( 'js/total.min.js' ),
				[],
				WPEX_THEME_VERSION,
				true
			);
		}

		// Load all non-minified Theme js
		else {

			wp_enqueue_script(
				'wpex-polyfills',
				wpex_asset_url( 'js/core/polyfills.js' ),
				[],
				WPEX_THEME_VERSION,
				true
			);

			wp_enqueue_script(
				'wpex-equal-heights',
				wpex_asset_url( 'js/core/wpexEqualHeights.js' ),
				[],
				WPEX_THEME_VERSION,
				true
			);

			// Core global functions
			wp_enqueue_script(
				WPEX_THEME_JS_HANDLE,
				wpex_asset_url( 'js/total.js' ),
				[
					'wpex-polyfills',
					'wpex-equal-heights'
				],
				WPEX_THEME_VERSION,
				true
			);

		}

		// Localize core js
		if ( $l10n = self::l10n() ) {
			wp_localize_script( WPEX_THEME_JS_HANDLE, 'wpex_theme_params', $l10n );
		}

	}

	/**
	 * Main js l10n.
	 */
	protected static function l10n() {
		$header_style = Header::style();
		$mm_breakpoint = Mobile_Menu::breakpoint();

		$l10n = [
			'menuWidgetAccordion'  => true,
			'mobileMenuBreakpoint' => $mm_breakpoint,

			// Translatable strings.
			'i18n' => [
				'openSubmenu'  => esc_html__( 'Open submenu of %s', 'total' ),
				'closeSubmenu' => esc_html__( 'Close submenu of %s', 'total' ),
			],

		];

		/**** Header params ****/
		if ( 'disabled' !== $header_style ) {

			// Sticky Header.
			if ( Sticky_Header::is_enabled() ) {

				$l10n['stickyHeaderStyle'] = wp_strip_all_tags( Sticky_Header::style() );

				if ( wpex_has_custom_header() ) {
					$l10n['hasStickyMobileHeader'] = true;
				} else {
					$l10n['hasStickyMobileHeader'] = (bool) get_theme_mod( 'fixed_header_mobile' );
				}

				// Sticky header breakpoint.
				$sticky_breakpoint = $mm_breakpoint + 1;
				$l10n['stickyHeaderBreakPoint'] = (int) apply_filters( 'wpex_sticky_header_breakpoint', $sticky_breakpoint );

				// Sticky header start position.
				$fixed_startp = Sticky_Header::get_start_position();
				if ( $fixed_startp ) {
					$fixed_startp = str_replace( 'px', '', $fixed_startp );
					$l10n['stickyHeaderStartPosition'] = wp_strip_all_tags( $fixed_startp ); // can be int or element class/id
				}

				// Make sure sticky is always enabled if responsive is disabled.
				if ( ! wpex_is_layout_responsive() ) {
					$l10n['hasStickyMobileHeader'] = true;
				}

				// Shrink sticky header > used for local-scroll offset.
				if ( Sticky_Header::is_shrink_enabled() ) {
					$l10n['hasStickyHeaderShrink'] = true;
					$l10n['hasStickyMobileHeaderShrink'] = Sticky_Header::is_shrink_enabled_mobile();
					$shrink_header_height = intval( get_theme_mod( 'fixed_header_shrink_end_height' ) ?: 50 );
					if ( ! Header::has_flex_container() ) {
						$shrink_header_height = $shrink_header_height + 20;
					}
					$l10n['shrinkHeaderHeight'] = $shrink_header_height;
				}

			}

			// Sticky Navbar.
			if ( wpex_has_sticky_header_menu() ) {
				$l10n['stickyNavbarBreakPoint'] = 960;
			}

			// Header five.
			if ( 'five' === $header_style ) {
				$l10n['headerFiveSplitOffset'] = 1;
			}

		} // End header params.

		// Sidr settings @todo move to it's own file so it's localized to the sidr script.
		if ( 'sidr' === Mobile_Menu::style() ) {
			$sidr_position = get_theme_mod( 'mobile_menu_sidr_direction' );
			if ( ! $sidr_position ) {
				if ( wpex_has_flex_header() ) {
					$toggle_style = wpex_header_menu_mobile_toggle_style();
					if ( 'centered_logo' === $toggle_style || 'next_to_logo' === $toggle_style ) {
						$sidr_position = 'left';
					} else {
						$sidr_position = 'right';
					}
				} else {
					$sidr_position = 'right';
				}
			}
			$l10n['sidrDarkSurface']          = wp_validate_boolean( get_theme_mod( 'mobile_menu_sidr_dark_surface', true ) );
			$l10n['sidrSource']               = wpex_sidr_menu_source();
			$l10n['sidrDisplace']             = wp_validate_boolean( get_theme_mod( 'mobile_menu_sidr_displace', false ) );
			$l10n['sidrSide']                 = wp_strip_all_tags( $sidr_position );
			$l10n['sidrBodyNoScroll']         = false;
			$l10n['sidrSpeed']                = 300;
			$l10n['mobileMenuAriaLabel']      = esc_attr( wpex_get_aria_label( 'mobile_menu' ) );
			$l10n['mobileMenuCloseAriaLabel'] = esc_attr( wpex_get_aria_label( 'mobile_menu_close' ) );
		}

		// Sticky topBar.
		if ( ! wpex_vc_is_inline()
			&& apply_filters( 'wpex_has_sticky_topbar', get_theme_mod( 'top_bar_sticky' ) )
		) {
			$l10n['stickyTopBarBreakPoint'] = 960;
			$l10n['hasStickyTopBarMobile']  = wp_validate_boolean( get_theme_mod( 'top_bar_sticky_mobile', true ) );
		}

		// Custom selects.
		if ( apply_filters( 'wpex_custom_selects_js', true ) ) {
			$l10n['selectArrowIcon'] = esc_html( Select_Wrap::get_arrow_icon_html() );
			$l10n['customSelects'] = '.widget_categories form,.widget_archive select,.vcex-form-shortcode select';

			// WooCommerce custom selects.
			if ( WPEX_WOOCOMMERCE_ACTIVE && wpex_has_woo_mods() ) {
				$l10n['customSelects'] .= ',.woocommerce-ordering .orderby,#dropdown_product_cat,.single-product .variations_form .variations select';
				if ( class_exists( 'WC_Product_Addons' ) ) {
					$l10n['customSelects'] .= ',.wc-pao-addon .wc-pao-addon-wrap select';
				}
			}

			// BBPress custom selects.
			if ( WPEX_BBPRESS_ACTIVE ) {
				$l10n['customSelects'] .= ',#bbp_stick_topic_select,#bbp_topic_status_select';
			}
		}

		/**
		 * Local Scroll args.
		 */
		$l10n['scrollToHash']          = wpex_has_local_scroll_on_load();
		$l10n['scrollToHashTimeout']   = wpex_get_local_scroll_on_load_timeout();
		$l10n['localScrollTargets']    = wpex_get_local_scroll_targets();
		$l10n['localScrollUpdateHash'] = wpex_has_local_scroll_hash_update();
		$l10n['localScrollHighlight']  = wpex_has_local_scroll_menu_highlight();
		$l10n['localScrollSpeed']      = wpex_get_local_scroll_speed();

		if ( $local_scroll_easing = wpex_get_local_scroll_easing() ) {
			$l10n['localScrollEasing'] = esc_attr( $local_scroll_easing );
		}

		/**
		 * Icons.
		 */
		$mm_subdrop_icon = (string) apply_filters( 'wpex_mobile_menu_open_submenu_icon', 'angle-down' );
		$l10n['mobileMenuOpenSubmenuIcon'] = Theme_Icons::get_icon( $mm_subdrop_icon, 'wpex-open-submenu__icon wpex-transition-all wpex-duration-300' );

		/**
		 * Filters the array of localized args for the theme js.
		 *
		 * @param array $l10n
		 * @todo rename to wpex_theme_js_l10n
		 */
		$l10n = (array) apply_filters( 'wpex_localize_array', $l10n );

		return $l10n;
	}

}