<?php
/**
 * Image Floating Effect — float, tilt, pulse, rotate animations.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class ImageFloatWidget extends WidgetBase {

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

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

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

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

	public function get_defaults(): array {
		return array(
			'image'           => '',
			'alt'             => '',
			'effect'          => 'float',
			'height'          => '320',
			'radius'          => '16',
			'shadow'          => '1',
			'object_position' => '50% 50%',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$effect = sanitize_key( (string) ( $settings['effect'] ?? 'float' ) );
		if ( ! in_array( $effect, array( 'float', 'tilt', 'pulse', 'rotate', 'bob' ), true ) ) {
			$effect = 'float';
		}
		$flag = static function ( $v, string $d = '1' ): string {
			if ( $v === null || $v === '' ) {
				return $d;
			}
			return ( $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes' ) ? '1' : '0';
		};
		return array(
			'image'           => esc_url_raw( (string) ( $settings['image'] ?? '' ) ),
			'alt'             => sanitize_text_field( (string) ( $settings['alt'] ?? '' ) ),
			'effect'          => $effect,
			'height'          => (string) max( 80, min( 800, (int) ( $settings['height'] ?? 320 ) ) ),
			'radius'          => (string) max( 0, min( 80, (int) ( $settings['radius'] ?? 16 ) ) ),
			'shadow'          => $flag( $settings['shadow'] ?? null, '1' ),
			'object_position' => self::sanitize_object_position( $settings['object_position'] ?? '50% 50%' ),
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$s      = $node->settings;
		$img    = (string) ( $s['image'] ?? '' );
		$alt    = (string) ( $s['alt'] ?? '' );
		$effect = esc_attr( (string) ( $s['effect'] ?? 'float' ) );
		$height = (int) ( $s['height'] ?? 320 );
		$radius = (int) ( $s['radius'] ?? 16 );
		$shadow = ( $s['shadow'] ?? '1' ) === '1' ? ' has-shadow' : '';
		$pos    = esc_attr( self::sanitize_object_position( $s['object_position'] ?? '50% 50%' ) );

		if ( $img === '' ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-img-float ab-empty">Imagem flutuante — escolha uma imagem</div>'
				: '';
		}

		return '<div class="ab-img-float ab-img-float--' . $effect . $shadow . '" style="--ab-if-h:' . esc_attr( (string) $height ) . 'px;--ab-if-r:' . esc_attr( (string) $radius ) . 'px;--ab-if-pos:' . $pos . '">'
			. '<img src="' . esc_url( $img ) . '" alt="' . esc_attr( $alt ) . '" loading="lazy" style="object-fit:cover;object-position:' . $pos . '"/>'
			. '</div>';
	}
}
