<?php
/**
 * Frontend cleanup optimizer.
 *
 * Removes unnecessary CSS and JS loaded on the frontend for
 * non-logged-in users, including Dashicons (~46KB) and
 * WordPress block library CSS when not using blocks.
 *
 * @package MonitorCat\Modules\Speed\Optimizer
 */

declare(strict_types=1);

namespace MonitorCat\Modules\Speed\Optimizer;

defined( 'ABSPATH' ) || exit;

use MonitorCat\Settings;

/**
 * Removes unnecessary frontend assets for non-logged-in users.
 */
final class FrontendCleanupOptimizer {

	/**
	 * Plugin settings.
	 *
	 * @var Settings
	 */
	private Settings $settings;

	/**
	 * Constructor.
	 *
	 * @param Settings $settings Plugin settings.
	 */
	public function __construct( Settings $settings ) {
		$this->settings = $settings;
	}

	/**
	 * Register hooks if the optimization is enabled.
	 */
	public function boot(): void {
		if ( ! $this->settings->get( 'speed.optimize_frontend_cleanup', true ) ) {
			return;
		}

		if ( is_admin() ) {
			return;
		}

		add_action( 'wp_enqueue_scripts', array( $this, 'cleanup_frontend_assets' ), 999 );
	}

	/**
	 * Remove unnecessary assets for non-logged-in visitors.
	 */
	public function cleanup_frontend_assets(): void {
		// Only for non-logged-in users — admins may need Dashicons for the toolbar.
		if ( is_user_logged_in() ) {
			return;
		}

		// Remove Dashicons CSS (~46KB) — only needed for admin bar.
		wp_deregister_style( 'dashicons' );

		// Remove WordPress global styles inline CSS if not needed.
		wp_dequeue_style( 'global-styles' );

		// Remove classic theme styles (loaded by default in WP 6.1+).
		wp_dequeue_style( 'classic-theme-styles' );
	}
}
