<?php

/**
 * Shuffle Letter 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\Text\TextStyle;
use ET\Builder\Packages\StyleLibrary\Utils\StyleDeclarations;
use ET\Builder\Packages\Module\Options\Css\CssStyle;
use ET\Builder\Packages\Module\Options\Link\LinkUtils;

/**
 * Class that handles "Shuffle Letter Module" module.
 */
class ShuffleLetters implements DependencyInterface
{


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

	/**
	 * Initilises 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.
	 */
	public static function register_module()
	{

		$module_json_path = DSM_DIR_PATH . 'divi-5/public/packages/module-library/shuffle-letters';

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

	public static function before_new_line_text_declaration($params)
	{
		$attr = $params['attrValue'] ?? array();

		$style_declarations = new StyleDeclarations(
			array(
				'returnType' => 'string',
				'important' => array(
					'display' => true,
				),
			)
		);

		$style_declarations->add('display', 'on' === $attr ? 'block' : 'inline-block');

		return $style_declarations->value();
	}

	public static function after_new_line_text_declaration($params)
	{
		$attr = $params['attrValue'] ?? array();

		$style_declarations = new StyleDeclarations(
			array(
				'returnType' => 'string',
				'important' => array(
					'display' => true,
				),
			)
		);

		$style_declarations->add('display', 'on' === $attr ? 'block' : 'inline-block');

		return $style_declarations->value();
	}

	/**
	 * Render module style.
	 *
	 * @param array $args - Arguments.
	 */
	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(
					// 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(),
						)
					),

					TextStyle::style(
						array(
							'selector' => $args['orderClass'],
							'attr' => $attrs['module']['advanced']['text'] ?? array(),
						)
					),

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

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

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

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm-before-shuffle-text",
							'attr' => $attrs['before_new_line']['innerContent'] ?? array(),
							'declarationFunction' => array(static::class, 'before_new_line_text_declaration'),
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm-after-shuffle-text",
							'attr' => $attrs['after_new_line']['innerContent'] ?? array(),
							'declarationFunction' => array(static::class, 'after_new_line_text_declaration'),
						)
					),
				),
			)
		);
	}

	/**
	 * Render module script data.
	 *
	 * @param array $args - Arguments.
	 */
	public static function module_script_data($args)
	{
		$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($args)
	{
		$classnames_instance = $args['classnamesInstance'];
		$attrs = $args['attrs'];
		$module_link_attr = $attrs['module']['advanced']['link'] ?? array();
		$text_color = $attrs['module']['advanced']['text']['text']['desktop']['value']['color'] ?? 'light';

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

		$classnames_instance->add('et_pb_bg_layout_' . $text_color);

		if (LinkUtils::is_enabled($module_link_attr)) {
			$classnames_instance->add('dsm-link');
		}
	}

	/**
	 * Normalize `title` innerContent for `headingLink` server render.
	 *
	 * @param array<string, mixed> $attrs Module attrs by reference.
	 * @return void
	 */
	private static function ensure_title_heading_link_shape(array &$attrs): void
	{
		if (!isset($attrs['title']['innerContent']) || !is_array($attrs['title']['innerContent'])) {
			return;
		}

		$inner = &$attrs['title']['innerContent'];

		foreach (array_keys($inner) as $breakpoint) {
			if (!isset($inner[$breakpoint]) || !is_array($inner[$breakpoint])) {
				continue;
			}

			if (!array_key_exists('value', $inner[$breakpoint])) {
				continue;
			}

			$value = &$inner[$breakpoint]['value'];

			if (is_string($value)) {
				$value = array(
					'text' => $value,
					'url' => '',
					'target' => 'off',
				);
				continue;
			}

			if (!is_array($value)) {
				continue;
			}

			if (!array_key_exists('url', $value)) {
				$value['url'] = '';
			}

			if (!array_key_exists('target', $value)) {
				$value['target'] = 'off';
			}
		}
	}

	/**
	 * Sanitize shuffle wrapper heading tag.
	 *
	 * @param mixed $heading_level Raw level.
	 * @return string
	 */
	private static function sanitize_heading_tag($heading_level): string
	{
		if (!is_string($heading_level)) {
			return 'h1';
		}

		$t = strtolower(trim($heading_level));
		if (preg_match('/^h[1-6]$/', $t)) {
			return $t;
		}

		if (in_array($t, array('p', 'div'), true)) {
			return $t;
		}

		return 'h1';
	}

	/**
	 * 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)
	{
		if (isset($elements->module_attrs) && is_array($elements->module_attrs)) {
			self::ensure_title_heading_link_shape($elements->module_attrs);
		}

		if (is_array($attrs)) {
			self::ensure_title_heading_link_shape($attrs);
		}

		$before_new_line = $attrs['before_new_line']['innerContent']['desktop']['value'] ?? 'off';
		$after_new_line = $attrs['after_new_line']['innerContent']['desktop']['value'] ?? 'off';

		$before_inner = $elements->render(
			array(
				'attrName' => 'before_shuffle_text',
			)
		);

		$after_inner = $elements->render(
			array(
				'attrName' => 'after_shuffle_text',
			)
		);

		$title_rendered = $elements->render(
			array(
				'attrName' => 'title',
			)
		);

		$title_plain = wp_strip_all_tags((string) $title_rendered, true);
		$title_plain = html_entity_decode($title_plain, ENT_QUOTES | ENT_HTML5, 'UTF-8');

		$shuffle_text_speed = $attrs['shuffle_text_speed']['innerContent']['desktop']['value'] ?? '0.05s';
		$shuffle_text_duration = $attrs['shuffle_text_duration']['innerContent']['desktop']['value'] ?? '1s';
		$shuffle_text_change = $attrs['shuffle_text_change']['innerContent']['desktop']['value'] ?? '';

		$heading_raw = $attrs['header']['decoration']['font']['font']['desktop']['value']['headingLevel'] ?? 'h1';
		$heading_tag = esc_attr(self::sanitize_heading_tag($heading_raw));

		$before_wrapped = '' !== trim(wp_strip_all_tags((string) $before_inner))
			? sprintf(
				'<span class="dsm-before-shuffle-text%2$s">%1$s</span>',
				$before_inner,
				'on' === $before_new_line ? ' dsm-text-newline' : ''
			)
			: '';

		$after_wrapped = '' !== trim(wp_strip_all_tags((string) $after_inner))
			? sprintf(
				'<span class="dsm-after-shuffle-text%2$s">%1$s</span>',
				$after_inner,
				'on' === $after_new_line ? ' dsm-text-newline' : ''
			)
			: '';

		wp_enqueue_script('dsm-baffle');
		wp_enqueue_script('dsm-shuffle-letter');

		$data_shuffle_chars = '' !== $shuffle_text_change ? esc_html($shuffle_text_change) : '';

		$container = sprintf(
			'<%1$s class="dsm-shuffle-letters et_pb_module_header">%2$s<span class="dsm-shuffle-text" data-dsm-shuffle-text="%5$s" data-dsm-shuffle-speed="%6$s" data-dsm-shuffle-duration="%7$s">%4$s</span>%3$s</%1$s>',
			$heading_tag,
			$before_wrapped,
			$after_wrapped,
			esc_html($title_plain),
			$data_shuffle_chars,
			esc_attr((string) $shuffle_text_speed),
			esc_attr((string) $shuffle_text_duration)
		);

		// 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 . $module_inner;

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