<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;


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

final class GalleryWidget extends WidgetBase {
	public function get_type(): string { return 'gallery'; }
	public function get_title(): string { return 'Galeria'; }
	public function get_icon(): string { return 'gallery'; }

	public function get_defaults(): array {
		return array(
			'images'         => '',
			'layout'         => 'grid', // grid | slider | masonry
			'columns'        => '3',
			'gap'            => '8',
			'ratio'          => '4/3', // auto | 1/1 | 4/3 | 16/9 | 3/2
			'per_view'       => '1', // for slider: how many visible
			'autoplay'       => '1', // slider: advance automatically
			'autoplay_speed' => '4500', // ms between slides
		);
	}

	public function sanitize_settings( array $settings ): array {
		$raw  = (string) ( $settings['images'] ?? '' );
		$urls = array();
		$decoded = json_decode( $raw, true );
		// Keep objects {id,url} when present so the media dialog can re-select them.
		$stored = array();
		if ( is_array( $decoded ) ) {
			foreach ( $decoded as $item ) {
				if ( is_string( $item ) ) {
					$u = esc_url_raw( $item );
					if ( $u ) {
						$urls[]   = $u;
						$stored[] = $u;
					}
				} elseif ( is_array( $item ) && ! empty( $item['url'] ) ) {
					$u = esc_url_raw( (string) $item['url'] );
					if ( $u ) {
						$urls[] = $u;
						$id     = (int) ( $item['id'] ?? 0 );
						$stored[] = $id > 0 ? array( 'id' => $id, 'url' => $u ) : $u;
					}
				}
			}
		} else {
			$parts = preg_split( '/[\n,]+/', $raw ) ?: array();
			foreach ( $parts as $p ) {
				$u = esc_url_raw( trim( explode( '|', $p )[0] ) );
				if ( $u ) {
					$urls[]   = $u;
					$stored[] = $u;
				}
			}
		}
		// De-dupe by URL while preserving {id,url} form.
		$seen   = array();
		$unique = array();
		foreach ( $stored as $item ) {
			$u = is_array( $item ) ? (string) ( $item['url'] ?? '' ) : (string) $item;
			if ( $u === '' || isset( $seen[ $u ] ) ) {
				continue;
			}
			$seen[ $u ] = true;
			$unique[]   = $item;
		}

		$layout = sanitize_key( (string) ( $settings['layout'] ?? 'grid' ) );
		if ( ! in_array( $layout, array( 'grid', 'slider', 'masonry' ), true ) ) {
			$layout = 'grid';
		}
		$ratio = (string) ( $settings['ratio'] ?? '4/3' );
		if ( ! in_array( $ratio, array( 'auto', '1/1', '4/3', '16/9', '3/2', '3/4' ), true ) ) {
			$ratio = '4/3';
		}

		$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';
		};
		$speed = (int) ( $settings['autoplay_speed'] ?? 4500 );
		if ( $speed < 1500 ) {
			$speed = 1500;
		}
		if ( $speed > 20000 ) {
			$speed = 20000;
		}

