<?php
/**
 * Inline Admin Assets Helper
 *
 * @package AmbassadorHub\Admin
 */

namespace AmbassadorHub\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Shared handle for attaching inline admin CSS/JS through the WordPress
 * enqueue system, instead of echoing raw <style>/<script> tags.
 *
 * Several admin screens across the plugin need a small, page-specific
 * <style> or <script> block (a metabox tweak, a conditional layout rule for
 * one settings tab, etc.) that isn't worth its own asset file. Rather than
 * echoing markup directly, they register/enqueue this shared no-op handle
 * and attach their CSS/JS to it via wp_add_inline_style()/wp_add_inline_script() —
 * the WordPress-recommended path for exactly this case (see the "Inline
 * JS"/"Inline CSS" rows in the enqueue documentation).
 *
 * Usage from any admin render callback:
 *
 *   InlineAssets::style( '.ambh-widget { margin-top: 0; }' );
 *   InlineAssets::script( 'console.log("ready");' );
 */
final class InlineAssets {

	/** Shared style handle. Registered with no src (false). */
	private const STYLE_HANDLE = 'ambh-admin-inline';

	/** Shared script handle. Registered with no src (false). */
	private const SCRIPT_HANDLE = 'ambh-admin-inline';

	/** @var bool Whether the shared style handle has been registered this request. */
	private static bool $style_registered = false;

	/** @var bool Whether the shared script handle has been registered this request. */
	private static bool $script_registered = false;

	/**
	 * Attach an inline CSS block to the shared admin style handle.
	 *
	 * Safe to call from any admin render callback, including ones that run
	 * after admin_enqueue_scripts (e.g. inside a metabox or settings tab
	 * render() method) — registration and enqueueing happen lazily on first
	 * use within the current request.
	 *
	 * @param string $css Raw CSS (no <style> tags).
	 *
	 * @return void
	 */
	public static function style( string $css ): void {
		if ( ! $css ) {
			return;
		}

		if ( ! self::$style_registered ) {
			wp_register_style( self::STYLE_HANDLE, false, array(), AMBASSADOR_HUB_VERSION );
			self::$style_registered = true;
		}

		wp_enqueue_style( self::STYLE_HANDLE );
		wp_add_inline_style( self::STYLE_HANDLE, $css );
	}

	/**
	 * Attach an inline JS block to the shared admin script handle.
	 *
	 * Safe to call from any admin render callback for the same reason as
	 * style() above.
	 *
	 * @param string $js  Raw JS (no <script> tags).
	 * @param string $position 'after' (default) or 'before' the handle's own output.
	 *
	 * @return void
	 */
	public static function script( string $js, string $position = 'after' ): void {
		if ( ! $js ) {
			return;
		}

		if ( ! self::$script_registered ) {
			wp_register_script( self::SCRIPT_HANDLE, false, array(), AMBASSADOR_HUB_VERSION, true );
			self::$script_registered = true;
		}

		wp_enqueue_script( self::SCRIPT_HANDLE );
		wp_add_inline_script( self::SCRIPT_HANDLE, $js, $position );
	}
}
