<?php
/**
 * Body profile helpers — sanitize and render rich HTML for Features, Tabs, Accordion, etc.
 *
 * @package Rsmspark_Editor
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Rich_Text_Body
 */
final class Rsmspark_Rich_Text_Body {

	/**
	 * @return array<string, array<string, bool>>
	 */
	public static function allowed_html() {
		$tags = Rsmspark_Rich_Text_Registry::allowed_tags( Rsmspark_Rich_Text_Registry::PROFILE_BODY );

		/**
		 * Filter wp_kses allowlist for body profile front-end output.
		 *
		 * @param array<string, array<string, bool>> $tags Allowed tags.
		 */
		return apply_filters( 'rsmspark_rich_text_body_allowed_html', $tags );
	}

	/**
	 * @param mixed $html Raw HTML.
	 * @return string
	 */
	public static function sanitize( $html ) {
		if ( ! class_exists( 'Rsmspark_Rich_Text', false ) ) {
			return wp_kses_post( (string) $html );
		}

		return Rsmspark_Rich_Text::sanitize( $html, Rsmspark_Rich_Text_Registry::PROFILE_BODY );
	}

	/**
	 * Expand shortcodes and apply body allowlist (chip bodies, tab panels, etc.).
	 *
	 * @param string $html Sanitized body HTML.
	 * @return string
	 */
	public static function render( $html ) {
		$html = (string) $html;
		if ( '' === trim( $html ) ) {
			return '';
		}

		$html = shortcode_unautop( $html );
		$html = do_shortcode( $html );

		return wp_kses( $html, self::allowed_html() );
	}

	/**
	 * Whether sanitized body HTML has visible text.
	 *
	 * @param string $html HTML.
	 * @return bool
	 */
	public static function has_text( $html ) {
		if ( class_exists( 'Rsmspark_Rich_Text', false ) ) {
			return Rsmspark_Rich_Text::has_text( $html );
		}

		return '' !== trim( wp_strip_all_tags( (string) $html ) );
	}
}
