<?php
/**
 * Tabs — item-by-item title/content (JSON), optional image per panel.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;


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

final class TabsWidget extends WidgetBase {

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

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

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

	public function get_defaults(): array {
		return array(
			'items'           => Json::encode(
				array(
					array( 'title' => 'Aba 1', 'content' => 'Conteúdo da primeira aba.', 'image' => '' ),
					array( 'title' => 'Aba 2', 'content' => 'Conteúdo da segunda aba.', 'image' => '' ),
					array( 'title' => 'Aba 3', 'content' => 'Conteúdo da terceira aba.', 'image' => '' ),
				)
			),
			'object_fit'      => 'cover',
			'object_position' => '50% 50%',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$fit = sanitize_key( (string) ( $settings['object_fit'] ?? 'cover' ) );
		if ( ! in_array( $fit, array( 'cover', 'contain', 'fill', 'none' ), true ) ) {
			$fit = 'cover';
		}
		return array(
			'items'           => $this->sanitize_items( (string) ( $settings['items'] ?? '' ) ),
			'object_fit'      => $fit,
			'object_position' => self::sanitize_object_position( $settings['object_position'] ?? '50% 50%' ),
		);
	}

	private function sanitize_items( string $raw ): string {
		$items = self::parse_items( $raw );
		$clean = array();
		foreach ( $items as $it ) {
			$clean[] = array(
				'title'   => sanitize_text_field( (string) ( $it['title'] ?? '' ) ),
				'content' => sanitize_textarea_field( (string) ( $it['content'] ?? '' ) ),
				'image'   => esc_url_raw( (string) ( $it['image'] ?? '' ) ),
			);
		}
		if ( count( $clean ) > 30 ) {
			$clean = array_slice( $clean, 0, 30 );
		}
		$json = Json::encode( $clean );
		return is_string( $json ) ? $json : '[]';
	}

	/**
	 * @return list<array{title:string,content:string,image?:string}>
	 */
	public static function parse_items( string $raw ): array {
		$parsed = AccordionWidget::parse_items( $raw );
		// Accordion parse always returns image key.
		return $parsed;
	}

	public function render( Node $node, array $context = array() ): string {
		$items = self::parse_items( (string) ( $node->settings['items'] ?? '' ) );
		$items = array_values(
			array_filter(
				$items,
				static function ( $it ) {
					return trim( (string) ( $it['title'] ?? '' ) ) !== '';
				}
			)
		);
		if ( ! $items ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-tabs ab-empty">Abas — adicione itens</div>'
				: '';
		}
		$s       = $node->settings;
		$fit     = esc_attr( (string) ( $s['object_fit'] ?? 'cover' ) );
		$obj_pos = esc_attr( self::sanitize_object_position( $s['object_position'] ?? '50% 50%' ) );
		$uid     = 'abtabs_' . preg_replace( '/[^a-zA-Z0-9_]/', '', $node->id );
		$html    = '<div class="ab-tabs" data-ab-tabs="1" style="--ab-tabs-fit:' . $fit . ';--ab-tabs-pos:' . $obj_pos . '">';
		$html   .= '<div class="ab-tabs__nav" role="tablist">';
		foreach ( $items as $i => $item ) {
			$active = $i === 0 ? ' is-active' : '';
			$html  .= '<button type="button" class="ab-tabs__tab' . $active . '" data-tab="' . esc_attr( $uid . '_' . $i ) . '" role="tab">'
				. esc_html( (string) $item['title'] ) . '</button>';
		}
		$html .= '</div><div class="ab-tabs__panels">';
		foreach ( $items as $i => $item ) {
			$active  = $i === 0 ? ' is-active' : '';
			$content = (string) ( $item['content'] ?? '' );
			$image   = (string) ( $item['image'] ?? '' );
			$html   .= '<div class="ab-tabs__panel' . $active . '" id="' . esc_attr( $uid . '_' . $i ) . '" role="tabpanel">';
			if ( $image !== '' ) {
				$html .= '<figure class="ab-tabs__media"><img src="' . esc_url( $image ) . '" alt="" loading="lazy" style="object-fit:' . $fit . ';object-position:' . $obj_pos . '"/></figure>';
			}
			if ( $content !== '' ) {
				$paras = preg_split( '/\n\n+/', $content ) ?: array( $content );
				foreach ( $paras as $p ) {
					$p = trim( $p );
					if ( $p !== '' ) {
						$html .= '<p class="ab-tabs__text">' . esc_html( $p ) . '</p>';
					}
				}
			}
			$html .= '</div>';
		}
		$html .= '</div></div>';
		return $html;
	}
}
