<?php
use Illuminate\Support\Str;
/**
 * 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', 0);
add_action('wp_enqueue_scripts', 'krik_enqueue_additional_scripts', 0);

// Add type module to scripts
add_filter( 'script_loader_tag', 'krik_add_type_module_script', 10, 3 );

// Defer scripts
if(!is_admin()) {
	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() {
	static $manifests = [];
	$assetsPath = WP_HOME . '/app/build';
	$entrypoints = ['public/app/themes/' . WP_DEFAULT_THEME . '/main.js'];
	$buildDirectory = '/http://localhost';
	$entrypoints = collect($entrypoints);

	if (is_file(PUBLIC_DIR . '/hot')) {
		$url = rtrim(file_get_contents(PUBLIC_DIR . '/hot'));

        add_action('wp_head', function () use ($url) {
            echo '<script type="module" crossorigin src="' . $url . '/@vite/client"></script>';
		});

		foreach ($entrypoints as $entrypoint) {
			wp_enqueue_script('main_vite', "{$url}/{$entrypoint}", array( 'jquery' ), null, true);
		}
	} else {
		$manifestPath = WP_CONTENT_DIR . '/build/manifest.json';

		if (! isset($manifests[$manifestPath])) {
			if (! is_file($manifestPath)) {
				throw new Exception("Vite manifest not found at: {$manifestPath}");
			}

			$manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true);
		}

		$manifest = $manifests[$manifestPath];

		foreach ($entrypoints as $entrypoint) {
			if (! isset($manifest[$entrypoint])) {
				throw new Exception("Unable to locate file in Vite manifest: {$entrypoint}.");
			}

			wp_enqueue_script('main', $assetsPath . "/{$manifest[$entrypoint]['file']}", array( 'jquery' ), null, true);

			if (isset($manifest[$entrypoint]['css'])) {
				foreach ($manifest[$entrypoint]['css'] as $css) {
					wp_enqueue_style('krik', $assetsPath . "/{$css}", false, null);
				}
			}

			if (isset($manifest[$entrypoint]['imports'])) {
				foreach ($manifest[$entrypoint]['imports'] as $import) {
					if (isset($manifest[$import]['css'])) {
						foreach ($manifest[$import]['css'] as $css) {
							wp_enqueue_style('krik', $assetsPath . "/{$css}", false, null);
						}
					}
				}
			}
		}
	}
};

function krik_enqueue_additional_scripts()
{
	wp_enqueue_script('jquery');
	wp_enqueue_script( 'jquery-ui' , 'https://code.jquery.com/ui/1.13.1/jquery-ui.min.js' );

	wp_deregister_script('wp-embed');
}

function krik_add_type_module_script( $tag, $handle ) {
	$module_scripts = array(
		'main_vite',
		'hmr_vite'
	);

	foreach ($module_scripts as $module_script) {
		if ($module_script === $handle) {
			return str_replace('text/javascript', 'module', $tag);
		}
	}

	return $tag;
}

function krik_defer_scripts( $url ) {
	$defer_scripts = array(
		'jquery/ui/core.min.js',
		'jquery/ui/mouse.min.js',
		'jquery/ui/slider.min.js',
		'jquery/ui/datepicker.min.js',
		'jquery.blockUI.min.js',
		'jquery/ui/slider.min.js'
	);

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

	return $url;
}

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'));
	}
}
