<?php
/**
 * Script module registration - Auto-generated by build process.
 * Do not edit this file manually.
 *
 * @package jetpack_newsletter
 */

/**
 * Register all script modules.
 */
function jetpack_newsletter_register_script_modules() {
	// Ensure this only runs once. wp_default_scripts can fire multiple times,
	// and each wp_deregister_script_module() call also dequeues the module.
	// If a module was enqueued between calls, repeated deregister/register
	// cycles would lose the enqueue state.
	static $already_registered = false;
	if ( $already_registered ) {
		return;
	}
	$already_registered = true;

	// Load build constants
	$constants_file = __DIR__ . '/constants.php';
	if ( ! file_exists( $constants_file ) ) {
		return;
	}
	$build_constants = require $constants_file;
	$modules_dir     = __DIR__ . '/modules';
	$modules_file    = $modules_dir . '/registry.php';

	if ( ! file_exists( $modules_file ) ) {
		return;
	}

	$modules = require $modules_file;
	$base_url = $build_constants['build_url'] . 'modules/';

	foreach ( $modules as $module ) {
		// WASM-only modules (e.g., vips worker) only have .min.js; use it even when SCRIPT_DEBUG is `true`.
		$extension = '.min.js';

		$asset_path = $modules_dir . '/' . $module['asset'];
		$asset = file_exists( $asset_path ) ? require $asset_path : array();

		// Deregister first to override any previously registered version
		// (e.g., Core's default modules when running as a plugin).
		wp_deregister_script_module( $module['id'] );

		wp_register_script_module(
			$module['id'],
			$base_url . $module['path'] . $extension,
			$asset['module_dependencies'] ?? array(),
			$asset['version'] ?? false,
			array(
				'fetchpriority' => 'low',
				'in_footer'     => true,
			)
		);
	}
}

add_action( 'wp_default_scripts', 'jetpack_newsletter_register_script_modules' );
