<?php
/**
 * Image Hotspot Child Module.
 *
 * @package DiviSupreme
 */

declare(strict_types=1);

namespace DiviSupreme\Modules;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

use ET\Builder\Framework\DependencyManagement\Interfaces\DependencyInterface;
use ET\Builder\Framework\Utility\HTMLUtility;
use ET\Builder\FrontEnd\Module\Style;
use DiviSupreme\Extensions\IconLibraries\LegacyModuleIconStyles;
use ET\Builder\Packages\Module\Module;
use ET\Builder\Packages\Module\Layout\Components\StyleCommon\CommonStyle;
use ET\Builder\Packages\Module\Options\Css\CssStyle;
use ET\Builder\Packages\Module\Options\Element\ElementClassnames;
use ET\Builder\Packages\ModuleLibrary\ModuleRegistration;
use ET\Builder\Packages\StyleLibrary\Utils\StyleDeclarations;

use DiviSupreme\Includes\ModuleRegisterAttrsNormalize;

/**
 * Class that handles "ImageHotspotsChild Module" module.
 */
class ImageHotspotsChild implements DependencyInterface {

	/**
	 * DSM Config.
	 *
	 * @var array<string, bool>
	 */
	public static $dsm_config = array(
		'load_icons' => true,
	);

	/**
	 * Register module.
	 * `DependencyInterface` interface ensures class method name `load()` is executed for initialization.
	 */
	public function load() {
		add_filter(
			'divi_module_library_register_module_attrs',
			array( self::class, 'filter_register_module_attrs' ),
			10,
			2
		);
		add_action( 'init', array( self::class, 'register_module' ) );
	}

	/**
	 * Normalize migrated tooltip `content` rich-text shape after merged attrs (matches card-carousel-child / flipbox-child).
	 *
	 * @param array<string, mixed> $module_attrs Merged module attrs.
	 * @param array<string, mixed> $filter_args  Contains `name`, `attrs`, `id`, `storeInstance`.
	 * @return array<string, mixed>
	 */
	public static function filter_register_module_attrs( $module_attrs, $filter_args ) {
		if ( ! is_array( $module_attrs ) || ! is_array( $filter_args ) ) {
			return is_array( $module_attrs ) ? $module_attrs : array();
		}

		$name = $filter_args['name'] ?? '';
		if ( ! in_array( $name, array( 'dsm/image-hotspots-child', 'dsm/image-hotspot-child' ), true ) ) {
			return $module_attrs;
		}

		ModuleRegisterAttrsNormalize::image_hotspots_child_merged( $module_attrs );

		return $module_attrs;
	}

	/**
	 * Initialises the module.
	 *
	 * @return void
	 */
	public static function dsm_initialise() {
		add_action(
			'divi_module_library_modules_dependency_tree',
			function ( $dependency_tree ) {
				$dependency_tree->add_dependency( new self() );
			}
		);
	}

	/**
	 * Register module.
	 *
	 * @return void
	 */
	public static function register_module() {
		$module_json_path = DSM_DIR_PATH . 'divi-5/public/packages/module-library/image-hotspots-child';

		ModuleRegistration::register_module(
			$module_json_path,
			array(
				'render_callback' => array( self::class, 'render_callback' ),
			)
		);
	}

	/**
	 * Icon ::before declaration for hotspot icon font.
	 *
	 * @param array<string, mixed> $params Parameters.
	 * @return string
	 */
	public static function icon_style_declaration( $params ) {
		return LegacyModuleIconStyles::build_pseudo_icon_declaration( $params );
	}

