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

use Sifency\Classes\Sifency_Addons_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Box_Shadow;
use Sifency\Traits\Sifency_Addons_Help_Controls;

class Sifency_Addons_Widget_Video_Avatar 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-video-avatar',
			'title'          => 'Sifency Video Avatar',
			'icon'           => 'eicon-video-camera',
			'category'       => array( 'sifency-business-widgets' ),
			'script_depends' => array( 'gsap', 'sifency-video-avatar-script' ),
			'style_depends'  => array( 'sifency-business-style' ),
			'keywords'       => array( 'video', 'avatar', 'floating', 'chatbot', 'intro', 'welcome' ),
		);
	}

	// ─────────────────────────────────────────────────────────────
	// CONTROLS
	// ─────────────────────────────────────────────────────────────
	protected function register_controls() {

		/*
		 ══════════════════════════════════════════
		   1. VIDEO CONTENT
		══════════════════════════════════════════ */
		$this->start_controls_section(
			'section_video',
			array( 'label' => esc_html__( 'Video Content', 'sifency-addons' ) )
		);

		// Video source type
		$this->add_control(
			'video_source',
			array(
				'label'   => esc_html__( 'Video Source', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'self_hosted',
				'options' => array(
					'self_hosted' => esc_html__( 'Self-Hosted (MP4)', 'sifency-addons' ),
					'youtube'     => esc_html__( 'YouTube', 'sifency-addons' ),
					'vimeo'       => esc_html__( 'Vimeo', 'sifency-addons' ),
				),
			)
		);

		// Self-hosted URL
		$this->add_control(
			'video_url',
			array(
				'label'       => esc_html__( 'MP4 Video URL', 'sifency-addons' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => 'https://your-site.com/intro.mp4',
				'description' => esc_html__( 'Vertical (9:16) videos work best.', 'sifency-addons' ),
				'condition'   => array( 'video_source' => 'self_hosted' ),
			)
		);

		// YouTube URL
		$this->add_control(
			'video_url_youtube',
			array(
				'label'       => esc_html__( 'YouTube URL', 'sifency-addons' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => 'https://www.youtube.com/watch?v=XXXXXXX',
				'condition'   => array( 'video_source' => 'youtube' ),
			)
		);

		// Vimeo URL
		$this->add_control(
			'video_url_vimeo',
			array(
				'label'       => esc_html__( 'Vimeo URL', 'sifency-addons' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => 'https://vimeo.com/XXXXXXX',
				'condition'   => array( 'video_source' => 'vimeo' ),
			)
		);

		// Fallback poster (self-hosted only)
		$this->add_control(
			'video_poster',
			array(
				'label'       => esc_html__( 'Fallback Poster Image', 'sifency-addons' ),
				'type'        => Controls_Manager::MEDIA,
				'description' => esc_html__( 'Shown while video is loading (self-hosted only).', 'sifency-addons' ),
				'condition'   => array( 'video_source' => 'self_hosted' ),
			)
		);

		$this->end_controls_section();

		/*
		 ══════════════════════════════════════════
		   2. CHAT BUBBLE MESSAGE
		══════════════════════════════════════════ */
		$this->start_controls_section(
			'section_chat_bubble',
			array( 'label' => esc_html__( 'Chat Bubble Message', 'sifency-addons' ) )
		);

		$this->add_control(
			'show_bubble',
			array(
				'label'        => esc_html__( 'Show Message Bubble', 'sifency-addons' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'sifency-addons' ),
				'label_off'    => esc_html__( 'Hide', 'sifency-addons' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'bubble_title',
			array(
				'label'     => esc_html__( 'Greeting Title', 'sifency-addons' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => esc_html__( 'Hey there! 👋', 'sifency-addons' ),
				'condition' => array( 'show_bubble' => 'yes' ),
			)
		);

		$this->add_control(
			'bubble_text',
			array(
				'label'     => esc_html__( 'Message', 'sifency-addons' ),
				'type'      => Controls_Manager::TEXTAREA,
				'default'   => esc_html__( 'I have a quick message for you. Tap to listen!', 'sifency-addons' ),
				'condition' => array( 'show_bubble' => 'yes' ),
			)
		);

		$this->add_control(
			'bubble_delay',
			array(
				'label'     => esc_html__( 'Pop-up Delay (Seconds)', 'sifency-addons' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min'  => 0,
						'max'  => 10,
						'step' => 0.5,
					),
				),
				'default'   => array( 'size' => 2 ),
				'condition' => array( 'show_bubble' => 'yes' ),
			)
		);

		$this->end_controls_section();

		/*
		 ══════════════════════════════════════════
		   3. WIDGET SETTINGS
		══════════════════════════════════════════ */
		$this->start_controls_section(
			'section_settings',
			array( 'label' => esc_html__( 'Widget Settings', 'sifency-addons' ) )
		);

		// Default expanded toggle
		$this->add_control(
			'default_expanded',
			array(
				'label'        => esc_html__( 'Start Expanded', 'sifency-addons' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'sifency-addons' ),
				'label_off'    => esc_html__( 'No', 'sifency-addons' ),
				'return_value' => 'yes',
				'default'      => '',
				'description'  => esc_html__( 'Open the video player immediately without needing a tap.', 'sifency-addons' ),
			)
		);

		$this->add_control(
			'position',
			array(
				'label'   => esc_html__( 'Screen Position', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'bottom-right',
				'options' => array(
					'top-left'      => esc_html__( 'Top Left', 'sifency-addons' ),
					'top-center'    => esc_html__( 'Top Center', 'sifency-addons' ),
					'top-right'     => esc_html__( 'Top Right', 'sifency-addons' ),
					'middle-left'   => esc_html__( 'Middle Left', 'sifency-addons' ),
					'middle-center' => esc_html__( 'Middle Center', 'sifency-addons' ),
					'middle-right'  => esc_html__( 'Middle Right', 'sifency-addons' ),
					'bottom-left'   => esc_html__( 'Bottom Left', 'sifency-addons' ),
					'bottom-center' => esc_html__( 'Bottom Center', 'sifency-addons' ),
					'bottom-right'  => esc_html__( 'Bottom Right', 'sifency-addons' ),
					'relative'      => esc_html__( 'Relative (In-Flow)', 'sifency-addons' ),
				),
			)
		);

		$this->add_control(
			'expanded_width',
			array(
				'label'   => esc_html__( 'Expanded Width (px)', 'sifency-addons' ),
				'type'    => Controls_Manager::NUMBER,
				'default' => 300,
			)
		);

		$this->add_control(
			'expanded_height',
			array(
				'label'   => esc_html__( 'Expanded Height (px)', 'sifency-addons' ),
				'type'    => Controls_Manager::NUMBER,
				'default' => 450,
			)
		);

		$this->end_controls_section();

		/*
		 ══════════════════════════════════════════
		   4. STYLE — BUBBLE
		══════════════════════════════════════════ */
		$this->start_controls_section(
			'section_style',
			array(
				'label' => esc_html__( 'Bubble Styling', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'bubble_bg',
			array(
				'label'     => esc_html__( 'Bubble Background', 'sifency-addons' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => array(
					'{{WRAPPER}} .sifency-va-bubble' => 'background-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-bottom-right .sifency-va-bubble::after' => 'border-left-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-bottom-left .sifency-va-bubble::after' => 'border-right-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-top-right .sifency-va-bubble::after' => 'border-left-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-top-left .sifency-va-bubble::after' => 'border-right-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-middle-right .sifency-va-bubble::after' => 'border-left-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-middle-left .sifency-va-bubble::after' => 'border-right-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-bottom-center .sifency-va-bubble::after' => 'border-top-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-top-center .sifency-va-bubble::after' => 'border-bottom-color: {{VALUE}};',
					'{{WRAPPER}} .sifency-pos-middle-center .sifency-va-bubble::after' => 'border-top-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'bubble_text_color',
			array(
				'label'     => esc_html__( 'Text Color', 'sifency-addons' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#111111',
				'selectors' => array( '{{WRAPPER}} .sifency-va-bubble' => 'color: {{VALUE}};' ),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'title_typography',
				'label'    => esc_html__( 'Title Typography', 'sifency-addons' ),
				'selector' => '{{WRAPPER}} .sifency-va-b-title',
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'bubble_shadow',
				'selector' => '{{WRAPPER}} .sifency-va-bubble, {{WRAPPER}} .sifency-va-video-wrap',
			)
		);

		$this->end_controls_section();

		/*
		 ══════════════════════════════════════════
		   5. STYLE — VIDEO OVERLAY
		══════════════════════════════════════════ */
		$this->start_controls_section(
			'section_overlay_style',
			array(
				'label' => esc_html__( 'Video Overlay', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'show_overlay',
			array(
				'label'        => esc_html__( 'Show Overlay', 'sifency-addons' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'sifency-addons' ),
				'label_off'    => esc_html__( 'Hide', 'sifency-addons' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'overlay_color',
			array(
				'label'     => esc_html__( 'Overlay Color', 'sifency-addons' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#000000',
				'condition' => array( 'show_overlay' => 'yes' ),
				'selectors' => array(
					'{{WRAPPER}} .sifency-va-mini-overlay' => '--sifency-va-overlay-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'overlay_opacity',
			array(
				'label'     => esc_html__( 'Overlay Opacity', 'sifency-addons' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min'  => 0,
						'max'  => 1,
						'step' => 0.05,
					),
				),
				'default'   => array( 'size' => 0.6 ),
				'condition' => array( 'show_overlay' => 'yes' ),
				'selectors' => array(
					'{{WRAPPER}} .sifency-va-mini-overlay' => '--sifency-va-overlay-opacity: {{SIZE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	// ─────────────────────────────────────────────────────────────
	// HELPERS
	// ─────────────────────────────────────────────────────────────

	/**
	 * Parse a YouTube or Vimeo URL and return an embed URL ready for iframe src.
	 * Returns empty string on failure.
	 */
	private function get_embed_url( string $raw_url, string $source ): string {
		$url = trim( $raw_url );
		if ( empty( $url ) ) {
			return '';
		}

		if ( 'youtube' === $source ) {
			$id = '';
			if ( preg_match( '#youtu\.be/([^?&]+)#i', $url, $m ) ) {
				$id = $m[1];
			}
			if ( empty( $id ) && preg_match( '#[?&]v=([^&]+)#i', $url, $m ) ) {
				$id = $m[1];
			}
			if ( empty( $id ) && preg_match( '#/embed/([^?&/]+)#i', $url, $m ) ) {
				$id = $m[1];
			}
			if ( empty( $id ) ) {
				return '';
			}
			return 'https://www.youtube.com/embed/' . esc_attr( $id ) . '?autoplay=1&mute=1&loop=1&playlist=' . esc_attr( $id ) . '&controls=0&playsinline=1&rel=0';
		}

		if ( 'vimeo' === $source ) {
			if ( ! preg_match( '#vimeo\.com/(\d+)#i', $url, $m ) ) {
				return '';
			}
			$id = $m[1];
			return 'https://player.vimeo.com/video/' . esc_attr( $id ) . '?autoplay=1&muted=1&loop=1&background=1';
		}

		return '';
	}

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

		$source       = $settings['video_source'] ?? 'self_hosted';
		$show_bubble  = ( 'yes' === ( $settings['show_bubble'] ?? 'yes' ) );
		$show_overlay = ( 'yes' === ( $settings['show_overlay'] ?? 'yes' ) );
		$default_exp  = ( 'yes' === ( $settings['default_expanded'] ?? '' ) );
		$position     = $settings['position'] ?? 'bottom-right';
		$pos_class    = 'sifency-pos-' . $position;

		// ── Build video markup ─────────────────────────────────────
		$video_html = '';

		if ( 'self_hosted' === $source ) {
			$raw_url = $settings['video_url']['url'] ?? '';
			if ( empty( $raw_url ) ) {
				return;
			}
			$poster     = $settings['video_poster']['url'] ?? '';
			$video_html = sprintf(
				'<video class="sifency-va-player" src="%s" poster="%s" autoplay loop muted playsinline></video>',
				esc_url( $raw_url ),
				esc_url( $poster )
			);
		} else {
			$raw_key   = ( 'youtube' === $source ) ? 'video_url_youtube' : 'video_url_vimeo';
			$raw_url   = $settings[ $raw_key ]['url'] ?? '';
			$embed_url = $this->get_embed_url( $raw_url, $source );
			if ( empty( $embed_url ) ) {
				return;
			}
			$video_html = sprintf(
				'<iframe class="sifency-va-player sifency-va-iframe" src="%s" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>',
				esc_url( $embed_url )
			);
		}

		// ── JS config ─────────────────────────────────────────────
		$config = array(
			'delay'      => $settings['bubble_delay']['size'] ?? 2,
			'expW'       => $settings['expanded_width'] ?? 300,
			'expH'       => $settings['expanded_height'] ?? 450,
			'defaultExp' => $default_exp,
			'showBubble' => $show_bubble,
			'source'     => $source,
		);

		// ── Overlay inline style ───────────────────────────────────
		$overlay_style = '';
		if ( $show_overlay ) {
			$overlay_color   = $settings['overlay_color'] ?? '#000000';
			$overlay_opacity = $settings['overlay_opacity']['size'] ?? 0.6;
			$overlay_style   = sprintf(
				'style="background: linear-gradient(to top, %s %s, transparent);"',
				esc_attr( $this->hex_to_rgba( $overlay_color, (float) $overlay_opacity ) ),
				'70%'
			);
		}

		// ── Classes on wrapper ─────────────────────────────────────
		$wrapper_classes = implode(
			' ',
			array_filter(
				array(
					'sifency-video-avatar-wrapper',
					esc_attr( $pos_class ),
					$default_exp ? 'sifency-va-is-expanded' : '',
					! $show_bubble ? 'sifency-va-no-bubble' : '',
				)
			)
		);
		?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>"
			 class="<?php echo esc_attr( $wrapper_classes ); ?>"
			 data-config='<?php echo esc_attr( wp_json_encode( $config ) ); ?>'>

			<?php if ( $show_bubble ) : ?>
			<!-- Chat Bubble -->
			<div class="sifency-va-bubble">
				<span class="sifency-va-bubble-close" aria-label="<?php esc_attr_e( 'Close message', 'sifency-addons' ); ?>">&times;</span>
				<div class="sifency-va-bubble-content">
					<div class="sifency-va-b-title"><?php echo esc_html( $settings['bubble_title'] ); ?></div>
					<div class="sifency-va-b-desc"><?php echo esc_html( $settings['bubble_text'] ); ?></div>
				</div>
			</div>
			<?php endif; ?>

			<!-- Video Container -->
			<div class="sifency-va-video-wrap">
				<div class="sifency-va-close-main" aria-label="<?php esc_attr_e( 'Close video', 'sifency-addons' ); ?>">&times;</div>

				<?php echo wp_kses_post( $video_html ); ?>

				<?php if ( $show_overlay ) : ?>
				<div class="sifency-va-mini-overlay" <?php echo wp_kses_post( $overlay_style ); ?>>
					<span class="sifency-va-tap-text"><?php esc_html_e( 'Tap to unmute', 'sifency-addons' ); ?></span>
				</div>
				<?php endif; ?>
			</div>

		</div>
		<?php
	}

	/**
	 * Convert a hex color + alpha float to rgba() string.
	 */
	private function hex_to_rgba( string $hex, float $alpha ): string {
		$hex = ltrim( $hex, '#' );
		if ( strlen( $hex ) === 3 ) {
			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
		}
		if ( strlen( $hex ) !== 6 ) {
			return 'rgba(0,0,0,' . $alpha . ')';
		}
		$r = hexdec( substr( $hex, 0, 2 ) );
		$g = hexdec( substr( $hex, 2, 2 ) );
		$b = hexdec( substr( $hex, 4, 2 ) );
		return "rgba({$r},{$g},{$b},{$alpha})";
	}
}
