<?php

namespace DIFL\Server\Modules\BackgroundSwitcherItem;

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

use ET\Builder\Packages\Module\Module;
use ET\Builder\FrontEnd\BlockParser\BlockParserStore;
use ET\Builder\Packages\Module\Options\Element\ElementComponents;
use ET\Builder\Packages\Module\Options\Background\BackgroundVideoScriptData;
use DIFL\Server\Traits\IconRenderTrait;

trait RenderCallback {
	use Classnames;
	use Styles;
	use IconRenderTrait;

	/**
	 * Register element script data for the module so Divi's background-video
	 * playback (wp-mediaelement + the bg-video script) is wired up on the frontend.
	 *
	 * The video span is rendered inside .df_bg_switcher_bg (not as a direct child of
	 * the module wrapper), so the default background-video selector ("{module} >
	 * .et-pb-background-video") no longer matches. Re-register it for the relocated
	 * location so the frontend init can still find + play the video.
	 */
	public static function module_script_data($args) {
		$args['elements']->script_data(['attrName' => 'module']);

		BackgroundVideoScriptData::set([
			'id'            => $args['id'],
			'selector'      => $args['selector'] . ' .df_bg_switcher_bg',
			'attr'          => $args['attrs']['module']['decoration']['background'] ?? [],
			'storeInstance' => $args['storeInstance'],
		]);
	}

	public static function render_callback($attrs, $content, $block, $elements) {
		$parent       = BlockParserStore::get_parent($block->parsed_block['id'], $block->parsed_block['storeInstance']);
		$parent_attrs = $parent->attrs ?? [];

		// The panel background image/color/gradient comes from the bgsi_bg
		// (divi/background) decoration, painted on .df_bg_switcher_bg via CSS.
		$settings = $attrs['bgsi_settings']['innerContent']['desktop']['value'] ?? [];

		$title       = trim((string) ($settings['title'] ?? ''));
		$description  = (string) ($settings['description'] ?? '');

		// Title heading level comes from the parent's global Title font decoration.
		$title_tag    = $parent_attrs['title_font']['decoration']['font']['font']['desktop']['value']['headingLevel'] ?? 'h3';
		$allowed_tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'span', 'p'];
		if (!in_array($title_tag, $allowed_tags, true)) {
			$title_tag = 'h3';
		}

		// Optional title link (Content → Link group). When a URL is set, the title
		// text is wrapped in an <a>; "on" target opens in a new tab.
		$link        = $attrs['bgsi_link']['innerContent']['desktop']['value'] ?? [];
		$link_url    = trim((string) ($link['title_link_url'] ?? ''));
		$link_target = ('on' === ($link['title_link_target'] ?? 'off')) ? '_blank' : '_self';

		$title_inner = esc_html($title);
		if ('' !== $title && '' !== $link_url) {
			$rel         = '_blank' === $link_target ? ' rel="noopener noreferrer"' : '';
			$title_inner = sprintf(
				'<a href="%1$s" target="%2$s"%3$s>%4$s</a>',
				esc_url($link_url),
				esc_attr($link_target),
				$rel,
				esc_html($title)
			);
		}

		$title_html = '' !== $title
			? sprintf('<%1$s class="df_bg_switcher_item_title">%2$s</%1$s>', $title_tag, $title_inner)
			: '';

