<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class CounterWidget extends WidgetBase {
	public function get_type(): string {
		return 'counter';
	}
	public function get_title(): string {
		return 'Contador';
	}
	public function get_icon(): string {
		return 'counter';
	}

	public function get_defaults(): array {
		return array(
			'number'   => '100',
			'prefix'   => '',
			'suffix'   => '+',
			'title'    => 'Clientes',
			'align'    => 'center',
			'animate'  => '1',
			'duration' => '1600',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$align = in_array( ( $settings['align'] ?? '' ), array( 'left', 'center', 'right' ), true )
			? (string) $settings['align']
			: 'center';
		$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';
		};
		$duration = max( 400, min( 6000, (int) ( $settings['duration'] ?? 1600 ) ) );

		return array(
			'number'   => sanitize_text_field( (string) ( $settings['number'] ?? '0' ) ),
			'prefix'   => sanitize_text_field( (string) ( $settings['prefix'] ?? '' ) ),
			'suffix'   => sanitize_text_field( (string) ( $settings['suffix'] ?? '' ) ),
			'title'    => sanitize_text_field( (string) ( $settings['title'] ?? '' ) ),
			'align'    => $align,
			'animate'  => $flag( $settings['animate'] ?? null, '1' ),
			'duration' => (string) $duration,
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$s        = $node->settings;
		$align    = esc_attr( (string) ( $s['align'] ?? 'center' ) );
		$number   = (string) ( $s['number'] ?? '0' );
		$prefix   = (string) ( $s['prefix'] ?? '' );
		$suffix   = (string) ( $s['suffix'] ?? '' );
		$title    = (string) ( $s['title'] ?? '' );
		$animate  = ( $s['animate'] ?? '1' ) === '1';
		$duration = (string) max( 400, min( 6000, (int) ( $s['duration'] ?? 1600 ) ) );
		$editor   = ! empty( $context['editor'] );

		// Start at 0 when animating (front + editor); show final if animation off.
		$display = $animate
			? $prefix . '0' . $suffix
			: $prefix . $number . $suffix;

		$html  = '<div class="ab-counter" data-ab-counter="1" data-animate="' . ( $animate ? '1' : '0' ) . '" style="text-align:' . $align . '">';
		$html .= '<div class="ab-counter__number"'
			. ' data-target="' . esc_attr( $number ) . '"'
			. ' data-prefix="' . esc_attr( $prefix ) . '"'
			. ' data-suffix="' . esc_attr( $suffix ) . '"'
			. ' data-duration="' . esc_attr( $duration ) . '"'
			. ( $editor ? ' data-ab-editor="1"' : '' )
			. '>' . esc_html( $display ) . '</div>';
		if ( $title !== '' ) {
			$html .= '<div class="ab-counter__title">' . esc_html( $title ) . '</div>';
		}
		$html .= '</div>';
		return $html;
	}
}
