<?php
/**
 * Embedded media (YouTube, X/Twitter, generic oEmbed).
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class EmbedWidget extends WidgetBase {

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

	public function get_title(): string {
		return 'Mídia incorporada';
	}

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

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

	public function get_defaults(): array {
		return array(
			'provider' => 'youtube',
			'url'      => '',
			'align'    => 'center',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$provider = sanitize_key( (string) ( $settings['provider'] ?? 'youtube' ) );
		if ( ! in_array( $provider, array( 'youtube', 'x', 'oembed', 'html' ), true ) ) {
			$provider = 'youtube';
		}
		$align = (string) ( $settings['align'] ?? 'center' );
		if ( ! in_array( $align, array( 'left', 'center', 'right' ), true ) ) {
			$align = 'center';
		}
		$url = esc_url_raw( (string) ( $settings['url'] ?? '' ) );
		return array(
			'provider' => $provider,
			'url'      => $url,
			'align'    => $align,
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$s        = $node->settings;
		$provider = (string) ( $s['provider'] ?? 'youtube' );
		$url      = (string) ( $s['url'] ?? '' );
		$align    = esc_attr( (string) ( $s['align'] ?? 'center' ) );
		$editor   = ! empty( $context['editor'] );

		if ( $url === '' ) {
			$label = $provider === 'youtube' ? 'YouTube' : ( $provider === 'x' ? 'X / Twitter' : 'Mídia' );
			return $editor
				? '<div class="ab-embed ab-embed--empty" style="text-align:' . $align . '">Cole a URL do ' . esc_html( $label ) . '</div>'
				: '';
		}

		$html = '';
		if ( $provider === 'youtube' ) {
			$html = $this->youtube_iframe( $url );
		} elseif ( $provider === 'x' ) {
			$html = $this->x_embed( $url, $editor );
		} else {
			$html = $this->oembed( $url, $editor );
		}

		if ( $html === '' ) {
			return $editor
				? '<div class="ab-embed ab-embed--empty" style="text-align:' . $align . '"><a href="' . esc_url( $url ) . '" target="_blank" rel="noopener">' . esc_html( $url ) . '</a></div>'
				: '<div class="ab-embed" style="text-align:' . $align . '"><a href="' . esc_url( $url ) . '" target="_blank" rel="noopener">' . esc_html( $url ) . '</a></div>';
		}

		return '<div class="ab-embed ab-embed--' . esc_attr( $provider ) . '" style="text-align:' . $align . '">' . $html . '</div>';
	}

	private function youtube_iframe( string $url ): string {
		$id = $this->youtube_id( $url );
		if ( $id === '' ) {
			return '';
		}
		$src = 'https://www.youtube.com/embed/' . rawurlencode( $id );
		return '<div class="ab-embed-responsive"><iframe src="' . esc_url( $src ) . '" title="YouTube" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen loading="lazy"></iframe></div>';
	}

	private function youtube_id( string $url ): string {
		if ( preg_match( '~(?:youtu\.be/|youtube\.com/(?:watch\?v=|embed/|shorts/|live/))([A-Za-z0-9_-]{6,})~', $url, $m ) ) {
			return $m[1];
		}
		return '';
	}

	private function x_embed( string $url, bool $editor ): string {
		// Prefer WP oEmbed for twitter/x.com
		$o = $this->oembed( $url, $editor );
		if ( $o !== '' ) {
			return $o;
		}
		return '<blockquote class="twitter-tweet"><a href="' . esc_url( $url ) . '">' . esc_html( $url ) . '</a></blockquote>';
	}

	private function oembed( string $url, bool $editor ): string {
		if ( function_exists( 'wp_oembed_get' ) ) {
			$html = wp_oembed_get( $url, array( 'width' => 720 ) );
			if ( is_string( $html ) && $html !== '' ) {
				return $html;
			}
		}
		global $wp_embed;
		if ( $wp_embed instanceof \WP_Embed ) {
			$auto = $wp_embed->shortcode( array(), $url );
			if ( is_string( $auto ) && $auto !== '' && $auto !== $url ) {
				return $auto;
			}
		}
		return '';
	}
}
