<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Image_Size;
use Elementor\Utils;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Image_Controls;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Help_Controls;
use Sifency\Classes\Sifency_Addons_Widget_Base;

class Sifency_Widget_Animated_Image extends Sifency_Addons_Widget_Base {

	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Image_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-addons-animated-image',
			'title'          => 'Sifency Animated Image',
			'icon'           => 'eicon-image-bold',
			'category'       => 'sifency-creative-widgets',
			'style_depends'  => array( 'sifency-typo-style', 'sifency-frontend-style' ),
			'script_depends' => array( 'three-js', 'gsap', 'hover-effect', 'sifency-image-fx-handler-script', 'html2canvas' ),
		);
	}

	// =========================================================================
	// CONTROLS
	// =========================================================================

	protected function register_controls() {

		// ── Animation & Content ───────────────────────────────────────────────
		$this->start_controls_section(
			'section_content',
			array(
				'label' => 'Animation & Content',
			)
		);

		$this->add_control(
			'anim_type',
			array(
				'label'        => 'Animation Style',
				'type'         => Controls_Manager::SELECT,
				'default'      => 'liquid',
				'options'      => array(
					'none'   => 'None (Standard)',
					'liquid' => 'Liquid Distortion (WebGL)',
					'tilt'   => 'Futuristic 3D Tilt',
					'glitch' => 'RGB Glitch Shift',
				),
				'prefix_class' => 'sifency-fx-type-',
			)
		);

		$this->add_control(
			'image_1',
			array(
				'label'   => 'Primary Image',
				'type'    => Controls_Manager::MEDIA,
				'default' => array( 'url' => Utils::get_placeholder_image_src() ),
			)
		);

		$this->add_control(
			'image_2',
			array(
				'label'       => 'Secondary Image (Hover)',
				'type'        => Controls_Manager::MEDIA,
				'description' => 'Used for Liquid transition. If empty, Primary image is used.',
				'condition'   => array( 'anim_type' => 'liquid' ),
			)
		);

		$this->add_control(
			'disp_map',
			array(
				'label'     => 'Displacement Map',
				'type'      => Controls_Manager::SELECT,
				'default'   => 'fluid',
				'options'   => array(
					'fluid'   => 'Fluid Waves',
					'clouds'  => 'Cloudy Texture',
					'stripes' => 'Diagonal Stripes',
					'dots'    => 'Digital Dots',
				),
				'condition' => array( 'anim_type' => 'liquid' ),
			)
		);

		$this->add_control(
			'intensity',
			array(
				'label'     => 'Effect Intensity',
				'type'      => Controls_Manager::SLIDER,
				'default'   => array( 'size' => 0.2 ),
				'range'     => array(
					'px' => array(
						'min'  => 0,
						'max'  => 2,
						'step' => 0.01,
					),
				),
				'condition' => array( 'anim_type' => array( 'liquid', 'glitch' ) ),
			)
		);

		$this->end_controls_section();

		$this->add_sifency_addons_help_controls();

		// ── Style Sections ────────────────────────────────────────────────────
		$this->add_sifency_addons_image_style_controls(
			array(
				'selector' => '.sifency-fx-container',
			)
		);

		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'caption_style',
				'label'      => 'Caption Style',
				'selector'   => '.sifency-image-caption',
				'color_only' => true,
				'exclude'    => array( 'tabs', 'transition', 'radius', 'bg', 'shadow' ),
			)
		);

		$this->add_Sifency_Addons_Animation_Controls();
	}

	// =========================================================================
	// PRIVATE HELPERS
	// =========================================================================

	/**
	 * Resolves an Elementor media-field array to a usable URL.
	 *
	 * Priority:
	 *   1. wp_get_attachment_url( $id ) — always current-site correct; survives XML / OCDI import.
	 *   2. Stored URL                   — last resort; may be stale after import.
	 *
	 * @param  array $media_field  e.g. $settings['image_1'] = ['id' => 12, 'url' => '...']
	 * @return string               Resolved URL or empty string.
	 */
	private function resolve_media_url( array $media_field ): string {
		$id  = ! empty( $media_field['id'] ) ? (int) $media_field['id'] : 0;
		$url = ! empty( $media_field['url'] ) ? $media_field['url'] : '';

		if ( $id > 0 ) {
			$resolved = wp_get_attachment_url( $id );
			if ( ! empty( $resolved ) ) {
				return $resolved;
			}
		}

		return $url;
	}

	// =========================================================================
	// RENDER
	// =========================================================================

	protected function render_dom( array $context ): void {
		$settings   = $this->get_settings_for_display();
		$wrapper_id = esc_attr( $context['dom_id'] );

		$img1 = $this->resolve_media_url( $settings['image_1'] ?? array() );

		// Early exit: no primary image.
		if ( empty( $img1 ) ) {
			return;
		}

		// Secondary image — falls back to primary when empty (liquid hover).
		$img2_field = $settings['image_2'] ?? array();
		$img2       = ! empty( $img2_field['id'] ) || ! empty( $img2_field['url'] )
			? $this->resolve_media_url( $img2_field )
			: $img1;

		// img2 may still be empty if field was blank and resolve returned ''.
		if ( empty( $img2 ) ) {
			$img2 = $img1;
		}

		// ── Displacement map URL (bundled asset, not user upload) ─────────────
		$map_url = SIFENCY_ADDONS_URL . 'assets/images/displacement/' . esc_attr( $settings['disp_map'] ?? 'fluid' ) . '.jpg';

		// ── Caption ───────────────────────────────────────────────────────────
		$caption_text   = '';
		$caption_source = $settings['caption_source'] ?? '';

		if ( 'attachment' === $caption_source ) {
			$img1_id      = ! empty( $settings['image_1']['id'] ) ? (int) $settings['image_1']['id'] : 0;
			$caption_text = $img1_id ? (string) wp_get_attachment_caption( $img1_id ) : '';
		} elseif ( 'custom' === $caption_source ) {
			$caption_text = $settings['caption'] ?? '';
		}

		$has_caption = ! empty( $caption_text );

		// ── Link ──────────────────────────────────────────────────────────────
		$link     = $settings['link'] ?? array();
		$has_link = ! empty( $link['url'] );
		if ( $has_link ) {
			$this->add_link_attributes( 'link_tag', $link );
		}

		$link_tag = $has_link ? 'a' : 'div';
		$html_tag = $has_caption ? 'figure' : 'div';

		// ── Animation wrapper ─────────────────────────────────────────────────
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );
		$wrapper_attrs     = $animation_manager->get_wrapper_attributes( array( 'sifency-image-fx-wrapper' ) );

		// ── FX container data-attributes ──────────────────────────────────────
		$this->add_render_attribute(
			'fx_container',
			array(
				'class'          => 'sifency-fx-container',
				'data-anim-type' => $settings['anim_type'] ?? 'liquid',
				'data-img1'      => esc_url( $img1 ),
				'data-img2'      => esc_url( $img2 ),
				'data-disp'      => esc_url( $map_url ),
				'data-intensity' => $settings['intensity']['size'] ?? 0.2,
			)
		);
		?>
		<<?php echo tag_escape( $html_tag ); ?>
		<?php
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- pre-escaped by animation manager
			echo wp_kses_post( $wrapper_attrs );
		?>
		>

			<<?php echo tag_escape( $link_tag ); ?>
			<?php
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor link attributes
				echo wp_kses_post( $this->get_render_attribute_string( 'link_tag' ) );
			?>
			>
				<div 
				<?php
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor render attributes
					echo wp_kses_post( $this->get_render_attribute_string( 'fx_container' ) );
				?>
				>
					<?php if ( 'none' === ( $settings['anim_type'] ?? '' ) ) : ?>
						<img src="<?php echo esc_url( $img1 ); ?>"
							 alt="<?php echo esc_attr( \Elementor\Control_Media::get_image_alt( $settings['image_1'] ) ); ?>">
					<?php endif; ?>
				</div>
			</<?php echo tag_escape( $link_tag ); ?>>

			<?php if ( $has_caption ) : ?>
				<figcaption class="sifency-image-caption sifency-caption-style">
					<?php echo wp_kses_post( $caption_text ); ?>
				</figcaption>
			<?php endif; ?>

		</<?php echo tag_escape( $html_tag ); ?>>
		<?php
	}
}
