<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

use AuraBuilder\Document\Node;
use AuraBuilder\Widgets\WidgetBase;

final class ImageWidget extends WidgetBase {

	public function get_type(): string {
		return 'image';
	}

	public function get_title(): string {
		return 'Imagem';
	}

	public function get_category(): string {
		return 'media';
	}

	public function get_icon(): string {
		return 'image';
	}

	public function get_defaults(): array {
		return array(
			'url'             => '',
			'alt'             => '',
			'align'           => 'center',
			'width'           => '',
			'object_fit'      => 'cover',
			'object_position' => 'center center',
		);
	}

	public function get_controls(): array {
		return array(
			array( 'type' => 'url', 'name' => 'url', 'label' => 'URL da imagem' ),
			array( 'type' => 'text', 'name' => 'alt', 'label' => 'Alt' ),
			array(
				'type'    => 'select',
				'name'    => 'align',
				'label'   => 'Alinhamento do bloco (E/C/D)',
				'options' => array(
					array( 'value' => 'left', 'label' => 'Esquerda' ),
					array( 'value' => 'center', 'label' => 'Centro' ),
					array( 'value' => 'right', 'label' => 'Direita' ),
				),
			),
			array(
				'type'  => 'text',
				'name'  => 'width',
				'label' => 'Largura (ex.: 50%, 320px)',
			),
			array(
				'type'    => 'select',
				'name'    => 'object_fit',
				'label'   => 'Encaixe no quadro',
				'options' => array(
					array( 'value' => 'cover', 'label' => 'Cobrir (recorte)' ),
					array( 'value' => 'contain', 'label' => 'Cabendo inteira' ),
					array( 'value' => 'fill', 'label' => 'Esticar' ),
					array( 'value' => 'none', 'label' => 'Original' ),
				),
			),
			array(
				'type'    => 'select',
				'name'    => 'object_position',
				'label'   => 'Posição no quadro (foco)',
				'options' => array(
					array( 'value' => 'center center', 'label' => 'Centro' ),
					array( 'value' => 'center top', 'label' => 'Topo' ),
					array( 'value' => 'center bottom', 'label' => 'Base' ),
					array( 'value' => 'left center', 'label' => 'Esquerda' ),
					array( 'value' => 'right center', 'label' => 'Direita' ),
					array( 'value' => 'left top', 'label' => 'Canto sup. esquerdo' ),
					array( 'value' => 'right top', 'label' => 'Canto sup. direito' ),
					array( 'value' => 'left bottom', 'label' => 'Canto inf. esquerdo' ),
					array( 'value' => 'right bottom', 'label' => 'Canto inf. direito' ),
				),
			),
		);
	}

