<?php
/**
 * CSS generator for the Image block's <img> element.
 *
 * The image block targets two separate elements:
 *   - <figure class="uniqueClass"> — handled by axcelersblocks_generate_block_styles()
 *   - <figure class="uniqueClass"> img — handled here
 *
 * @package AxcelersBlocks
 */

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

if ( ! function_exists( 'axcelersblocks_image_build_sizes' ) ) {
	/**
	 * Build an accurate `sizes` attribute from the block's width constraints.
	 *
	 * WordPress' default `sizes` assumes the image fills the content width, so a
	 * constrained image still makes the browser pick an oversized srcset candidate.
	 * When the block caps the image to a fixed px width/max-width at the largest
	 * (desktop) breakpoint, we emit `(max-width: Wpx) 100vw, Wpx` — the same shape
	 * WordPress core uses — so the browser never downloads wider than W.
	 *
	 * Non-px units (%, vw, em, auto) can't be expressed as a fixed hint, so those
	 * fall back to WordPress' default sizes (this returns '').
	 *
	 * @param array $attributes Full block attributes.
	 * @return string A `sizes` value, or '' to leave WordPress' default in place.
	 */
	function axcelersblocks_image_build_sizes( array $attributes ): string {
		// Most specific → least specific width source for the displayed <img>.
		foreach ( [ 'imgWidth', 'imgMaxWidth', 'width', 'maxWidth' ] as $key ) {
			$value = $attributes[ $key ]['desktop'] ?? '';
			if ( is_string( $value ) && preg_match( '/^\s*(\d+(?:\.\d+)?)px\s*$/', $value, $m ) ) {
				$w = (int) round( (float) $m[1] );
				if ( $w > 0 ) {
					return sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $w );
				}
			}
		}
		return '';
	}
}

if ( ! function_exists( 'axcelersblocks_image_generate_img_css' ) ) {
	/**
	 * Generate responsive CSS rules for the <img> element inside an image block.
	 *
	 * Handles: object-fit, object-position, width, height, min/max dimensions, border-radius.
	 *
	 * @param string $unique_class Block-scoped unique class.
	 * @param array  $devices      Device map from axcelersblocks_get_responsive_devices().
	 * @param array  $attributes   Full block attributes.
	 * @return string[] CSS rule strings.
	 */
	function axcelersblocks_image_generate_img_css( string $unique_class, array $devices, array $attributes ): array {
		// Match the shared CSS generator's mobile-first compatibility behavior:
		// old/default data that only has a desktop value must still emit a base
		// rule so it applies below the first min-width breakpoint.
		$has_css_v = function ( $v ) use ( &$has_css_v ) {
			if ( is_bool( $v ) || is_null( $v ) ) { return false; }
			if ( is_string( $v ) ) { return '' !== $v; }
			if ( is_array( $v ) ) {
				foreach ( $v as $item ) {
					if ( $has_css_v( $item ) ) { return true; }
				}
			}
			return false;
		};

		foreach ( $attributes as &$attribute_value ) {
			if ( ! is_array( $attribute_value ) ) { continue; }
			$has_desktop = isset( $attribute_value['desktop'] ) && $has_css_v( $attribute_value['desktop'] );
			$has_tablet  = isset( $attribute_value['tablet'] ) && $has_css_v( $attribute_value['tablet'] );
			$has_mobile  = isset( $attribute_value['mobile'] ) && $has_css_v( $attribute_value['mobile'] );
			if ( $has_desktop && ! $has_mobile ) {
				$attribute_value['mobile'] = $attribute_value['desktop'];
			}
			if ( $has_tablet && ! $has_desktop ) {
				$attribute_value['desktop'] = $attribute_value['tablet'];
				if ( ! $has_mobile ) {
					$attribute_value['mobile'] = $attribute_value['tablet'];
				}
			}
		}
		unset( $attribute_value );

		$styles_css = [];
		$cascade    = [];
		$selector   = '.' . sanitize_html_class( $unique_class ) . ' img';

		// Simple responsive attribute → CSS property map.
		$props = [
			'object-fit'      => 'imgObjectFit',
			'object-position' => 'imgObjectPosition',
			'width'           => 'imgWidth',
			'height'          => 'imgHeight',
			'min-width'       => 'imgMinWidth',
			'min-height'      => 'imgMinHeight',
			'max-width'       => 'imgMaxWidth',
			'max-height'      => 'imgMaxHeight',
			'border-radius'   => 'imgBorderRadius',
		];

		foreach ( $devices as $device => $config ) {
			$rules = [];

			foreach ( $props as $css_prop => $attr_key ) {
				$val = axcelersblocks_sanitize_css_value( $attributes[ $attr_key ][ $device ] ?? '' );
				if ( $val === '' ) {
					continue;
				}
				// Cascade deduplication: skip identical values on tablet/desktop.
				if ( $device !== 'mobile' && isset( $cascade[ $css_prop ] ) && $cascade[ $css_prop ] === $val ) {
					continue;
				}
				$cascade[ $css_prop ] = $val;
				$rules[]              = "$css_prop: $val;";
			}

			if ( empty( $rules ) ) {
				continue;
			}

			$css            = implode( ' ', $rules );
			$styles_css[]   = empty( $config['media'] )
				? "$selector { $css }"
				: "{$config['media']} { $selector { $css } }";
		}

		return $styles_css;
	}
}
