<?php
/**
 * Toggle — one or many expandable items (title + content + optional image).
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;


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

final class ToggleWidget extends WidgetBase {

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

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

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

	public function get_defaults(): array {
		return array(
			'items'           => Json::encode(
				array(
					array(
						'title'   => 'Clique para expandir',
						'content' => 'Conteúdo oculto.',
						'image'   => '',
					),
				)
			),
			'open_first'      => '0',
			'object_fit'      => 'cover',
			'object_position' => '50% 50%',
		);
	}

	public function sanitize_settings( array $settings ): array {
		// Backward compat: single title/content → one item.
		if ( empty( $settings['items'] ) && ( ! empty( $settings['title'] ) || ! empty( $settings['content'] ) ) ) {
			$settings['items'] = Json::encode(
				array(
					array(
						'title'   => (string) ( $settings['title'] ?? '' ),
						'content' => (string) ( $settings['content'] ?? '' ),
						'image'   => '',
					),
				)
			);
		}
		$flag = static function ( $v, string $d = '0' ): string {
			if ( $v === null || $v === '' ) {
				return $d;
			}
			return ( $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes' ) ? '1' : '0';
		};
		$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'] ?? '' ) ),
			'open_first'      => $flag( $settings['open_first'] ?? null, '0' ),
			'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 ) > 40 ) {
			$clean = array_slice( $clean, 0, 40 );
		}
		$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 {
		// Reuse accordion JSON / pipe parser shape.
		return AccordionWidget::parse_items( $raw );
	}

	public function render( Node $node, array $context = array() ): string {
		$s     = $node->settings;
		$items = self::parse_items( (string) ( $s['items'] ?? '' ) );
		$items = array_values(
			array_filter(
				$items,
				static function ( $it ) {
					return trim( (string) ( $it['title'] ?? '' ) ) !== '' || trim( (string) ( $it['content'] ?? '' ) ) !== '';
				}
			)
		);
		if ( ! $items ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-toggle-list ab-empty">Toggle — adicione itens</div>'
				: '';
		}
		$open_first = ( $s['open_first'] ?? '0' ) === '1';
		$fit        = esc_attr( (string) ( $s['object_fit'] ?? 'cover' ) );
		$obj_pos    = esc_attr( self::sanitize_object_position( $s['object_position'] ?? '50% 50%' ) );
		$html       = '<div class="ab-toggle-list" data-ab-toggle-list="1" style="--ab-tg-fit:' . $fit . ';--ab-tg-pos:' . $obj_pos . '">';
		foreach ( $items as $i => $item ) {
			$open    = $open_first && $i === 0 ? ' is-open' : '';
			$title   = (string) ( $item['title'] ?? '' );
			$content = (string) ( $item['content'] ?? '' );
			$image   = (string) ( $item['image'] ?? '' );
			$html   .= '<div class="ab-toggle-w' . $open . '" data-ab-toggle="1">';
			$html   .= '<button type="button" class="ab-toggle-w__head">'
				. '<span class="ab-toggle-w__title">' . esc_html( $title ) . '</span>'
				. '<span class="ab-toggle-w__icon" aria-hidden="true">▾</span></button>';
			$html   .= '<div class="ab-toggle-w__body">';
			if ( $image !== '' ) {
				$html .= '<figure class="ab-toggle-w__media"><img src="' . esc_url( $image ) . '" alt="' . esc_attr( $title ) . '" 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-toggle-w__text">' . esc_html( $p ) . '</p>';
					}
				}
			}
			$html .= '</div></div>';
		}
		$html .= '</div>';
		return $html;
	}
}