	public function sanitize_settings( array $settings ): array {
		$align = isset( $settings['align'] ) ? (string) $settings['align'] : 'center';
		if ( ! in_array( $align, array( 'left', 'center', 'right' ), true ) ) {
			$align = 'center';
		}
		$fit = sanitize_key( (string) ( $settings['object_fit'] ?? 'cover' ) );
		if ( ! in_array( $fit, array( 'contain', 'cover', 'fill', 'none' ), true ) ) {
			$fit = 'cover';
		}
		$pos_raw = strtolower( trim( (string) ( $settings['object_position'] ?? '50% 50%' ) ) );
		$pos_raw = preg_replace( '/\s+/', ' ', $pos_raw ) ?? '50% 50%';
		// Prefer "X% Y%" from focal-point picker; also accept keywords.
		if ( preg_match( '/^(-?\d+(?:\.\d+)?)\s*%?\s+(-?\d+(?:\.\d+)?)\s*%?$/', $pos_raw, $pm ) ) {
			$x = max( 0, min( 100, (float) $pm[1] ) );
			$y = max( 0, min( 100, (float) $pm[2] ) );
			$pos_raw = round( $x ) . '% ' . round( $y ) . '%';
		} else {
			$allowed_pos = array(
				'center center',
				'center top',
				'center bottom',
				'left center',
				'right center',
				'left top',
				'right top',
				'left bottom',
				'right bottom',
				'top',
				'bottom',
				'left',
				'right',
				'center',
			);
			if ( ! in_array( $pos_raw, $allowed_pos, true ) ) {
				$pos_raw = '50% 50%';
			}
			if ( $pos_raw === 'top' || $pos_raw === 'bottom' ) {
				$pos_raw = 'center ' . $pos_raw;
			} elseif ( $pos_raw === 'left' || $pos_raw === 'right' ) {
				$pos_raw = $pos_raw . ' center';
			} elseif ( $pos_raw === 'center' ) {
				$pos_raw = 'center center';
			}
		}
		$width = sanitize_text_field( (string) ( $settings['width'] ?? '' ) );
		if ( $width !== '' && ! preg_match( '/^\d+(\.\d+)?(%|px|rem|em|vw)?$/i', $width ) ) {
			$width = '';
		}
		return array(
			'url'             => esc_url_raw( (string) ( $settings['url'] ?? '' ) ),
			'alt'             => sanitize_text_field( (string) ( $settings['alt'] ?? '' ) ),
			'align'           => $align,
			'width'           => $width,
			'object_fit'      => $fit,
			'object_position' => $pos_raw,
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$s   = $node->settings;
		$url = esc_url( (string) ( $s['url'] ?? '' ) );
		$alt = esc_attr( (string) ( $s['alt'] ?? '' ) );
		if ( $url === '' ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-img-ph">Imagem — defina a URL</div>'
				: '';
		}
		$align = esc_attr( (string) ( $s['align'] ?? 'center' ) );
		$width = (string) ( $s['width'] ?? '' );
		$fit   = sanitize_key( (string) ( $s['object_fit'] ?? 'cover' ) );
		if ( ! in_array( $fit, array( 'contain', 'cover', 'fill', 'none' ), true ) ) {
			$fit = 'cover';
		}
		$pos = (string) ( $s['object_position'] ?? 'center center' );
		if ( $pos === '' ) {
			$pos = 'center center';
		}

		// Fixed height on styles → StyleEngine / .ab-has-h fills the box.
		$desk  = is_array( $node->styles['desktop'] ?? null ) ? $node->styles['desktop'] : array();
		$has_h = false;
		foreach ( array( 'height', 'min_height' ) as $hk ) {
			$hv = isset( $desk[ $hk ] ) ? trim( (string) $desk[ $hk ] ) : '';
			if ( $hv !== '' && $hv !== 'auto' && $hv !== '0' && $hv !== '0px' ) {
				$has_h = true;
				break;
			}
		}

		// Fixed height without explicit fit: cover the frame.
		if ( $has_h && ( $fit === '' || ( empty( $s['object_fit'] ) && $fit === 'contain' ) ) ) {
			$fit = 'cover';
		}

		$img_style = array();
		if ( $has_h ) {
			$img_style[] = 'max-width:100%';
			$img_style[] = 'object-position:' . esc_attr( $pos );
		} else {
			if ( $width !== '' ) {
				$img_style[] = 'width:' . esc_attr( $width );
				$img_style[] = 'max-width:100%';
			} else {
				$img_style[] = 'max-width:100%';
				$img_style[] = 'height:auto';
				$img_style[] = 'width:auto';
			}
			$img_style[] = 'object-fit:' . esc_attr( $fit );
			$img_style[] = 'object-position:' . esc_attr( $pos );
			$img_style[] = 'display:inline-block';
			$img_style[] = 'vertical-align:middle';
		}

		$cls = 'ab-image' . ( $has_h ? ' ab-image--fill' : '' );
		$wrap_style = 'text-align:' . $align . ';--ab-img-pos:' . esc_attr( $pos );
		return '<div class="' . esc_attr( $cls ) . '" style="' . esc_attr( $wrap_style ) . '" data-fit="' . esc_attr( $fit ) . '" data-pos="' . esc_attr( $pos ) . '"><img src="' . $url . '" alt="' . $alt . '" loading="lazy"' . ( $img_style ? ' style="' . esc_attr( implode( ';', $img_style ) ) . '"' : '' ) . '/></div>';
	}
}
