<?php
/**
 * WordPress Default CSS Remover.
 *
 * @package Etch
 * @subpackage Assets
 */

declare(strict_types=1);

namespace Etch\Assets\Styles;

use Etch\Helpers\Flag;

/**
 * Class WpDefaultCssRemover
 *
 * Handles removal of WordPress default CSS styles.
 */
class WpDefaultCssRemover {

	/**
	 * Initialize the CSS remover.
	 *
	 * @return void
	 */
	public function init(): void {
		if ( ! Flag::is_on( 'REMOVE_WP_DEFAULT_CSS' ) ) {
			return;
		}
		$this->remove_wp_default_css();
	}

	/**
	 * Remove WordPress default CSS styles.
	 *
	 * @return void
	 */
	private function remove_wp_default_css(): void {
		// Remove emoji styles and scripts
		add_action( 'wp_print_styles', array( $this, 'remove_emoji_styles' ), 99 );
		add_action( 'wp_print_scripts', array( $this, 'remove_emoji_script' ), 99 );

		// Use output buffering to remove specific inline styles
		add_action( 'wp_head', array( $this, 'start_output_buffering' ), 1 );
		add_action( 'wp_footer', array( $this, 'end_output_buffering' ), 999 );
	}

	/**
	 * Start output buffering to capture and filter HTML.
	 *
	 * @return void
	 */
	public function start_output_buffering(): void {
		ob_start( array( $this, 'filter_output' ) );
	}

	/**
	 * End output buffering.
	 *
	 * @return void
	 */
	public function end_output_buffering(): void {
		if ( ob_get_level() ) {
			ob_end_flush();
		}
	}

	/**
	 * Filter the output to remove specific inline styles.
	 *
	 * @param string $html The HTML output.
	 * @return string
	 */
	public function filter_output( string $html ): string {
		// Remove specific WordPress inline styles
		$patterns = array(
			'/<style[^>]*id=[\'"]wp-emoji-styles-inline-css[\'"][^>]*>.*?<\/style>/s',
			'/<style[^>]*id=[\'"]wp-block-library-inline-css[\'"][^>]*>.*?<\/style>/s',
			'/<style[^>]*id=[\'"]global-styles-inline-css[\'"][^>]*>.*?<\/style>/s',
			'/<style[^>]*id=[\'"]wp-block-template-skip-link-inline-css[\'"][^>]*>.*?<\/style>/s',
		);

		$filtered_html = preg_replace( $patterns, '', $html );

		return $filtered_html ?? $html;
	}

	/**
	 * Remove emoji styles.
	 *
	 * @return void
	 */
	public function remove_emoji_styles(): void {
		wp_dequeue_style( 'wp-emoji-release' );
		remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
		remove_action( 'wp_print_styles', 'print_emoji_styles' );
	}

	/**
	 * Remove emoji script.
	 *
	 * @return void
	 */
	public function remove_emoji_script(): void {
		wp_dequeue_script( 'wp-emoji' );
		remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
		remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
		remove_action( 'wp_print_styles', 'print_emoji_styles' );
		remove_action( 'admin_print_styles', 'print_emoji_styles' );
		remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
		remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
		remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
	}
}
