<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class IconWidget extends WidgetBase {
	public function get_type(): string { return 'icon'; }
	public function get_title(): string { return 'Ícone'; }
	public function get_icon(): string { return 'icon'; }
	public function get_defaults(): array {
		return array( 'icon' => '★', 'size' => '32', 'align' => 'center', 'link' => '' );
	}
	public function sanitize_settings( array $settings ): array {
		$align = in_array( ( $settings['align'] ?? '' ), array( 'left', 'center', 'right' ), true ) ? (string) $settings['align'] : 'center';
		$icon  = (string) ( $settings['icon'] ?? '★' );
		// Allow emoji / short unicode / simple text icon (not HTML).
		$icon = wp_strip_all_tags( $icon );
		if ( mb_strlen( $icon ) > 8 ) {
			$icon = mb_substr( $icon, 0, 8 );
		}
		return array(
			'icon'  => $icon !== '' ? $icon : '★',
			'size'  => (string) max( 12, min( 200, (int) ( $settings['size'] ?? 32 ) ) ),
			'align' => $align,
			'link'  => esc_url_raw( (string) ( $settings['link'] ?? '' ) ),
		);
	}
	public function render( Node $node, array $context = array() ): string {
		$s     = $node->settings;
		$icon  = esc_html( (string) ( $s['icon'] ?? '★' ) );
		$size  = (int) ( $s['size'] ?? 32 );
		$align = esc_attr( (string) ( $s['align'] ?? 'center' ) );
		$inner = '<span class="ab-icon" style="font-size:' . esc_attr( (string) $size ) . 'px;line-height:1">' . $icon . '</span>';
		$link  = (string) ( $s['link'] ?? '' );
		if ( $link !== '' ) {
			$inner = '<a href="' . esc_url( $link ) . '">' . $inner . '</a>';
		}
		return '<div class="ab-icon-wrap" style="text-align:' . $align . '">' . $inner . '</div>';
	}
}
