<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class VideoWidget extends WidgetBase {
	public function get_type(): string { return 'video'; }
	public function get_title(): string { return 'Vídeo'; }
	public function get_icon(): string { return 'video'; }
	public function get_defaults(): array {
		return array( 'url' => '', 'align' => 'center', 'autoplay' => '0' );
	}
	public function sanitize_settings( array $settings ): array {
		$align = in_array( ( $settings['align'] ?? '' ), array( 'left', 'center', 'right' ), true ) ? (string) $settings['align'] : 'center';
		return array(
			'url'      => esc_url_raw( (string) ( $settings['url'] ?? '' ) ),
			'align'    => $align,
			'autoplay' => empty( $settings['autoplay'] ) || $settings['autoplay'] === '0' ? '0' : '1',
		);
	}
	public function render( Node $node, array $context = array() ): string {
		$url   = (string) ( $node->settings['url'] ?? '' );
		$align = esc_attr( (string) ( $node->settings['align'] ?? 'center' ) );
		if ( $url === '' ) {
			return ! empty( $context['editor'] ) ? '<div class="ab-video ab-empty">Vídeo — cole a URL (YouTube/Vimeo/MP4)</div>' : '';
		}
		if ( preg_match( '~(?:youtu\.be/|youtube\.com/(?:watch\?v=|embed/|shorts/))([A-Za-z0-9_-]{6,})~', $url, $m ) ) {
			$src = 'https://www.youtube.com/embed/' . rawurlencode( $m[1] );
			if ( ( $node->settings['autoplay'] ?? '0' ) === '1' ) {
				$src .= '?autoplay=1&mute=1';
			}
			return '<div class="ab-video" style="text-align:' . $align . '"><div class="ab-embed-responsive"><iframe src="' . esc_url( $src ) . '" title="Video" allowfullscreen loading="lazy"></iframe></div></div>';
		}
		if ( preg_match( '~vimeo\.com/(?:video/)?(\d+)~', $url, $m ) ) {
			$src = 'https://player.vimeo.com/video/' . rawurlencode( $m[1] );
			return '<div class="ab-video" style="text-align:' . $align . '"><div class="ab-embed-responsive"><iframe src="' . esc_url( $src ) . '" title="Vimeo" allowfullscreen loading="lazy"></iframe></div></div>';
		}
		if ( preg_match( '/\.(mp4|webm|ogg)(\?|$)/i', $url ) ) {
			$auto = ( $node->settings['autoplay'] ?? '0' ) === '1' ? ' autoplay muted playsinline' : '';
			return '<div class="ab-video" style="text-align:' . $align . '"><video class="ab-video-el" src="' . esc_url( $url ) . '" controls' . $auto . '></video></div>';
		}
		return '<div class="ab-video" style="text-align:' . $align . '"><a href="' . esc_url( $url ) . '" target="_blank" rel="noopener">' . esc_html( $url ) . '</a></div>';
	}
}
