<?php
declare( strict_types=1 );

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

/**
 * ╭────────────────────────────────────────────────╮
 * | Filters position when Products element is used |
 * ╰────────────────────────────────────────────────╯
 * This snippet will close the .bricks-before-shop-loop div and open a new one for filters before the shop loop.
 * When custom loop is used this hook won't be triggered.
 */
add_action(
	'woocommerce_before_shop_loop',
	function () {
		if ( ! did_action( 'bricks/archive_product/before' ) ) {
			echo '</div><div>';
		}
	},
	490
);

/*
 * ╭────────────╮
 * | Custom CSS |
 * ╰────────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		ob_start();
		?>
		<style>
			[class^="brxe-fibofilters-"], [class*=" brxe-fibofilters-"] {
				width: 100%;
			}

			.woocommerce .fibofilters-show-more-button-container .button,
			.woocommerce .fibofilters-show-previous-button-container .button {
				align-self: auto;
			}
		</style>
		<?php
		$css = ob_get_clean();

		wp_add_inline_style(
			'fibofilters',
			str_replace( [ '<style>', '</style>' ], '', $css )
		);
	}
);

/**
 * ╭───────────────────────────────────────────────────╮
 * | Reinit lazy load shop images and AJAX add to cart |
 * ╰───────────────────────────────────────────────────╯
 * Bricks >> Settings >> Performance >> Disable lazy loading (default: checkbox disabled)
 * Bricks >> Settings >> WooCommerce >> Enable AJAX add to cart (default: checkbox disabled)
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		ob_start();
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				function fibofiltersBricksFix() {
					if (typeof bricksLazyLoad === 'function') {
						bricksLazyLoad();
					}

					if (bricksWooCommerce?.ajaxAddToCartEnabled === '1' && typeof bricksWooAjaxAddToCartFn.run === 'function') {
						bricksWooAjaxAddToCartFn.run();
					}

					if (bricksWooCommerce?.ajaxAddToCartEnabled === '1'
						&& typeof bricksWooQuantityTriggersFn?.run === 'function'
						&& typeof bricksWooLoopQtyListenerFn?.run === 'function') {
						bricksWooQuantityTriggersFn.run();
						bricksWooLoopQtyListenerFn.run();
					}
				}

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