<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class TextWidget extends WidgetBase {

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

	public function get_title(): string {
		return 'Texto';
	}

	public function get_icon(): string {
		return 'align-left';
	}

	public function get_defaults(): array {
		return array(
			'text'  => 'Escreva seu texto aqui.',
			'align' => 'left',
		);
	}

	public function get_controls(): array {
		return array(
			array( 'type' => 'textarea', 'name' => 'text', 'label' => 'Texto' ),
			array(
				'type'    => 'select',
				'name'    => 'align',
				'label'   => 'Alinhamento',
				'options' => array(
					array( 'value' => 'left', 'label' => 'Esquerda' ),
					array( 'value' => 'center', 'label' => 'Centro' ),
					array( 'value' => 'right', 'label' => 'Direita' ),
				),
			),
		);
	}

	public function sanitize_settings( array $settings ): array {
		$align = isset( $settings['align'] ) ? (string) $settings['align'] : 'left';
		if ( ! in_array( $align, array( 'left', 'center', 'right', 'justify' ), true ) ) {
			$align = 'left';
		}
		$text = (string) ( $settings['text'] ?? '' );
		// Import leftovers sometimes store raw CSS as "text".
		if ( \AuraBuilder\Support\Assets::looks_like_css_blob( wp_strip_all_tags( $text ) ) ) {
			$text = '';
		} else {
			$text = wp_kses_post( $text );
			$text = \AuraBuilder\Support\Assets::strip_orphaned_css_blobs( $text );
		}
		$out = array(
			'text'  => $text,
			'align' => $align,
		);
		if ( isset( $settings['display_name'] ) && is_string( $settings['display_name'] ) && $settings['display_name'] !== '' ) {
			$out['display_name'] = sanitize_text_field( $settings['display_name'] );
		}
		return $out;
	}

	public function render( Node $node, array $context = array() ): string {
		$s     = $node->settings;
		$align = (string) ( $s['align'] ?? 'left' );
		if ( ! in_array( $align, array( 'left', 'center', 'right', 'justify' ), true ) ) {
			$align = 'left';
		}
		$text = (string) ( $s['text'] ?? '' );
		if ( \AuraBuilder\Support\Assets::looks_like_css_blob( wp_strip_all_tags( $text ) ) ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-text ab-empty">CSS importado (oculto no site)</div>'
				: '';
		}
		$text = wp_kses_post( $text );
		$text = \AuraBuilder\Support\Assets::strip_orphaned_css_blobs( $text );
		if ( $text === '' ) {
			return '';
		}
		$attr = $this->leaf_style_attr( $node, array( 'text-align:' . $align ) );
		return '<div class="ab-text"' . $attr . '>' . $text . '</div>';
	}
}
