<?php
/**
 * Image Carousel (pro) — arrows, dots, autoplay, captions.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;


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

final class ImageCarouselProWidget extends WidgetBase {

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

	public function get_title(): string {
		return 'Carrossel de imagens';
	}

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

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

	public function get_defaults(): array {
		return array(
			// One per line: URL or URL|Legenda
			'images'   => "|Infantil\n|Sala de aula\n|Esportes",
			'height'   => '360',
			'autoplay' => '1',
			'dots'     => '1',
			'arrows'   => '1',
			'interval' => '4500',
			'radius'   => '12',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$flag = static function ( $v, string $d = '1' ): string {
			if ( $v === null || $v === '' ) {
				return $d;
			}
			return ( $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes' ) ? '1' : '0';
		};
		// Normalize to JSON array of URLs for gallery media picker + legacy lines.
		$parsed = self::parse_images( (string) ( $settings['images'] ?? '' ) );
		$urls   = array();
		foreach ( $parsed as $row ) {
			if ( ! empty( $row['url'] ) ) {
				// Keep caption as "url|caption" only if caption present; store as JSON objects.
				$urls[] = $row['caption'] !== ''
					? array( 'url' => $row['url'], 'caption' => $row['caption'] )
					: $row['url'];
			}
		}
		$json = Json::encode( $urls );
		return array(
			'images'   => is_string( $json ) ? $json : '[]',
			'height'   => (string) max( 120, min( 900, (int) ( $settings['height'] ?? 360 ) ) ),
			'autoplay' => $flag( $settings['autoplay'] ?? null, '1' ),
			'dots'     => $flag( $settings['dots'] ?? null, '1' ),
			'arrows'   => $flag( $settings['arrows'] ?? null, '1' ),
			'interval' => (string) max( 2000, min( 12000, (int) ( $settings['interval'] ?? 4500 ) ) ),
			'radius'   => (string) max( 0, min( 40, (int) ( $settings['radius'] ?? 12 ) ) ),
		);
	}

	/**
	 * @return list<array{url:string,caption:string}>
	 */
	public static function parse_images( string $raw ): array {
		$raw = trim( $raw );
		$out = array();
		if ( $raw === '' ) {
			return $out;
		}

		// JSON array of URLs or {url, caption} objects.
		if ( str_starts_with( $raw, '[' ) ) {
			$decoded = json_decode( $raw, true );
			if ( is_array( $decoded ) ) {
				foreach ( $decoded as $item ) {
					if ( is_string( $item ) ) {
						$url = esc_url_raw( trim( $item ) );
						if ( $url ) {
							$out[] = array( 'url' => $url, 'caption' => '' );
						}
						continue;
					}
					if ( is_array( $item ) && ! empty( $item['url'] ) ) {
						$url = esc_url_raw( (string) $item['url'] );
						if ( $url ) {
							$out[] = array(
								'url'     => $url,
								'caption' => sanitize_text_field( (string) ( $item['caption'] ?? $item['alt'] ?? '' ) ),
							);
						}
					}
				}
				return $out;
			}
		}

		$lines = preg_split( '/\r\n|\r|\n/', $raw ) ?: array();
		foreach ( $lines as $line ) {
			$line = trim( $line );
			if ( $line === '' || str_starts_with( $line, '[' ) || str_starts_with( $line, '{' ) ) {
				continue;
			}
			$p   = explode( '|', $line, 2 );
			$url = esc_url_raw( trim( $p[0] ) );
			if ( $url === '' ) {
				continue;
			}
			$out[] = array(
				'url'     => $url,
				'caption' => sanitize_text_field( trim( (string) ( $p[1] ?? '' ) ) ),
			);
		}
		return $out;
	}

	public function render( Node $node, array $context = array() ): string {
		$s      = $node->settings;
		$slides = self::parse_images( (string) ( $s['images'] ?? '' ) );
		if ( ! $slides ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-img-carousel ab-empty">Carrossel — URL ou URL|Legenda por linha</div>'
				: '';
		}
		$height   = (int) ( $s['height'] ?? 360 );
		$radius   = (int) ( $s['radius'] ?? 12 );
		$interval = (int) ( $s['interval'] ?? 4500 );
		$autoplay = ( $s['autoplay'] ?? '1' ) === '1' ? '1' : '0';
		$dots     = ( $s['dots'] ?? '1' ) === '1';
		$arrows   = ( $s['arrows'] ?? '1' ) === '1';

		$html  = '<div class="ab-img-carousel" style="--ab-ic-h:' . esc_attr( (string) $height ) . 'px;--ab-ic-r:' . esc_attr( (string) $radius ) . 'px" data-ab-img-carousel="1" data-autoplay="' . $autoplay . '" data-interval="' . esc_attr( (string) $interval ) . '">';
		$html .= '<div class="ab-img-carousel__track">';
		foreach ( $slides as $i => $slide ) {
			$active = $i === 0 ? ' is-active' : '';
			$html  .= '<figure class="ab-img-carousel__slide' . $active . '">';
			$html  .= '<img src="' . esc_url( $slide['url'] ) . '" alt="' . esc_attr( $slide['caption'] ) . '" loading="' . ( $i === 0 ? 'eager' : 'lazy' ) . '"/>';
			if ( $slide['caption'] !== '' ) {
				$html .= '<figcaption class="ab-img-carousel__cap">' . esc_html( $slide['caption'] ) . '</figcaption>';
			}
			$html .= '</figure>';
		}
		$html .= '</div>';
		if ( $arrows && count( $slides ) > 1 ) {
			$html .= '<button type="button" class="ab-img-carousel__nav ab-img-carousel__nav--prev" data-ab-ic-prev aria-label="Anterior">‹</button>';
			$html .= '<button type="button" class="ab-img-carousel__nav ab-img-carousel__nav--next" data-ab-ic-next aria-label="Próximo">›</button>';
		}
		if ( $dots && count( $slides ) > 1 ) {
			$html .= '<div class="ab-img-carousel__dots">';
			foreach ( $slides as $i => $_s ) {
				$html .= '<button type="button" class="ab-img-carousel__dot' . ( $i === 0 ? ' is-active' : '' ) . '" data-ab-ic-dot="' . esc_attr( (string) $i ) . '" aria-label="Slide ' . esc_attr( (string) ( $i + 1 ) ) . '"></button>';
			}
			$html .= '</div>';
		}
		$html .= '</div>';
		return $html;
	}
}
