<?php

namespace Brandy\BlocksOverride\WooCommerce;

use Brandy\Traits\SingletonTrait;

/**
 * Override WooCommerce product image zoom.
 *
 * When global zoom is enabled and a product image block has no per-block
 * hover animation set, inject HoverAnimation classes as a fallback.
 * Per-block hoverAnimation always takes priority.
 */
class WooCommerceProductImageHoverZoom {
	use SingletonTrait;

	/**
	 * Cached theme mod value to avoid repeated DB queries
	 */
	private static $enable_zoom = null;

	protected function __construct() {
		add_filter( 'render_block_woocommerce/product-image', array( $this, 'apply_product_image_hover_zoom' ), 10, 3 );
	}

	public function apply_product_image_hover_zoom( $html, $block, $instance ) {

		$is_inside_product_template = ! empty( $instance->context['postId'] )
			&& ! empty( $instance->context['query']['postType'] )
			&& 'product' === $instance->context['query']['postType'];

		if ( ! $is_inside_product_template ) {
			return $html;
		}

		if ( null === self::$enable_zoom ) {
			self::$enable_zoom = get_theme_mod( 'enable_product_image_hover_zoom', true );
		}

		if ( ! self::$enable_zoom ) {
			return $html;
		}

		// Skip if block already has per-block hover animation (HoverAnimation/Caller.php runs first)
		if ( str_contains( $html, 'has-hover-animation' ) || str_contains( $html, 'has-hover-child-animation' ) ) {
			return $html;
		}

		// Inject HoverAnimation classes as global fallback
		$tag = new \WP_HTML_Tag_Processor( $html );

		if ( $tag->next_tag() ) {
			$existing_class = $tag->get_attribute( 'class' ) ?? '';
			$zoom_classes   = 'has-hover-animation has-hover-image-zoom has-hover-level-medium';
			$tag->set_attribute( 'class', trim( $existing_class . ' ' . $zoom_classes ) );
			$html = $tag->get_updated_html();

			// Ensure HoverAnimation stylesheet is loaded
			\Brandy\BlockSettings\HoverAnimation\Caller::get_instance()->maybe_enqueue_frontend_styles();
		}

		return $html;
	}
}
