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

use Sifency\Classes\Sifency_Addons_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Utils;
use Sifency\Traits\Sifency_Addons_Help_Controls;

class Sifency_Liquid_Background extends Sifency_Addons_Widget_Base {
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-liquid-background',
			'title'          => 'Sifency Liquid Distortion',
			'icon'           => 'eicon-image-rollover',
			'category'       => array( 'sifency-creative-widgets' ),
			'script_depends' => array( 'curtains-js', 'sifency-liquid-script' ),
			'style_depends'  => array( 'sifency-master-style' ),
			'keywords'       => array( 'liquid', 'distortion', 'webgl', 'fluid', 'water' ),
		);
	}

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

	protected function register_controls() {

		// ── Liquid Background ─────────────────────────────────────────────────
		$this->start_controls_section(
			'section_content',
			array( 'label' => esc_html__( 'Liquid Background', 'sifency-addons' ) )
		);

		$this->add_control(
			'bg_type',
			array(
				'label'   => esc_html__( 'Background Type', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'image',
				'options' => array(
					'image' => esc_html__( 'Image', 'sifency-addons' ),
					'video' => esc_html__( 'Video', 'sifency-addons' ),
				),
			)
		);

		$this->add_control(
			'bg_image',
			array(
				'label'       => esc_html__( 'Background Image', 'sifency-addons' ),
				'type'        => Controls_Manager::MEDIA,
				'default'     => array( 'url' => Utils::get_placeholder_image_src() ),
				'description' => 'This image will be converted into a liquid surface.',
				'condition'   => array( 'bg_type' => 'image' ),
			)
		);

		$this->add_control(
			'bg_video',
			array(
				'label'       => esc_html__( 'Background Video', 'sifency-addons' ),
				'type'        => Controls_Manager::MEDIA,
				'media_types' => array( 'video' ),
				'description' => 'Upload an MP4/WebM video. Note: Background videos auto-play and are muted by default.',
				'condition'   => array( 'bg_type' => 'video' ),
			)
		);

		$this->add_control(
			'displacement_image',
			array(
				'label'       => esc_html__( 'Displacement Map (Liquid Image)', 'sifency-addons' ),
				'type'        => Controls_Manager::MEDIA,
				'description' => 'Select an image (usually a B&W pattern) to act as the liquid distortion map.',
			)
		);

		$this->add_control(
			'overlay_color',
			array(
				'label'     => esc_html__( 'Overlay Color (Optional)', 'sifency-addons' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => 'rgba(0, 0, 0, 0.3)',
				'selectors' => array(
					'{{WRAPPER}} .sifency-liquid-overlay' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();

		// ── Liquid Physics ────────────────────────────────────────────────────
		$this->start_controls_section(
			'section_physics',
			array( 'label' => esc_html__( 'Liquid Physics', 'sifency-addons' ) )
		);

		$this->add_control(
			'ripple_size',
			array(
				'label'   => esc_html__( 'Ripple Size (Frequency)', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 10,
						'max'  => 100,
						'step' => 1,
					),
				),
				'default' => array( 'size' => 30 ),
			)
		);

		$this->add_control(
			'ripple_speed',
			array(
				'label'   => esc_html__( 'Ripple Speed', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 0.1,
						'max'  => 5,
						'step' => 0.1,
					),
				),
				'default' => array( 'size' => 1.5 ),
			)
		);

		$this->add_control(
			'ripple_intensity',
			array(
				'label'   => esc_html__( 'Distortion Intensity', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 0.01,
						'max'  => 0.5,
						'step' => 0.01,
					),
				),
				'default' => array( 'size' => 0.05 ),
			)
		);

		$this->end_controls_section();

		// ── Container Layout ──────────────────────────────────────────────────
		$this->start_controls_section(
			'section_layout',
			array(
				'label' => esc_html__( 'Container Layout', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_responsive_control(
			'min_height',
			array(
				'label'      => esc_html__( 'Min Height', 'sifency-addons' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'vh', 'px' ),
				'range'      => array(
					'vh' => array(
						'min' => 20,
						'max' => 100,
					),
					'px' => array(
						'min' => 200,
						'max' => 1000,
					),
				),
				'default'    => array(
					'unit' => 'vh',
					'size' => 80,
				),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-liquid-wrapper' => 'min-height: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

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

	/**
	 * Resolves a single Elementor media-field array to a usable URL.
	 *
	 * Resolution 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.
	 *
	 * Note: Group_Control_Image_Size is intentionally skipped here because this
	 * widget passes raw URLs to a WebGL canvas — "full" size is always wanted.
	 *
	 * @param  array $media_field  e.g. $settings['bg_image'] = ['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'] );
		$bg_type    = $settings['bg_type'] ?? 'image';

		// ── Resolve media URLs from attachment IDs ────────────────────────────
		// Done via wp_get_attachment_url() so URLs remain valid after
		// XML / OCDI imports where Elementor re-maps IDs but stored URLs
		// can point to the source site.
		$image_url = $this->resolve_media_url( $settings['bg_image'] ?? array() );
		$video_url = $this->resolve_media_url( $settings['bg_video'] ?? array() );
		$disp_url  = $this->resolve_media_url( $settings['displacement_image'] ?? array() );

		// ── Early-exit guards ─────────────────────────────────────────────────
		if ( 'image' === $bg_type && empty( $image_url ) ) {
			echo '<div class="elementor-alert elementor-alert-warning">'
				. esc_html__( 'Please select a background image.', 'sifency-addons' )
				. '</div>';
			return;
		}

		if ( 'video' === $bg_type && empty( $video_url ) ) {
			echo '<div class="elementor-alert elementor-alert-warning">'
				. esc_html__( 'Please select a background video.', 'sifency-addons' )
				. '</div>';
			return;
		}

		// ── Build config passed to the JS handler ─────────────────────────────
		$config = array(
			'type'             => $bg_type,
			'image'            => $image_url,
			'video'            => $video_url,
			'displacement_url' => $disp_url,
			'size'             => $settings['ripple_size']['size'] ?? 30,
			'speed'            => $settings['ripple_speed']['size'] ?? 1.5,
			'intensity'        => $settings['ripple_intensity']['size'] ?? 0.05,
		);
		?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>"
			class="sifency-liquid-wrapper"
			data-config="<?php echo esc_attr( wp_json_encode( $config ) ); ?>">
			<canvas class="sifency-liquid-canvas"></canvas>
			<div class="sifency-liquid-overlay"></div>
		</div>
		<?php
	}
}
