<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;


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

final class IconListWidget extends WidgetBase {
	public function get_type(): string { return 'icon_list'; }
	public function get_title(): string { return 'Lista de ícones'; }
	public function get_icon(): string { return 'icon_list'; }

	public function get_defaults(): array {
		return array(
			// JSON: [{icon, text}] or legacy "✓ Item" lines
			'items' => Json::encode(
				array(
					array( 'icon' => '✓', 'text' => 'Item um' ),
					array( 'icon' => '✓', 'text' => 'Item dois' ),
					array( 'icon' => '✓', 'text' => 'Item três' ),
				)
			),
			'align' => 'left',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$align = in_array( ( $settings['align'] ?? '' ), array( 'left', 'center', 'right' ), true )
			? (string) $settings['align']
			: 'left';
		return array(
			'items' => $this->sanitize_items( (string) ( $settings['items'] ?? '' ) ),
			'align' => $align,
		);
	}

	private function sanitize_items( string $raw ): string {
		$items = self::parse_items( $raw );
		$clean = array();
		foreach ( $items as $it ) {
			// Keep emoji icons — sanitize_text_field can mangle some UTF-8 on older WP.
			$icon = Json::repair_stripped_unicode( wp_strip_all_tags( (string) ( $it['icon'] ?? '✓' ) ) );
			$text = Json::repair_stripped_unicode( sanitize_text_field( (string) ( $it['text'] ?? '' ) ) );
			if ( mb_strlen( $icon ) > 16 ) {
				$icon = mb_substr( $icon, 0, 16 );
			}
			$clean[] = array(
				'icon' => $icon !== '' ? $icon : '✓',
				'text' => $text,
			);
		}
		if ( count( $clean ) > 50 ) {
			$clean = array_slice( $clean, 0, 50 );
		}
		$json = Json::encode( $clean );
		return is_string( $json ) ? $json : '[]';
	}

	/**
	 * @return list<array{icon:string,text:string}>
	 */
	public static function parse_items( string $raw ): array {
		$raw = trim( $raw );
		if ( $raw === '' ) {
			return array();
		}
		$raw = Json::repair_stripped_unicode( $raw );
		if ( str_starts_with( $raw, '[' ) ) {
			$decoded = json_decode( $raw, true );
			if ( is_array( $decoded ) ) {
				$out = array();
				foreach ( $decoded as $row ) {
					if ( is_string( $row ) ) {
						$row = trim( $row );
						if ( $row === '' ) {
							continue;
						}
						// "✓ text" or "icon|text"
						if ( str_contains( $row, '|' ) ) {
							$p = explode( '|', $row, 2 );
							$out[] = array(
								'icon' => Json::repair_stripped_unicode( trim( $p[0] ) ),
								'text' => Json::repair_stripped_unicode( trim( $p[1] ?? '' ) ),
							);
						} else {
							// First char as icon if emoji/symbol, rest as text
							$chars = preg_split( '//u', $row, -1, PREG_SPLIT_NO_EMPTY ) ?: array();
							$icon  = $chars[0] ?? '✓';
							$text  = trim( mb_substr( $row, mb_strlen( $icon ) ) );
							$out[] = array(
								'icon' => Json::repair_stripped_unicode( $icon ),
								'text' => Json::repair_stripped_unicode( $text !== '' ? $text : $row ),
							);
						}
						continue;
					}
					if ( is_array( $row ) ) {
						$out[] = array(
							'icon' => Json::repair_stripped_unicode( (string) ( $row['icon'] ?? '✓' ) ),
							'text' => Json::repair_stripped_unicode( (string) ( $row['text'] ?? $row['label'] ?? '' ) ),
						);
					}
				}
				return $out;
			}
		}
		$out   = array();
		$lines = preg_split( '/\r\n|\r|\n/', $raw ) ?: array();
		foreach ( $lines as $line ) {
			$line = trim( $line );
			if ( $line === '' ) {
				continue;
			}
			if ( str_contains( $line, '|' ) ) {
				$p = explode( '|', $line, 2 );
				$out[] = array( 'icon' => trim( $p[0] ), 'text' => trim( $p[1] ?? '' ) );
			} else {
				$chars = preg_split( '//u', $line, -1, PREG_SPLIT_NO_EMPTY ) ?: array();
				$icon  = $chars[0] ?? '✓';
				$text  = trim( mb_substr( $line, mb_strlen( $icon ) ) );
				$out[] = array( 'icon' => $icon, 'text' => $text !== '' ? $text : $line );
			}
		}
		return $out;
	}

	public function render( Node $node, array $context = array() ): string {
		$items = self::parse_items( (string) ( $node->settings['items'] ?? '' ) );
		$align = esc_attr( (string) ( $node->settings['align'] ?? 'left' ) );
		if ( ! $items ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-icon-list ab-empty">Lista de ícones — adicione itens</div>'
				: '';
		}
		$html = '<ul class="ab-icon-list" style="text-align:' . $align . '">';
		foreach ( $items as $it ) {
			$text = (string) ( $it['text'] ?? '' );
			$icon = (string) ( $it['icon'] ?? '✓' );
			if ( $text === '' && $icon === '' ) {
				continue;
			}
			$html .= '<li class="ab-icon-list__item">'
				. '<span class="ab-icon-list__icon" aria-hidden="true">' . esc_html( $icon ) . '</span>'
				. '<span class="ab-icon-list__text">' . esc_html( $text ) . '</span>'
				. '</li>';
		}
		$html .= '</ul>';
		return $html;
	}
}
