<?php
declare( strict_types=1 );

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

add_action(
	'wp_enqueue_scripts',
	function () {
		wp_add_inline_style(
			'fibofilters',
			'body {
				--fibofilters--colors--base: var( --global-palette1, var( --fibofilters--colors--base-org ) );
				--fibofilters--colors--link: var( --global-palette-highlight, var( --fibofilters--colors--link-org ) );
			}'
		);
	}
);

/**
 * Fix for Kadence badges.
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		if ( ! post_type_exists( 'kt_woo_badge' ) ) {
			return;
		}
		ob_start();
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				function fibofiltersKadenceBadgesFix() {
					if (typeof window.KTBadgeAdminInstance !== 'undefined' && typeof window.KTBadgeAdminInstance.initBadges === 'function') {
						window.KTBadgeAdminInstance.initBadges();
					}
				}

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

/*
 * ╭─────────────────────────────────────╮
 * | Fix for Kadence Woo Extras swatches |
 * ╰─────────────────────────────────────╯
 * Shop Kit -> Product Variations -> Variation Swatches
 * Minimum Kadence Woo Extras version: v2.4.10
 */
add_action(
	'template_redirect',
	function () {
		global $kt_woo_extras;

		if ( empty( $kt_woo_extras['variation_swatches'] ) || empty( $kt_woo_extras['variation_archive_swatches'] ) ) {
			return;
		}

		add_filter( 'fibofilters/config/early_products_caching', '__return_true' );

		add_action(
			'wp_enqueue_scripts',
			function () {
				ob_start();
				?>
			<script>
				console.log('Kadence Swatches Fix');
				if (typeof fiboFilters !== 'undefined') {
					function fibofiltersKadenceSwatchesFix() {
						if (typeof window.kadence_woo_extras_init_catalog_swatches === 'function' && typeof jQuery !== 'undefined') {
							jQuery(".variations_form:not(.variation-initialized)").each(
								function () {
									jQuery(this).wc_variation_form();
								}
							);
							window.kadence_woo_extras_init_catalog_swatches();
						}
					}

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