<?php
/**
 * Icon List 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 ET\Builder\Packages\Module\Module;
use ET\Builder\Packages\Module\Options\Element\ElementClassnames;
use ET\Builder\Packages\ModuleLibrary\ModuleRegistration;
use ET\Builder\Packages\Module\Layout\Components\StyleCommon\CommonStyle;
use ET\Builder\Packages\Module\Options\Css\CssStyle;
use DiviSupreme\Extensions\IconLibraries\LegacyModuleIconStyles;


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


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

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

	/**
	 * Register module.
	 */
	public static function register_module(): void
	{
		$module_json_path = DSM_DIR_PATH . 'divi-5/public/packages/module-library/icon-list-child';

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


	/**
	 * @param mixed $params Style params from CommonStyle.
	 */
	public static function icon_style_declaration( $params ): string {
		return LegacyModuleIconStyles::build_pseudo_icon_declaration( $params );
	}

	/**
	 * Render module style.
	 *
	 * @param array $args - Arguments.
	 */
	public static function module_styles(array $args): void
	{
		$attrs = $args['attrs'] ?? array();
		$elements = $args['elements'];
		$tooltip_placement = $attrs['tooltip_placement']['innerContent']['desktop']['value'] ?? '';
		$tooltip_block_id    = isset( $args['id'] ) ? (string) $args['id'] : '';
		$tooltip_css_attr    = str_replace(
			array( '\\', '"' ),
			array( '\\\\', '\\"' ),
			$tooltip_block_id
		);
		$tooltip_popper_root = '' !== $tooltip_block_id
			? '[data-dsm-icon-list-tooltip-id="' . $tooltip_css_attr . '"]'
			: '';

		Style::add(
			array(
				'id' => $args['id'],
				'name' => $args['name'],
				'orderIndex' => $args['orderIndex'],
				'storeInstance' => $args['storeInstance'],
				'styles' => array(
					// Module.
					$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' => 'iconStyling',
						)
					),

					$elements->style(
						array(
							'attrName' => 'imageStyling',
						)
					),

					$elements->style(
						array(
							'attrName' => 'text',
						)
					),

					$elements->style(
						array(
							'attrName' => 'tooltip_padding',
						)
					),

					$elements->style(
						array(
							'attrName' => 'content',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_icon_list_icon",
							'attr' => $attrs['icon_gap_width']['innerContent'] ?? array(),
							'property' => 'width',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
							'orderClass' => $args['orderClass'],
							'selectors' => array(
								'desktop' => array(
									'value' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
									'hover' => "{$args['orderClass']}.dsm_icon_list_child:hover .dsm_icon_list_wrapper > .dsm_icon_list_icon",
								),
								'tablet' => array(
									'value' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
									'hover' => "{$args['orderClass']}.dsm_icon_list_child:hover .dsm_icon_list_wrapper > .dsm_icon_list_icon",
								),
								'phone' => array(
									'value' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
									'hover' => "{$args['orderClass']}.dsm_icon_list_child:hover .dsm_icon_list_wrapper > .dsm_icon_list_icon",
								),
							),
							'attr' => $attrs['icon_color']['innerContent'] ?? array(),
							'property' => 'color',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
							'orderClass' => $args['orderClass'],
							'selectors' => array(
								'desktop' => array(
									'value' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
									'hover' => "{$args['orderClass']}.dsm_icon_list_child:hover .dsm_icon_list_wrapper > .dsm_icon_list_icon",
								),
								'tablet' => array(
									'value' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
									'hover' => "{$args['orderClass']}.dsm_icon_list_child:hover .dsm_icon_list_wrapper > .dsm_icon_list_icon",
								),
								'phone' => array(
									'value' => "{$args['orderClass']}.dsm_icon_list_child .dsm_icon_list_wrapper > .dsm_icon_list_icon",
									'hover' => "{$args['orderClass']}.dsm_icon_list_child:hover .dsm_icon_list_wrapper > .dsm_icon_list_icon",
								),
							),
							'attr' => $attrs['icon_background_color']['innerContent'] ?? array(),
							'property' => 'background',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_icon_list_wrapper .dsm_icon_list_icon",
							'attr' => $attrs['icon_padding']['innerContent'] ?? array(),
							'property' => 'padding',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_icon_list_wrapper .dsm_icon_list_icon",
							'attr' => $attrs['icon_font_size']['innerContent'] ?? array(),
							'property' => 'font-size',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_icon_list_icon::after",
							'attr' => $attrs['font_icon']['innerContent'] ?? array(),
							'declarationFunction' => array(static::class, 'icon_style_declaration'),
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_icon_list_image",
							'attr' => $attrs['image_background_color']['innerContent'] ?? array(),
							'property' => 'background',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_icon_list_image",
							'attr' => $attrs['image_padding']['innerContent'] ?? array(),
							'property' => 'padding',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm_icon_list_image img",
							'attr' => $attrs['image_max_width']['innerContent'] ?? array(),
							'property' => 'width',
						)
					),

					'' !== $tooltip_popper_root ?

					CommonStyle::style(
						array(
							'selector' => "{$tooltip_popper_root} .tippy-box",
							'attr' => $attrs['tooltip_background_color']['innerContent'] ?? array(),
							'property' => 'background',
						)
					) : '',

					'' !== $tooltip_popper_root ?

					CommonStyle::style(
						array(
							'selector' => "{$tooltip_popper_root} .tippy-box",
							'attr' => $attrs['tooltip_max_width']['innerContent'] ?? array(),
							'property' => 'max-width',
						)
					) : '',

					( '' !== $tooltip_popper_root && 'top' === $tooltip_placement ) ?

					CommonStyle::style(
						array(
							'selector' => "{$tooltip_popper_root} .tippy-box[data-placement^='top'] .tippy-arrow::before",
							'attr' => $attrs['tooltip_background_color']['innerContent'] ?? array(),
							'property' => 'border-top-color',
						)
					) : '',

					( '' !== $tooltip_popper_root && 'bottom' === $tooltip_placement ) ?

					CommonStyle::style(
						array(
							'selector' => "{$tooltip_popper_root} .tippy-box[data-placement^='bottom'] .tippy-arrow::before",
							'attr' => $attrs['tooltip_background_color']['innerContent'] ?? array(),
							'property' => 'border-bottom-color',
						)
					) : '',

					( '' !== $tooltip_popper_root && 'left' === $tooltip_placement ) ?

					CommonStyle::style(
						array(
							'selector' => "{$tooltip_popper_root} .tippy-box[data-placement^='left'] .tippy-arrow::before",
							'attr' => $attrs['tooltip_background_color']['innerContent'] ?? array(),
							'property' => 'border-left-color',
						)
					) : '',

					( '' !== $tooltip_popper_root && 'right' === $tooltip_placement ) ?

					CommonStyle::style(
						array(
							'selector' => "{$tooltip_popper_root} .tippy-box[data-placement^='right'] .tippy-arrow::before",
							'attr' => $attrs['tooltip_background_color']['innerContent'] ?? array(),
							'property' => 'border-right-color',
						)
					) : '',

				),
			)
		);
	}

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

		// Element Script Data Options.
		$elements->script_data(
			array(
				'attrName' => 'module',
			)
		);
	}

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

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

		$classnames_instance->add('dsm_icon_list_child');
	}

	/**
	 * Render module HTML output.
	 *
	 * @param array     $attrs - Modules Attributes.
	 * @param string    $content - Content.
	 * @param \WP_Block $block - Block.
	 * @param mixed     $elements - Elements.
	 */
	public static function render_callback($attrs, $content, $block, $elements): string
	{
		$use_icon    = $attrs['use_icon']['innerContent']['desktop']['value'] ?? 'on';
		$text_value  = $attrs['text']['innerContent']['desktop']['value'] ?? '';
		$image_raw   = $attrs['image']['innerContent']['desktop']['value'] ?? '';
		$image_url   = '';
		if (is_array($image_raw)) {
			$src = $image_raw['src'] ?? '';
			$image_url = is_string($src) ? $src : '';
		} elseif (is_string($image_raw)) {
			$image_url = $image_raw;
		}
		$use_tooltip = $attrs['use_tooltip']['innerContent']['desktop']['value'] ?? 'off';
		$tooltip_content = $attrs['content']['innerContent']['desktop']['value'] ?? '';
		$tooltip_placement = $attrs['tooltip_placement']['innerContent']['desktop']['value'] ?? 'right';
		$link_url = $attrs['module']['advanced']['link']['desktop']['value']['url'] ?? '';
		$link_target = $attrs['module']['advanced']['link']['desktop']['value']['target'] ?? '';
		$block_id    = isset( $block->parsed_block['id'] ) ? (string) $block->parsed_block['id'] : '';

		// Icon glyph is rendered via ::after + module_styles (not as raw HTML — avoids <>& in markup/CSS).
		$icon = HTMLUtility::render(
			array(
				'tag' => 'span',
				'attributes' => array(
					'class' => 'dsm_icon_list_icon',
				),
			)
		);

		$image_markup = sprintf(
			'<span class="dsm_icon_list_image">
			  <img src="%1$s" />
			</span>',
			$image_url
		);

		$markup_with_tooltip = sprintf(
			'<div class="dsm-tooltip dsm_icon_list_tooltip dsm-frontend" data-dsm-tooltip-placement="%4$s" data-dsm-icon-list-tooltip-id="%5$s">
			   <span class="dsm_icon_list_wrapper">
			     %1$s
			  </span>
			  <span class="dsm_icon_list_text">%2$s</span>
			</div>
			<div class="tooltip-content">%3$s</div>',
			'off' === $use_icon ? $image_markup : $icon,
			$text_value,
			$tooltip_content,
			$tooltip_placement,
			esc_attr( $block_id )
		);

		$markup_without_tooltip = sprintf(
			'<span class="dsm_icon_list_wrapper">
			     %1$s
			  </span>
			  <span class="dsm_icon_list_text">%2$s</span>
			',
			'off' === $use_icon ? $image_markup : $icon,
			$text_value
		);

		$container = sprintf(
			'%1$s',
			!empty($link_url) ? sprintf(
				'<a href="%1$s" %2$s>%3$s</a>',
				$link_url,
				'on' === $link_target ? 'target="_blank"' : '',
				'on' === $use_tooltip ? $markup_with_tooltip : $markup_without_tooltip
			) : (
				'on' === $use_tooltip ? $markup_with_tooltip : $markup_without_tooltip
			)
		);

		// Module Inner.
		// Essentially, this is the module content.
		// Were wrapping the title and content in a div with class `et_pb_module_inner`.
		$module_inner = HTMLUtility::render(
			array(
				'tag' => 'div',
				'attributes' => array(
					'class' => 'et_pb_module_inner',
				),
				'childrenSanitizer' => 'et_core_esc_previously',
				'children' => $container,
			)
		);

		// This are the module elements that will be rendered in the frontend.

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

		// This are the children of the module container, which are the module elements and the module inner.
		$module_container_children = $module_elements . $container;

		return Module::render(
			array(
				// FE only.
				'orderIndex' => $block->parsed_block['orderIndex'],
				'storeInstance' => $block->parsed_block['storeInstance'],
				// VB equivalent.
				'tag' => 'li',
				'attrs' => $attrs,
				'elements' => $elements,
				'id' => $block->parsed_block['id'],
				'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,
			)
		);
	}
}
