<?php
/**
 * SiteOrigin Page Builder widget picker branding for RSM plugins.
 *
 * Applies RSMSpark orange (#FF6B35) to widget icons and optional dialog tab grouping.
 *
 * @package Rsmspark_Suite
 */

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'Rsmspark_Panels_Branding', false ) ) :

/**
 * Rsmspark_Panels_Branding
 */
final class Rsmspark_Panels_Branding {

	/**
	 * Spark logo accent orange.
	 */
	public const BRAND_ORANGE = '#FF6B35';

	/**
	 * @var array<string, array<string, mixed>>
	 */
	private static $registry = array();

	/**
	 * @var bool
	 */
	private static $hooks_registered = false;

	/**
	 * @var bool
	 */
	private static $auto_brand_enabled = false;

	/**
	 * Enable suite-wide orange icons for all RSM SiteOrigin widgets.
	 *
	 * @return void
	 */
	public static function ensure_suite_branding() {
		self::$auto_brand_enabled = true;
		self::ensure_hooks();
		self::bust_widget_cache();
	}

	/**
	 * Register SiteOrigin picker branding for a plugin's widgets.
	 *
	 * @param array<string, mixed> $config {
	 *     @type string   $group_id          Tab/filter group id.
	 *     @type string   $group_label       Tab label in add-widget dialog.
	 *     @type string[] $widget_classes    PHP class names (RSM_Foo_Widget, etc.).
	 *     @type int      $filter_priority   siteorigin_panels_widgets filter priority.
	 * }
	 * @return void
	 */
	public static function register( array $config ) {
		$group_id = sanitize_key( (string) ( $config['group_id'] ?? '' ) );
		if ( '' === $group_id ) {
			return;
		}

		self::$registry[ $group_id ] = wp_parse_args(
			$config,
			array(
				'group_id'        => $group_id,
				'group_label'     => '',
				'widget_classes'  => array(),
				'filter_priority' => 15,
			)
		);

		self::ensure_hooks();
		self::bust_widget_cache();
	}

