<?php

namespace EasyCriticalCSS;

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

class Compatibility_EWWW extends Compatibility {
	public static function init() {
		self::add_conditional_action( [ __CLASS__, 'is_ewww_lazy_active' ], 'wp_head', [ __CLASS__, 'apply_lazy_load_fix' ], 0 );
	}

	public static function is_ewww_lazy_active() {
		// Check if EWWW is active.
		if ( ! defined( 'EWWW_IMAGE_OPTIMIZER_VERSION' ) ) {
			return false;
		}

		// Check if the helper function exists.
		if ( ! function_exists( 'ewww_image_optimizer_get_option' ) ) {
			return false;
		}

		// Check EWWW settings for lazy load.
		return (bool) ewww_image_optimizer_get_option( 'ewww_image_optimizer_lazy_load' );
	}

	/**
	 * Apply lazy load compatibility fixes for EWWW Image Optimizer.
	 *
	 * LazySizes detects images but doesn't process them when ECC is active.
	 * This forces lazySizes to check and unveil all lazyload elements after
	 * the page is fully loaded.
	 */
	public static function apply_lazy_load_fix() {
		if ( Critical_CSS::should_skip_critical() ) {
			return;
		}

		$identifier   = Critical_CSS::get_page_identifier();
		$critical_css = Critical_CSS::get_critical_css( $identifier );

		// Only apply if critical CSS contains lazyload opacity rule.
		if ( empty( $critical_css ) || stripos( $critical_css, '.lazyload' ) === false ) {
			return;
		}

		// Force lazySizes to check all elements after page load.
		?>
		<script>
		window.addEventListener('load', function() {
			if (window.lazySizes && window.lazySizes.loader) {
				setTimeout(function() {
					var lazyElements = document.querySelectorAll('.lazyload');
					lazyElements.forEach(function(el) {
						if (window.lazySizes.loader.unveil) {
							window.lazySizes.loader.unveil(el);
						}
					});
				}, 100);
			}
		});
		</script>
		<?php
	}
}
