( function () {
	'use strict';

	var cfg = window.wppsOpenExternalLinks || {};
	var siteHost = normalizeHost( cfg.siteHost || window.location.hostname );

	function normalizeHost( host ) {
		return String( host || '' )
			.replace( /^www\./i, '' )
			.toLowerCase();
	}

	function isExternalUrl( href ) {
		if ( ! href ) {
			return false;
		}

		href = String( href ).trim();
		if ( href === '' || href.charAt( 0 ) === '#' ) {
			return false;
		}

		if ( href.indexOf( 'mailto:' ) === 0 || href.indexOf( 'tel:' ) === 0 || href.indexOf( 'javascript:' ) === 0 ) {
			return false;
		}

		if ( href.charAt( 0 ) === '/' && href.charAt( 1 ) !== '/' ) {
			return false;
		}

		var anchor = document.createElement( 'a' );
		anchor.href = href;

		if ( ! anchor.hostname ) {
			return false;
		}

		var protocol = anchor.protocol.replace( ':', '' ).toLowerCase();
		if ( protocol !== 'http' && protocol !== 'https' ) {
			return false;
		}

		return normalizeHost( anchor.hostname ) !== siteHost;
	}

	function ensureSafeRel( link ) {
		var required = [ 'noopener', 'noreferrer', 'nofollow' ];
		var tokens = ( link.getAttribute( 'rel' ) || '' )
			.split( /\s+/ )
			.filter( Boolean )
			.map( function ( token ) {
				return token.toLowerCase();
			} );

		required.forEach( function ( token ) {
			if ( tokens.indexOf( token ) === -1 ) {
				tokens.push( token );
			}
		} );

		link.setAttribute( 'rel', tokens.join( ' ' ) );
	}

	function processLink( link ) {
		if ( ! link || link.nodeName !== 'A' ) {
			return;
		}

		if ( link.closest( '#wpadminbar' ) ) {
			return;
		}

		var href = link.getAttribute( 'href' );
		if ( ! isExternalUrl( href ) ) {
			return;
		}

		var target = ( link.getAttribute( 'target' ) || '' ).toLowerCase();
		if ( target !== '_blank' && target !== '_parent' && target !== '_self' && target !== '_top' ) {
			link.setAttribute( 'target', '_blank' );
		}

		ensureSafeRel( link );
	}

	function processRoot( root ) {
		if ( ! root || ! root.querySelectorAll ) {
			return;
		}

		root.querySelectorAll( 'a[href]' ).forEach( processLink );
	}

	var elementorHookRegistered = false;

	function registerElementorHook() {
		if ( elementorHookRegistered || ! window.elementorFrontend || ! window.elementorFrontend.hooks ) {
			return;
		}

		elementorHookRegistered = true;
		window.elementorFrontend.hooks.addAction( 'frontend/element_ready/global', function ( $scope ) {
			if ( $scope && $scope[ 0 ] ) {
				processRoot( $scope[ 0 ] );
			}
		} );
	}

	function boot() {
		processRoot( document.body );
		registerElementorHook();
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', boot );
	} else {
		boot();
	}

	if ( window.jQuery ) {
		window.jQuery( window ).on( 'elementor/frontend/init', boot );
	}
}() );
