<?php

namespace Brandy\BlocksOverride\WooCommerce;

use Brandy\Traits\SingletonTrait;
use Brandy\Core\Services\PerformanceService;

/**
 * Override WP latest posts block
 */
class WooCommerceProductImageHoverEffect {
	use SingletonTrait;

	private $enqueued_scripts = false;

	/**
	 * Cached theme mod values to avoid repeated DB queries
	 */
	private static $enable_hover_effect = null;
	private static $hover_effect_type   = null;

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

	public function maybe_enqueue_frontend_scripts() {

		if ( $this->enqueued_scripts ) {
			return;
		}

		$this->enqueued_scripts = true;

		wp_enqueue_script( 'brandy/product-image-hover-effect', BRANDY_TEMPLATE_URL . '/inc/BlocksOverride/Assets/woocommerce-product-image-hover-effect.js', array( 'jquery' ), BRANDY_SCRIPT_VERSION, true );
	}

	public function apply_product_image_hover_effect( $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;
		}

		// Cache theme mod values to avoid repeated DB queries per block
		if ( null === self::$enable_hover_effect ) {
			self::$enable_hover_effect = get_theme_mod( 'enable_product_image_hover_effect', true );
		}
		if ( null === self::$hover_effect_type ) {
			self::$hover_effect_type = get_theme_mod( 'product_image_hover_effect', 'display-secondary-image' );
		}

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

		$product_image_hover_effect = self::$hover_effect_type;

		// Get product ID from context
		$post_id = isset( $block['context']['postId'] ) ? $block['context']['postId'] : get_the_ID();

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

		$product = \wc_get_product( $post_id );

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

		// Get gallery image IDs
		$gallery_image_ids = $product->get_gallery_image_ids();

		if ( ! empty( $gallery_image_ids ) ) {
			// Match the image size from the main product image block
			$image_sizing = $block['attrs']['imageSizing'] ?? 'cropped';
			$image_size   = 'thumbnail' === $image_sizing ? 'woocommerce_thumbnail' : '';

			// Build inline styles to match the main image
			$image_style_parts = array();
			$attrs             = $block['attrs'];

			if ( ! empty( $attrs['height'] ) ) {
				$image_style_parts[] = 'height:' . $attrs['height'];
			}
			if ( ! empty( $attrs['width'] ) ) {
				$image_style_parts[] = 'width:' . $attrs['width'];
			}
			$image_style_parts[] = 'object-fit:' . ( $attrs['scale'] ?? 'cover' );
			if ( ! empty( $attrs['objectPosition'] ) ) {
				$image_style_parts[] = 'object-position:' . \Brandy\BlockSettings\ImageObjectPosition\Caller::get_position_css( $attrs['objectPosition'] );
			}
			if ( ! empty( $attrs['aspectRatio'] ) ) {
				$image_style_parts[] = 'aspect-ratio:' . $attrs['aspectRatio'];
			}
			if ( ! empty( $attrs['style']['dimensions']['aspectRatio'] ) ) {
				$image_style_parts[] = 'aspect-ratio:' . $attrs['style']['dimensions']['aspectRatio'];
			}
			if ( ! empty( $attrs['style']['dimensions']['minHeight'] ) ) {
				$image_style_parts[] = 'min-height:' . $attrs['style']['dimensions']['minHeight'];
			}

			$image_style = ! empty( $image_style_parts ) ? implode( ';', $image_style_parts ) : '';

			$gallery_images_html = '';

			foreach ( $gallery_image_ids as $index => $image_id ) {

				$image_style .= ';opacity:0;';

				if ( 'display-slider' !== $product_image_hover_effect && $index > 0 ) {
					break;
				}

				$image_attrs = array(
					'class'            => 'brandy-slide-image',
					'data-slide-index' => $index + 1,
					'decoding'         => 'async',
				);

				$image_attrs['loading'] = 'lazy';

				if ( ! empty( $image_style ) ) {
					$image_attrs['style'] = $image_style;
				}

				$image                = wp_get_attachment_image(
					$image_id,
					$image_size,
					false,
					$image_attrs
				);
				$gallery_images_html .= $image;
			}

			$tag = new \WP_HTML_Tag_Processor( $html );

			if ( $tag->next_tag() ) {
				$tag_class  = $tag->get_attribute( 'class' );
				$tag_class .= ' brandy-product-image-slideshow ' . ( 'display-secondary-image' === $product_image_hover_effect ? 'brandy-display-secondary-image ' : '' );
				$tag->set_attribute( 'class', $tag_class );
				$html = $tag->get_updated_html();
			}

			// // Insert gallery images after the main image
			$html = preg_replace(
				'/(<img[^>]*data-testid="product-image"[^>]*>)/',
				'$1' . $gallery_images_html . '',
				$html
			);

			$this->maybe_enqueue_frontend_scripts();
		}
		return $html;
	}
}
