<?php

/**
 * Enqueue scripts
 * @see codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts
 * @category Functions
 * @author Krik
 */

// Enqueue scripts
add_action('wp_enqueue_scripts', 'krik_enqueue_scripts');

// Defer scripts
// add_filter('script_loader_tag', 'krik_defer_scripts', 10, 2);

// Async scripts
// add_filter('script_loader_tag', 'krik_async_scripts', 10, 2);

// Remove jQuery migrate
add_action('wp_default_scripts', 'krik_dequeue_jquery_migrate');

function krik_enqueue_scripts()
{
	if (!is_admin()) {
		wp_deregister_script('jquery');
		wp_register_script('jquery', '', '', '', true);
	}

	// wp_register_script('manifest', mix('scripts/manifest.js'), null, null, true);
	// wp_enqueue_script('manifest');

	// wp_register_script('vendor', mix('scripts/vendor.js'), null, null, true);
	// wp_enqueue_script('vendor');

	// wp_register_script('app', mix('scripts/app.js'), null, null, true);
	// wp_enqueue_script('app');

	wp_deregister_script('wp-embed');
}

function krik_defer_scripts($tag, $handle)
{
	$defer_scripts = array(
		'manifest',
		'vendor',
		'app'
	);

	foreach ($defer_scripts as $defer_script) {
		if ($defer_script === $handle) {
			return str_replace(' src', ' defer="defer" src', $tag);
		}
	}

	return $tag;
}

function krik_async_scripts($tag, $handle)
{
	$async_scripts = array('...');

	foreach ($async_scripts as $async_script) {
		if ($async_script === $handle) {
			return str_replace(' src', ' async="async" src', $tag);
		}
	}

	return $tag;
}

function krik_dequeue_jquery_migrate($scripts)
{
	if (!is_admin() && !empty($scripts->registered['jquery'])) {
		$jquery_dependencies = $scripts->registered['jquery']->deps;
		$scripts->registered['jquery']->deps = array_diff($jquery_dependencies, array('jquery-migrate'));
	}
}
