<?php
/**
 * Tiny UI helpers reused across admin views. Keeps markup consistent (color
 * inputs with hex fallback, dropdowns, etc.) and centralised.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Admin;

defined( 'ABSPATH' ) || exit;

final class UI {

	/**
	 * Render a color input: real color picker + manual hex text field.
	 * The two stay in sync via the small inline script declared once per page.
	 *
	 * @param string $name  The form name (also used as id base).
	 * @param string $value Current hex value (#rrggbb).
	 * @param string $extra Extra attributes for the hidden hex input.
	 */
	public static function color_input( string $name, string $value, string $extra = '' ): void {
		$value = self::normalize_hex( $value );
		$uid = 'wmk-color-' . md5( $name . microtime( true ) );
		?>
		<div class="wmk-color" data-wmk-color>
			<label class="wmk-color-swatch" style="--swatch: <?php echo esc_attr( $value ); ?>;">
				<input type="color" value="<?php echo esc_attr( $value ); ?>" data-wmk-color-picker aria-hidden="true" tabindex="-1">
			</label>
			<input class="wmk-input"
				type="text"
				name="<?php echo esc_attr( $name ); ?>"
				id="<?php echo esc_attr( $uid ); ?>"
				value="<?php echo esc_attr( $value ); ?>"
				maxlength="7"
				pattern="^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$"
				data-wmk-color-hex
				<?php echo $extra; // phpcs:ignore WordPress.Security.EscapeOutput ?>>
		</div>
		<?php
	}

	public static function normalize_hex_public( string $value ): string {
		return self::normalize_hex( $value );
	}

	private static function normalize_hex( string $value ): string {
		$value = trim( $value );
		if ( ! preg_match( '/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/', $value ) ) {
			return '#2AB2E5';
		}
		return strtoupper( $value );
	}
}
