<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

use Breeze_Options_Reader;

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

/**
 * Class Breeze
 *
 * Plugin Name: Breeze
 * Plugin URI: https://pl.wordpress.org/plugins/breeze/
 * Tested versions: 2.2.15
 */
class Breeze extends AbstractPlugin {
	public function init(): void {
		$this->inject_lazyload_fix();
	}

	private function inject_lazyload_fix(): void {

		if ( ! class_exists( '\Breeze_Options_Reader' ) ) {
			return;
		}

		if ( Breeze_Options_Reader::get_option_value( 'breeze-lazy-load' ) !== '1' ) {
			return;
		}

		ob_start();
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				/**
				 * Fix for Breeze plugin lazy loading.
				 * This function initializes Breeze's lazy loading for product images after they are reloaded.
				 */
				function fixBreezeLazyImages() {
					const hasUnloaded = document.querySelectorAll('img.br-lazy:not(.br-loaded)').length > 0;

					if (!hasUnloaded) {
						return;
					}

					new window.LazyLoad({
						elements_selector: ".br-lazy:not(.br-loaded)",
						data_src: "breeze",
						data_srcset: "brsrcset",
						data_sizes: "brsizes"
					});
				}

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