	/**
	 * @return void
	 */
	private static function ensure_hooks() {
		if ( self::$hooks_registered ) {
			return;
		}

		self::$hooks_registered = true;
		add_filter( 'siteorigin_panels_widgets', array( __CLASS__, 'brand_widgets' ), 15 );
		add_filter( 'siteorigin_panels_widget_dialog_tabs', array( __CLASS__, 'register_tabs' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_styles' ) );
	}

	/**
	 * @return void
	 */
	private static function bust_widget_cache() {
		delete_transient( 'siteorigin_panels_widgets' );
	}

	/**
	 * @param array<string, mixed> $widgets Panels widgets.
	 * @return array<string, mixed>
	 */
	public static function brand_widgets( $widgets ) {
		if ( ! is_array( $widgets ) ) {
			return $widgets;
		}

		foreach ( self::$registry as $group ) {
			$classes  = is_array( $group['widget_classes'] ?? null ) ? $group['widget_classes'] : array();
			$group_id = sanitize_key( (string) ( $group['group_id'] ?? '' ) );

			foreach ( $classes as $class ) {
				$class = (string) $class;
				if ( ! isset( $widgets[ $class ] ) || ! is_array( $widgets[ $class ] ) ) {
					continue;
				}

				self::apply_brand( $widgets, $class, $group_id );
			}
		}

		if ( self::$auto_brand_enabled ) {
			foreach ( $widgets as $class => $widget ) {
				$class = (string) $class;
				if ( ! is_array( $widget ) || ! self::is_rsm_widget( $class, $widget ) ) {
					continue;
				}

				self::apply_brand( $widgets, $class, '' );
			}
		}

		return $widgets;
	}

	/**
	 * @param array<string, mixed> $widgets   Widget list (by reference).
	 * @param string               $class     Widget PHP class.
	 * @param string               $group_id  Optional dialog tab group.
	 * @return void
	 */
	private static function apply_brand( array &$widgets, $class, $group_id ) {
		$icon = (string) ( $widgets[ $class ]['icon'] ?? 'dashicons dashicons-admin-generic' );
		if ( false === strpos( $icon, 'rsm-panels-icon' ) ) {
			$widgets[ $class ]['icon'] = 'rsm-panels-icon ' . $icon;
		}

		if ( '' === $group_id ) {
			return;
		}

		$groups = is_array( $widgets[ $class ]['groups'] ?? null ) ? $widgets[ $class ]['groups'] : array();
		if ( ! in_array( $group_id, $groups, true ) ) {
			$groups[] = $group_id;
		}
		$widgets[ $class ]['groups'] = $groups;
	}

	/**
	 * @param string               $class  Widget PHP class.
	 * @param array<string, mixed> $widget Widget metadata.
	 * @return bool
	 */
	private static function is_rsm_widget( $class, array $widget ) {
		if ( preg_match( '/(?:^|\\\\)RSM[_\\\\]/', (string) $class ) ) {
			return true;
		}

		$title = (string) ( $widget['title'] ?? '' );
		if ( '' === $title ) {
			return false;
		}

		return (bool) preg_match( '/^RSM(?:\s|:|$)/i', $title ) || 0 === stripos( $title, 'RSMMenu' );
	}

	/**
	 * @param array<string, mixed> $tabs Dialog tabs.
	 * @return array<string, mixed>
	 */
	public static function register_tabs( $tabs ) {
		if ( ! is_array( $tabs ) ) {
			$tabs = array();
		}

		foreach ( self::$registry as $group ) {
			$group_id = sanitize_key( (string) ( $group['group_id'] ?? '' ) );
			if ( '' === $group_id ) {
				continue;
			}
			$tabs[ $group_id ] = array(
				'title'  => (string) ( $group['group_label'] ?? $group_id ),
				'filter' => array(
					'groups' => array( $group_id ),
				),
			);
		}

		return $tabs;
	}

	/**
	 * @param string $hook Admin hook.
	 * @return void
	 */
	public static function enqueue_styles( $hook ) {
		if ( ! in_array( $hook, array( 'post.php', 'post-new.php', 'widgets.php' ), true ) ) {
			return;
		}

		if ( ! self::$hooks_registered ) {
			return;
		}

		$css = sprintf(
			':root{--rsm-brand-orange:%1$s;}
			.so-panels-dialog .rsm-panels-icon::before,
			.so-panels-dialog .widget-icon.rsm-panels-icon::before,
			.so-panels-dialog .widget-icon.rsm-panels-icon,
			.so-available-widgets-list .rsm-panels-icon::before,
			.so-available-widgets-list .widget-icon.rsm-panels-icon::before,
			#so-panels-add-widgets-dialog .rsm-panels-icon::before,
			#so-panels-add-widgets-dialog .widget-icon.rsm-panels-icon::before,
			.so-panels-add-widget-dialog .rsm-panels-icon::before,
			.so-panels-add-widget-dialog .widget-icon.rsm-panels-icon::before,
			.so-panels-dialog .rsm-cw-panels-icon::before,
			.so-panels-dialog .widget-icon.rsm-cw-panels-icon::before,
			.so-available-widgets-list .rsm-cw-panels-icon::before,
			#so-panels-add-widgets-dialog .rsm-cw-panels-icon::before,
			.so-panels-add-widget-dialog .rsm-cw-panels-icon::before,
			.so-panels-dialog .widget[class*="RSM_"] .widget-icon,
			.so-panels-dialog .widget[class*="RSM_"] .widget-icon::before,
			.so-available-widgets-list .widget[class*="RSM_"] .widget-icon::before{color:var(--rsm-brand-orange)!important;}
			.rsm-license-tier-label{display:inline-block;margin-left:6px;padding:1px 6px;font-size:11px;font-weight:600;text-transform:uppercase;color:#fff;background:%1$s;border-radius:3px;vertical-align:middle;}',
			esc_attr( self::BRAND_ORANGE )
		);

		wp_register_style( 'rsm-panels-branding', false, array(), RSMSPARK_SUITE_VERSION );
		wp_enqueue_style( 'rsm-panels-branding' );
		wp_add_inline_style( 'rsm-panels-branding', $css );
	}
}

endif;

if ( class_exists( 'Rsmspark_Panels_Branding', false ) && ! class_exists( 'RSM_Panels_Branding', false ) ) {
	class_alias( 'Rsmspark_Panels_Branding', 'RSM_Panels_Branding' );
}
