<?php

declare( strict_types=1 );

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

/*
 * ╭────────╮
 * | Colors |
 * ╰────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		wp_add_inline_style(
			'fibofilters',
			'body {
				--fibofilters--colors--base: var( --wp--preset--color--virtue-primary, var( --fibofilters--colors--base-org ) );
				--fibofilters--colors--link: var( --wp--preset--color--virtue-primary, var( --fibofilters--colors--link-org ) );
			}'
		);
	}
);

/**
 * ╭───────────────────╮
 * | Products per page |
 * ╰───────────────────╯
 * Appearance -> Theme Options -> Shop Settings -> Shop Archive Page Settings -> How many products per page
 */
add_filter(
	'fibofilters/config/products_per_page',
	function ( $per_page ): int {
		if ( function_exists( 'virtue_products_per_page' ) ) {
			$per_page = intval( virtue_products_per_page() );
		}

		return $per_page;
	}
);

/**
 * ╭─────────────────────╮
 * | Product placeholder |
 * ╰─────────────────────╯
 */
add_filter(
	'fibofilters/request/html/product_placeholder',
	function () {
		$classes = [];
		if ( function_exists( 'virtue_add_product_loop_classes' ) ) {
			$classes = virtue_add_product_loop_classes();
		}
		ob_start();
		?>
		<div class="fibofilters-product-placeholder <?php echo esc_attr( implode( ' ', $classes ) ); ?>">
			<img src="<?php echo esc_url( wc_placeholder_img_src() ); ?> " alt="Placeholder image"/>
		</div>
		<?php
		return (string) ob_get_clean();
	}
);

add_action(
	'wp_enqueue_scripts',
	function () {
		// Custom CSS.
		ob_start();
		?>
		<style>
			.fibofilters-block__items-list li {
				border-bottom: none !important;
				line-height: inherit !important;
			}
		</style>
		<?php
		$css = ob_get_clean();

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

		// Custom JS.
		ob_start();
		/**
		 * Theme uses Masonry for product layout: https://masonry.desandro.com/
		 * After filtering products, we need to reload Masonry layout including appended products.
		 */
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				function fibofiltersVirtueFix() {
					if (typeof jQuery === 'undefined') {
						return;
					}
					const virtueProductWrapper = jQuery('#product_wrapper');
					if (typeof virtueProductWrapper.data('masonry') === 'undefined') {
						return;
					}
					virtueProductWrapper.data('masonry').options.transitionDuration = '0';
					virtueProductWrapper.imagesLoaded().progress(function () {
						virtueProductWrapper.masonry('reloadItems').masonry('layout');
					});
				}

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