<?php
/**
 * Queue inline script variables for admin screens (printed via wp_add_inline_script).
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Admin;

defined( 'ABSPATH' ) || exit;

final class View_Inline_Assets {

	/** @var array<int, array{global: string, data: array<string, mixed>}> */
	private static array $vars = array();

	public static function register(): void {
		add_action( 'admin_print_footer_scripts', array( __CLASS__, 'flush' ), 5 );
	}

	/**
	 * @param string               $global_name JavaScript global (e.g. SUITEMKT3K_NEWSLETTER_STATE).
	 * @param array<string, mixed> $data        Data encoded with wp_json_encode().
	 */
	public static function script_var( string $global_name, array $data ): void {
		$global = preg_replace( '/[^A-Za-z0-9_]/', '', $global_name );
		if ( '' === $global ) {
			return;
		}

		// Attach as soon as the view renders (after admin_enqueue_scripts) so the
		// variable exists before suitemkt3k-admin.js boots Alpine on DOMContentLoaded.
		if ( wp_script_is( 'suitemkt3k-admin', 'enqueued' ) || wp_script_is( 'suitemkt3k-admin', 'done' ) ) {
			self::print_var( $global, $data );
			return;
		}

		self::$vars[] = array(
			'global' => $global,
			'data'   => $data,
		);
	}

	/**
	 * @param string               $global
	 * @param array<string, mixed> $data
	 */
	private static function print_var( string $global, array $data ): void {
		wp_add_inline_script(
			'suitemkt3k-admin',
			'window.' . $global . ' = ' . wp_json_encode( $data ) . ';',
			'before'
		);
	}

	public static function flush(): void {
		if ( empty( self::$vars ) ) {
			return;
		}
		if ( ! wp_script_is( 'suitemkt3k-admin', 'enqueued' ) && ! wp_script_is( 'suitemkt3k-admin', 'done' ) ) {
			self::$vars = array();
			return;
		}
		foreach ( self::$vars as $item ) {
			if ( '' === $item['global'] ) {
				continue;
			}
			self::print_var( $item['global'], $item['data'] );
		}
		self::$vars = array();
	}
}
