<?php
declare( strict_types=1 );

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

/*
 * ╭───────────────────╮
 * | Products per page |
 * ╰───────────────────╯
 */
add_filter(
	'fibofilters/config/products_per_page',
	function (): int {
		if ( function_exists( 'uncode_wc_shop_per_page' ) ) {
			return (int) uncode_wc_shop_per_page();
		}

		return 10;
	}
);

/**
 * ╭─────────────────╮
 * | Product sorting |
 * ╰─────────────────╯
 */
add_filter( 'fibofilters/config/override_ordering_enabled', '__return_true' );

/**
 * ╭─────────────────────╮
 * | Product placeholder |
 * ╰─────────────────────╯
 */
add_filter(
	'fibofilters/request/html/product_placeholder',
	function () {
		$classes = 'fibofilters-product-placeholder tmb tmb-iso-w4';
		ob_start();
		?>
		<div <?php wc_product_class( $classes ); ?>>
			<div class="t-inside">
				<img src="<?php echo esc_url( wc_placeholder_img_src() ); ?> "
					alt="Placeholder image"/>
			</div>
		</div>
		<?php
		return (string) ob_get_clean();
	}
);

/**
 * ╭────────────────────────────╮
 * | Products fetching strategy |
 * ╰────────────────────────────╯
 */
add_filter( 'fibofilters/config/products_fetching_strategy', fn() => 'page' );

/**
 * ╭────────────╮
 * | Pagination |
 * ╰────────────╯
 */
add_filter(
	'fibofilters/config/pagination_selectors',
	fn() => [ '.row-navigation' ]
);

/*
 * ╭─────────────────╮
 * | Pagination args |
 * ╰─────────────────╯
 */
add_filter(
	'fibofilters/config/pagination_args',
	function ( $args ) {
		return wp_parse_args(
			[
				'wrapper_class' => 'row row-parent limit-width pagination',
				'end_size'      => 1,
				'mid_size'      => 2,
				'prev_text'     => '<i class="fa fa-angle-left"></i>',
				'next_text'     => '<i class="fa fa-angle-right"></i>',
			],
			$args
		);
	}
);

/**
 * ╭────────────╮
 * | Custom CSS |
 * ╰────────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		// Custom CSS.
		ob_start();
		?>
		<style>
			.page-numbers.nav-pagination {
				margin-top: 0px;
			}

			.page-numbers.nav-pagination li {
				display: inline-block;
				width: 35px;
			}

			.page-numbers.nav-pagination li a {
				color: #333333
			}

			.page-numbers.nav-pagination > li span {
				display: block;
				width: 36px;
				height: 36px;
				line-height: 36px;
				margin-top: 4.5px;
				margin-bottom: 4.5px;
				border-radius: 50%;
				font-size: 12px;
				font-weight: 500;
			}

			.page-numbers.current {
				background-color: #eeeeee;
			}

			.page-numbers.nav-pagination > li:first-child:has(a.prev) {
				float: left;
				width: 54px;
			}

			.page-numbers.nav-pagination > li:last-child:has(a.next) {
				float: right;
				width: 54px;
			}

			.page-numbers.nav-pagination > li i {
				display: inline-block;
				font-size: 18px;
				vertical-align: baseline;
				line-height: 45px;
			}

			.fibofilters-filters-widget .fibofilters-item {
				margin-bottom: 0;
			}

			.fibofilters-block ul.fibofilters-block__items-list {
				padding: 0 !important;
			}
		</style>
		<?php
		$css = ob_get_clean();

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

add_action(
	'wp_enqueue_scripts',
	function () {
		// Custom JS.
		ob_start();
		/**
		 * Theme uses Isotope for product layout: https://isotope.metafizzy.co/
		 * After filtering products, we need to reload Isotope layout including appended products.
		 */
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				function fibofiltersThemeFix() {
					if (typeof jQuery === 'undefined') {
						return;
					}

					const themeProductWrapper = jQuery('.isotope-container');
					if (typeof themeProductWrapper.data('isotope') !== 'undefined') {
						themeProductWrapper.isotope('option', {transitionDuration: 1});

						themeProductWrapper.imagesLoaded().progress(function () {
							themeProductWrapper.children().addClass('tmb-iso');
							themeProductWrapper.isotope('reloadItems').isotope('arrange');
							themeProductWrapper.children().find('.t-inside').css('opacity', '1');
							window.dispatchEvent(new Event('resize'));
							window.dispatchEvent(new Event('boxResized'));
						});
					} else {
						window.dispatchEvent(new Event('resize'));
						window.dispatchEvent(new Event('boxResized'));

						if (
							typeof SiteParameters !== 'undefined' &&
							SiteParameters?.dynamic_srcset_active === '1' &&
							typeof UNCODE === 'object' &&
							typeof UNCODE.refresh_dynamic_srcset_size === 'function'
						) {
							UNCODE.refresh_dynamic_srcset_size(false)
						}
					}
				}

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

/**
 * ╭────────────────────────────────╮
 * | Show more button extra classes |
 * ╰────────────────────────────────╯
 */
add_filter(
	'fibofilters/config/show_more_extra_classes',
	function ( $classes ) {
		$classes[] = 'btn';

		return $classes;
	}
);

/*
 * ╭────────╮
 * | Colors |
 * ╰────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {

		$base_color = fibofilters_integration_get_accent_color();

		wp_add_inline_style(
			'fibofilters',
			"body {
				--fibofilters--colors--base: $base_color;
				--fibofilters--colors--link: $base_color;
			}"
		);
	}
);

function fibofilters_integration_get_accent_color(): ?string {
	$base_color = '#006cff';
	if ( ! function_exists( 'ot_options_id' ) ) {
		return $base_color;
	}
	$options   = get_option( ot_options_id() );
	$accent_id = $options['_uncode_accent_color'] ?? null;
	$colors    = $options['_uncode_custom_colors_list'] ?? [];

	if ( ! $accent_id || ! is_array( $colors ) ) {
		return $base_color;
	}

	foreach ( $colors as $color ) {
		if ( ( $color['_uncode_custom_color_unique_id'] ?? '' )
			=== $accent_id
		) {
			return $color['_uncode_custom_color'] ?? $base_color;
		}
	}

	return $base_color;
}