		return array(
			'images'         => Json::encode( array_values( $unique ) ),
			'layout'         => $layout,
			'columns'        => (string) max( 1, min( 6, (int) ( $settings['columns'] ?? 3 ) ) ),
			'gap'            => (string) max( 0, min( 48, (int) ( $settings['gap'] ?? 8 ) ) ),
			'ratio'          => $ratio,
			'per_view'       => (string) max( 1, min( 4, (int) ( $settings['per_view'] ?? 1 ) ) ),
			'autoplay'       => $flag( $settings['autoplay'] ?? null, '1' ),
			'autoplay_speed' => (string) $speed,
		);
	}

	/**
	 * @return list<string>
	 */
	public static function urls_from_images( $raw ): array {
		$urls = array();
		if ( is_string( $raw ) ) {
			$decoded = json_decode( $raw, true );
		} else {
			$decoded = $raw;
		}
		if ( ! is_array( $decoded ) ) {
			return $urls;
		}
		foreach ( $decoded as $item ) {
			if ( is_string( $item ) && $item !== '' ) {
				$urls[] = $item;
			} elseif ( is_array( $item ) && ! empty( $item['url'] ) ) {
				$urls[] = (string) $item['url'];
			}
		}
		return $urls;
	}

	public function render( Node $node, array $context = array() ): string {
		$s    = $node->settings;
		$urls = self::urls_from_images( $s['images'] ?? '[]' );
		if ( ! $urls ) {
			return ! empty( $context['editor'] ) ? '<div class="ab-gallery ab-empty">Galeria — abra a mídia</div>' : '';
		}
		$layout  = (string) ( $s['layout'] ?? 'grid' );
		$cols    = max( 1, min( 6, (int) ( $s['columns'] ?? 3 ) ) );
		$gap     = max( 0, min( 48, (int) ( $s['gap'] ?? 8 ) ) );
		$ratio   = (string) ( $s['ratio'] ?? '4/3' );
		$per     = max( 1, min( 4, (int) ( $s['per_view'] ?? 1 ) ) );
		$ratio_s = $ratio === 'auto' ? 'auto' : str_replace( '/', ' / ', $ratio );

		// Radius from node styles (desktop bag) so gallery corners match the panel control.
		$desk   = is_array( $node->styles['desktop'] ?? null ) ? $node->styles['desktop'] : array();
		$radius = trim( (string) ( $desk['radius'] ?? '' ) );
		$style  = sprintf(
			'--ab-gal-cols:%d;--ab-gal-gap:%dpx;--ab-gal-ratio:%s;--ab-gal-per:%d',
			$cols,
			$gap,
			$ratio_s,
			$per
		);
		if ( $radius !== '' && $radius !== '0' && $radius !== '0px' ) {
			$style .= ';--ab-radius:' . $radius . ';border-radius:' . $radius;
		}

		if ( $layout === 'slider' ) {
			$autoplay = ( $s['autoplay'] ?? '1' ) !== '0' && ( $s['autoplay'] ?? '1' ) !== 'false';
			$speed    = max( 1500, min( 20000, (int) ( $s['autoplay_speed'] ?? 4500 ) ) );
			$html     = '<div class="ab-gallery ab-gallery--slider" style="' . esc_attr( $style ) . '"'
				. ' data-ab-gallery-slider="1"'
				. ' data-per="' . esc_attr( (string) $per ) . '"'
				. ' data-autoplay="' . ( $autoplay ? '1' : '0' ) . '"'
				. ' data-autoplay-ms="' . esc_attr( (string) $speed ) . '">';
			$html    .= '<div class="ab-gallery__track">';
			foreach ( $urls as $i => $u ) {
				$u = esc_url( (string) $u );
				if ( $u === '' ) {
					continue;
				}
				$html .= '<figure class="ab-gallery__item' . ( $i === 0 ? ' is-active' : '' ) . '"><img src="' . $u . '" alt="" loading="lazy"/></figure>';
			}
			$html .= '</div>';
			// Always expose nav when more than one image (even if per_view == count).
			if ( count( $urls ) > 1 ) {
				$html .= '<button type="button" class="ab-gallery__nav ab-gallery__nav--prev" data-ab-gal-prev aria-label="Anterior">‹</button>';
				$html .= '<button type="button" class="ab-gallery__nav ab-gallery__nav--next" data-ab-gal-next aria-label="Próximo">›</button>';
			}
			$html .= '</div>';
			return $html;
		}

		$mod = $layout === 'masonry' ? ' ab-gallery--masonry' : ' ab-gallery--grid';
		$html = '<div class="ab-gallery' . $mod . '" style="' . esc_attr( $style ) . '">';
		foreach ( $urls as $u ) {
			$u = esc_url( (string) $u );
			if ( $u === '' ) {
				continue;
			}
			$html .= '<figure class="ab-gallery__item"><img src="' . $u . '" alt="" loading="lazy"/></figure>';
		}
		$html .= '</div>';
		return $html;
	}
}
