<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Perfmatters
 *
 * Plugin Name: Perfmatters
 * Plugin URI: https://perfmatters.io/
 * Tested versions: 2.3.2
 */
class Perfmatters extends AbstractPlugin {
	public function init(): void {
		add_filter( 'perfmatters_defer_js_exclusions', [ $this, 'add_defer_js_exclusions' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_perfmatters_lazyload_fix_script' ] );
	}

	/**
	 * Add excluded from Deferral
	 *
	 * @param array $assets data.
	 */
	public function add_defer_js_exclusions( $assets ): array {
		if ( is_array( $assets ) ) {
			$assets[] = '/fibofilters-pro/';
			$assets[] = 'fiboFiltersData';
			$assets[] = 'fibofilters-data';
		}

		return $assets;
	}

	public function enqueue_perfmatters_lazyload_fix_script() {
		ob_start();
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				function fibofiltersPerfmattersFix() {
					if (typeof LazyLoad === 'undefined') {
						return;
					}
					if (typeof window.lazyLoadInstance === 'undefined') {
						window.lazyLoadInstance = new LazyLoad({
							elements_selector: ".perfmatters-lazy"
						});
					} else if (typeof window.lazyLoadInstance === 'object' && typeof window.lazyLoadInstance.update === 'function') {
						window.lazyLoadInstance.update();
					}
				}

				fiboFilters.hooks.addAction('fiboFilters.renderer.products_loaded', 'fibofilters', fibofiltersPerfmattersFix);
				fiboFilters.hooks.addAction('fiboFilters.renderer.product_placeholders_overwritten', 'fibofilters', fibofiltersPerfmattersFix);
			}
		</script>
		<?php
		$this->enqueue_inline_script( (string) ob_get_clean() );
	}
}