		// Optional icon/image above the title (Content → Icon/Image). Design comes from
		// the parent (.df_bg_switcher_icon); per-child color override is a separate group.
		$icon_settings = $attrs['bgsi_icon']['innerContent']['desktop']['value'] ?? [];
		$icon_html     = '';
		if ('on' === ($icon_settings['use_icon'] ?? 'off')) {
			if ('image' === ($icon_settings['icon_type'] ?? 'icon')) {
				// Image lives in its own attribute (bgsi_icon_image) so the upload's
				// syncImageData write can't reset the use_icon/icon_type siblings.
				$icon_image = $attrs['bgsi_icon_image']['innerContent']['desktop']['value']['icon_image'] ?? '';
				$img_src    = '' !== $icon_image ? $icon_image : plugins_url('Builder/assets/images/placeholder.svg', DIFL_MAIN_FILE_PATH);
				$icon_inner = sprintf(
					'<img class="df_bg_switcher_icon_img" src="%s" alt="%s" />',
					esc_url($img_src, ['http', 'https', 'data']),
					esc_attr($title)
				);
			} else {
				$icon_inner = self::render_icon($icon_settings['font_icon'] ?? '');
			}
			if ('' !== $icon_inner) {
				$icon_html = sprintf('<div class="df_bg_switcher_icon">%s</div>', $icon_inner);
			}
		}

		// Rich-text Description (Content → Description) — rendered below the title inside
		// .df_bg_switcher_elements_inner; nothing output when empty. Rich text is sanitized
		// on save, so it's emitted as-is (not esc_html).
		$desc_html = '' !== trim((string) $description)
			? sprintf('<div class="df_bg_switcher_item_desc">%s</div>', $description)
			: '';

		// Added elements (+ Add Element) — always wrapped so the hover reveal works
		// even before any element is added.
		$elements_html = !empty(trim((string) $content)) ? $content : '';

		// .df_bg_switcher_bg is painted by the native module Background (Background group)
		// via CSS. When no background (image/color/gradient) is configured, add the
		// --placeholder class so the default placeholder image shows (dropped as soon as
		// any bg is set).
		$bg     = $attrs['module']['decoration']['background']['desktop']['value'] ?? [];
		$has_bg = !empty($bg['image']['url'])
			|| !empty($bg['color'])
			|| (isset($bg['gradient']['enabled']) && 'on' === $bg['gradient']['enabled'])
			|| !empty($bg['video']['mp4'])
			|| !empty($bg['video']['webm']);
		$bg_class = $has_bg ? 'df_bg_switcher_bg' : 'df_bg_switcher_bg df_bg_switcher_bg--placeholder';

		// Divi's background elements (notably the background-video <span>) — rendered
		// INSIDE .df_bg_switcher_bg so the video lives in the (correctly sized) bg layer
		// and inherits its cross-fade. See module_script_data() for the matching selector.
		$bg_elements = ElementComponents::component(
			[
				'attrs'         => $attrs['module']['decoration'] ?? [],
				'id'            => $block->parsed_block['id'],
				'orderIndex'    => $block->parsed_block['orderIndex'],
				'storeInstance' => $block->parsed_block['storeInstance'],
			]
		);

		$item_html = sprintf(
			'<div class="df_bg_switcher_item" tabindex="0">
				<div class="df_bg_switcher_panel">
					<div class="df_bg_switcher_content">
						%5$s%1$s
						<div class="df_bg_switcher_elements"><div class="df_bg_switcher_elements_inner">%2$s</div></div>
					</div>
				</div>
			</div>
			<div class="%3$s">%4$s</div>',
			$title_html,
			$desc_html . $elements_html,
			esc_attr($bg_class),
			$bg_elements,
			$icon_html
		);

		return Module::render(
			[
				// FE only.
				'orderIndex'         => $block->parsed_block['orderIndex'],
				'storeInstance'      => $block->parsed_block['storeInstance'],

				// VB equivalent.
				'id'                 => $block->parsed_block['id'],
				'name'               => $block->block_type->name,
				'moduleCategory'     => $block->block_type->category,
				'attrs'              => $attrs,
				'elements'           => $elements,
				'classnamesFunction' => [self::class, 'classnames'],
				'stylesComponent'    => [self::class, 'styles'],
				'scriptDataComponent' => [self::class, 'module_script_data'],
				'parentAttrs'        => $parent_attrs,
				'parentId'           => $parent->id ?? '',
				'parentName'         => $parent->blockName ?? '',
				'children'           => $item_html,
			]
		);
	}
}