	/**
	 * Render module style.
	 *
	 * @param array $args Arguments.
	 * @return void
	 */
	public static function module_styles( $args ) {
		$attrs    = $args['attrs'] ?? array();
		$elements = $args['elements'];

		Style::add(
			array(
				'id'            => $args['id'],
				'name'          => $args['name'],
				'orderIndex'    => $args['orderIndex'],
				'storeInstance' => $args['storeInstance'],
				'styles'        => array(
					$elements->style(
						array(
							'attrName'   => 'module',
							'styleProps' => array(
								'disabledOn' => array(
									'disabledModuleVisibility' => $args['settings']['disabledModuleVisibility'] ?? null,
								),
							),
						)
					),
					CssStyle::style(
						array(
							'selector' => $args['orderClass'],
							'attr'     => $attrs['css'] ?? array(),
						)
					),
					$elements->style(
						array(
							'attrName' => 'hotspot_padding',
						)
					),
					$elements->style(
						array(
							'attrName' => 'tooltip_padding',
						)
					),
					$elements->style(
						array(
							'attrName' => 'hotspotStyle',
						)
					),
					$elements->style(
						array(
							'attrName' => 'imageStyle',
						)
					),
					$elements->style(
						array(
							'attrName' => 'hotspot_text',
						)
					),
					$elements->style(
						array(
							'attrName' => 'tooltipStyle',
						)
					),
					$elements->style(
						array(
							'attrName' => 'pulseStyle',
						)
					),
					$elements->style(
						array(
							'attrName' => 'tooltip_header',
						)
					),
					$elements->style(
						array(
							'attrName' => 'tooltip_body',
						)
					),
					CommonStyle::style(
						array(
							'selector'            => "{$args['orderClass']} .dsm_image_hotspots_icon::before",
							'attr'                => $attrs['font_icon']['innerContent'] ?? array(),
							'declarationFunction' => array( static::class, 'icon_style_declaration' ),
						)
					),
					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}",
							'attr'     => $attrs['hotspot_image_max_width']['innerContent'] ?? array(),
							'property' => 'max-width',
						)
					),
					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}:not(.tippy-box)",
							'attr'     => $attrs['left_position']['innerContent'] ?? array(),
							'property' => 'left',
						)
					),
					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}:not(.tippy-box)",
							'attr'     => $attrs['top_position']['innerContent'] ?? array(),
							'property' => 'top',
						)
					),
					CommonStyle::style(
						array(
							'selector' => ".dsm_image_hotspots {$args['orderClass']} .dsm_image_hotspots_icon::before",
							'attr'     => $attrs['icon_color']['innerContent'] ?? array(),
							'property' => 'color',
						)
					),
					CommonStyle::style(
						array(
							'selector' => ".dsm_image_hotspots {$args['orderClass']} .dsm_image_hotspots_icon::before",
							'attr'     => $attrs['icon_font_size']['innerContent'] ?? array(),
							'property' => 'font-size',
						)
					),
					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}.tippy-box .tippy-content",
							'attr'     => $attrs['tooltip_background_color']['innerContent'] ?? array(),
							'property' => 'background-color',
						)
					),
					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}.tippy-box .tippy-arrow",
							'attr'     => $attrs['tooltip_background_color']['innerContent'] ?? array(),
							'property' => 'color',
						)
					),
					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}.tippy-box .tippy-content",
							'attr'     => $attrs['tooltip_max_width']['innerContent'] ?? array(),
							'property' => 'max-width',
						)
					),
					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_image_hotspot_pulse:before",
							'attr'     => $attrs['pulse_background_color']['innerContent'] ?? array(),
							'property' => 'background-color',
						)
					),
				),
			)
		);
	}

	/**
	 * Render module script data.
	 *
	 * @param array $args Arguments.
	 * @return void
	 */
	public static function module_script_data( $args ) {
		$elements = $args['elements'];

		$elements->script_data(
			array(
				'attrName' => 'module',
			)
		);
	}

	/**
	 * Render module classnames.
	 *
	 * @param array $args Arguments.
	 * @return void
	 */
	public static function module_classnames( $args ) {
		$classnames_instance = $args['classnamesInstance'];
		$attrs               = $args['attrs'];

		$classnames_instance->add(
			ElementClassnames::classnames(
				array(
					'attrs' => $attrs['module']['decoration'] ?? array(),
				)
			)
		);
	}

	/**
	 * Render module HTML output.
	 *
	 * @param array     $attrs   Modules Attributes.
	 * @param string    $content Content.
	 * @param \WP_Block $block   Block.
	 * @param mixed     $elements Elements.
	 * @return string
	 */
	public static function render_callback( $attrs, $content, $block, $elements ) {
		$hotspot_type      = $attrs['hotspot_type']['innerContent']['desktop']['value'] ?? 'icon';
		$hotspot_text      = $attrs['hotspot_text']['innerContent']['desktop']['value'] ?? 'text';
		$hotspot_img_raw = $attrs['hotspot_img']['innerContent']['desktop']['value'] ?? '';
		$hotspot_img     = ImageHotspots::get_image_src( $hotspot_img_raw );
		if ( '' === $hotspot_img && 'image' === $hotspot_type ) {
			$hotspot_img = ImageHotspots::PLACEHOLDER_IMAGE_SRC;
		}
		$tooltip_raw       = $attrs['content']['innerContent']['desktop']['value'] ?? 'Your tooltip content goes here';
		$tooltip_placement = $attrs['tooltip_placement']['innerContent']['desktop']['value'] ?? 'top';
		$use_tooltip       = $attrs['use_tooltip']['innerContent']['desktop']['value'] ?? 'on';
		$pulse_animation   = $attrs['pulse_animation']['innerContent']['desktop']['value'] ?? 'off';

		if ( is_array( $tooltip_raw ) && isset( $tooltip_raw['text'] ) ) {
			$tooltip_html = wp_kses_post( (string) $tooltip_raw['text'] );
		} elseif ( is_string( $tooltip_raw ) ) {
			$tooltip_html = wp_kses_post( $tooltip_raw );
		} else {
			$tooltip_html = '';
		}

		$tooltip_wrapper = sprintf(
			'<div class="dsm_image_hotspot_tooltip">
			   <div class="dsm_image_tooltip_content">
			   	  %1$s
			   </div>
			</div>',
			$tooltip_html
		);

		$container = sprintf(
			'%8$s
			<div class="dsm_image_hotspots_wrapper dsm-hotspot-frontend" data-tippy-arrow="true" data-tippy-placement="%5$s" data-dsm-tooltip-show="%6$s" data-order-class="dsm_image_hotspots_child_%7$s">
			  %1$s
			  %2$s
			  %3$s
			</div>
			%4$s',
			'icon' === $hotspot_type ? '<span class="et-pb-icon dsm_image_hotspots_icon"></span>' : '',
			'text' === $hotspot_type ? sprintf( '<span class="dsm_image_hotspots_text">%1$s</span>', esc_html( (string) $hotspot_text ) ) : '',
			'image' === $hotspot_type ? ImageHotspots::render_responsive_image_tag( $hotspot_img, $hotspot_img_raw, 'dsm_image_hotspot_img', '' ) : '',
			$tooltip_wrapper,
			esc_attr( $tooltip_placement ),
			esc_attr( $use_tooltip ),
			(int) $block->parsed_block['orderIndex'],
			'on' === $pulse_animation ? '<div class="dsm_image_hotspot_pulse"></div>' : ''
		);

		$module_inner = HTMLUtility::render(
			array(
				'tag'               => 'div',
				'attributes'        => array(
					'class' => 'et_pb_module_inner',
				),
				'childrenSanitizer' => 'et_core_esc_previously',
				'children'          => $container,
			)
		);

		$module_elements = $elements->style_components(
			array(
				'attrName' => 'module',
			)
		);

		$module_container_children = $module_elements . $module_inner;

		return Module::render(
			array(
				'orderIndex'          => $block->parsed_block['orderIndex'],
				'storeInstance'       => $block->parsed_block['storeInstance'],
				'attrs'               => $attrs,
				'elements'            => $elements,
				'id'                  => $block->parsed_block['id'],
				'moduleClassName'     => 'dsm_image_hotspots_child',
				'name'                => $block->block_type->name,
				'classnamesFunction'  => array( self::class, 'module_classnames' ),
				'moduleCategory'      => $block->block_type->category,
				'stylesComponent'     => array( self::class, 'module_styles' ),
				'scriptDataComponent' => array( self::class, 'module_script_data' ),
				'children'            => $module_container_children,
			)
		);
	}
}
