<?php
/**
 * Popup — image / carousel modal with effects, timer, home or all pages.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;


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

final class PopupWidget extends WidgetBase {

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

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

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

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

	public function get_defaults(): array {
		return array(
			// image | carousel
			'mode'           => 'image',
			'images'         => '[]',
			// all | home | current
			'scope'          => 'current',
			// once | every | session
			'frequency'      => 'session',
			'delay'          => '800',
			'slide_time'     => '4000',
			'autoplay'       => '1',
			'show_close'     => '1',
			'overlay'        => '1',
			'max_width'      => '720',
			// none | fadein | fadeinup | zoomin | ...
			'open_effect'    => 'fadein',
			'slide_effect'   => 'fade',
			'enabled'        => '1',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$gw  = new GalleryWidget();
		$tmp = $gw->sanitize_settings(
			array(
				'images'  => $settings['images'] ?? '[]',
				'columns' => '1',
				'gap'     => '0',
			)
		);
		$mode = sanitize_key( (string) ( $settings['mode'] ?? 'image' ) );
		if ( ! in_array( $mode, array( 'image', 'carousel' ), true ) ) {
			$mode = 'image';
		}
		$scope = sanitize_key( (string) ( $settings['scope'] ?? 'current' ) );
		if ( ! in_array( $scope, array( 'current', 'home', 'all' ), true ) ) {
			$scope = 'current';
		}
		$freq = sanitize_key( (string) ( $settings['frequency'] ?? 'session' ) );
		if ( ! in_array( $freq, array( 'once', 'every', 'session' ), true ) ) {
			$freq = 'session';
		}
		$open = sanitize_key( (string) ( $settings['open_effect'] ?? 'fadein' ) );
		$slide = sanitize_key( (string) ( $settings['slide_effect'] ?? 'fade' ) );
		if ( ! in_array( $slide, array( 'fade', 'slide', 'zoom' ), true ) ) {
			$slide = 'fade';
		}
		$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';
		};

		return array(
			'mode'         => $mode,
			'images'       => $tmp['images'],
			'scope'        => $scope,
			'frequency'    => $freq,
			'delay'        => (string) max( 0, min( 30000, (int) ( $settings['delay'] ?? 800 ) ) ),
			'slide_time'   => (string) max( 1000, min( 30000, (int) ( $settings['slide_time'] ?? 4000 ) ) ),
			'autoplay'     => $flag( $settings['autoplay'] ?? null, '1' ),
			'show_close'   => $flag( $settings['show_close'] ?? null, '1' ),
			'overlay'      => $flag( $settings['overlay'] ?? null, '1' ),
			'max_width'    => (string) max( 280, min( 1400, (int) ( $settings['max_width'] ?? 720 ) ) ),
			'open_effect'  => $open !== '' ? $open : 'fadein',
			'slide_effect' => $slide,
			'enabled'      => $flag( $settings['enabled'] ?? null, '1' ),
		);
	}

	/**
	 * @return list<string>
	 */
	public static function image_urls( array $settings ): array {
		return GalleryWidget::urls_from_images( $settings['images'] ?? '[]' );
	}

	/**
	 * Public payload for global popup injection.
	 *
	 * @return array<string, mixed>|null
	 */
	public static function public_config( Node $node ): ?array {
		$s = $node->settings;
		if ( ( $s['enabled'] ?? '1' ) !== '1' ) {
			return null;
		}
		$urls = self::image_urls( $s );
		if ( ! $urls ) {
			return null;
		}
		return array(
			'id'           => $node->id,
			'mode'         => (string) ( $s['mode'] ?? 'image' ),
			'images'       => $urls,
			'scope'        => (string) ( $s['scope'] ?? 'current' ),
			'frequency'    => (string) ( $s['frequency'] ?? 'session' ),
			'delay'        => (int) ( $s['delay'] ?? 800 ),
			'slide_time'   => (int) ( $s['slide_time'] ?? 4000 ),
			'autoplay'     => ( $s['autoplay'] ?? '1' ) === '1',
			'show_close'   => ( $s['show_close'] ?? '1' ) === '1',
			'overlay'      => ( $s['overlay'] ?? '1' ) === '1',
			'max_width'    => (int) ( $s['max_width'] ?? 720 ),
			'open_effect'  => (string) ( $s['open_effect'] ?? 'fadein' ),
			'slide_effect' => (string) ( $s['slide_effect'] ?? 'fade' ),
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$editor = ! empty( $context['editor'] );
		$cfg    = self::public_config( $node );

		if ( $editor ) {
			$urls  = $cfg ? $cfg['images'] : array();
			$thumb = $urls[0] ?? '';
			$scope = (string) ( $node->settings['scope'] ?? 'current' );
			$scope_lab = $scope === 'all' ? 'Todas as páginas' : ( $scope === 'home' ? 'Só Home' : 'Só esta página' );
			$html  = '<div class="ab-popup-placeholder" data-ab-popup-ph="1">';
			$html .= '<div class="ab-popup-placeholder__badge">Popup · ' . esc_html( $scope_lab ) . '</div>';
			if ( $thumb ) {
				$html .= '<img src="' . esc_url( $thumb ) . '" alt="" class="ab-popup-placeholder__img"/>';
			} else {
				$html .= '<p class="ab-popup-placeholder__empty">Adicione imagens no painel. O popup abre no site público.</p>';
			}
			$html .= '<p class="ab-popup-placeholder__hint">' . count( $urls ) . ' imagem(ns) · atraso ' . esc_html( (string) ( $node->settings['delay'] ?? '800' ) ) . 'ms</p>';
			$html .= '</div>';
			return $html;
		}

		// On front: current-scope popups render a marker; JS opens from data attribute.
		// home/all are also synced to option and injected site-wide.
		if ( ! $cfg ) {
			return '';
		}
		$scope = $cfg['scope'];
		if ( $scope === 'home' && ! is_front_page() && ! is_home() ) {
			return '';
		}
		// "all" also renders here if widget is on the page; global inject handles other pages.
		$json = Json::encode( $cfg );
		if ( ! is_string( $json ) ) {
			return '';
		}
		return '<div class="ab-popup-source" data-ab-popup="' . esc_attr( $json ) . '" hidden aria-hidden="true"></div>';
	}
}
