<?php

namespace DIFL\Server\Modules\BackgroundSwitcher;

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

use ET\Builder\FrontEnd\BlockParser\BlockParserStore;
use ET\Builder\Packages\Module\Module;
use ET\Builder\Packages\Module\Options\Element\ElementComponents;

trait RenderCallback {
	use Classnames;
	use Styles;
	use ScriptData;

	public static function render_callback($attrs, $content, $block, $elements) {
		wp_enqueue_script('df_background_switcher');

		$children_ids = $block->parsed_block['innerBlocks'] ? array_map(
			function ($inner_block) {
				return $inner_block['id'];
			},
			$block->parsed_block['innerBlocks']
		) : [];

		$parent       = BlockParserStore::get_parent($block->parsed_block['id'], $block->parsed_block['storeInstance']);
		$parent_attrs = $parent->attrs ?? [];

		$settings       = $attrs['bgs_settings']['innerContent']['desktop']['value'] ?? [];
		$style_settings = $attrs['style_settings']['innerContent']['desktop']['value'] ?? [];

		$layout_type              = $settings['layout_type'] ?? 'flex';
		$bg_effect                = $settings['bg_effect'] ?? 'default';
		$content_mode             = $settings['content_mode'] ?? 'default';
		$anim_name                = $settings['anim_name'] ?? 'fadeIn';
		$content_position         = $style_settings['content_position'] ?? 'bottom';
		$enable_default_active    = $settings['enable_default_active'] ?? 'off';
		$default_active_item      = $settings['default_active_item'] ?? '1';

		// When enabled, pass the 1-based default-active index to the frontend script.
		// The script converts it to 0-based and clamps to the last item if it overflows.
		$data_attrs = '';
		if ( 'on' === $enable_default_active ) {
			$data_attrs = sprintf( ' data-default-active="%s"', esc_attr( $default_active_item ) );
		}

		// When autoplay is on, pass its config as a JSON data-settings blob (mirrors the
		// Interactive Circle module). Autoplay advances in natural item order for every
		// layout, so no layout/column info is needed here.
		$enable_autoplay = $settings['enable_autoplay'] ?? 'off';
		if ( 'on' === $enable_autoplay ) {
			$autoplay_settings = [
				'enable_autoplay'         => 'on',
				'autoplay_speed'          => $settings['autoplay_speed'] ?? '3000',
				'autoplay_interval'       => $settings['autoplay_interval'] ?? '0',
				'autoplay_pause_on_hover'   => $settings['autoplay_pause_on_hover'] ?? 'on',
				'enable_border_progress'    => $settings['enable_border_progress'] ?? 'off',
				'border_progress_direction' => $settings['border_progress_direction'] ?? 'clockwise',
			];
			$data_attrs .= sprintf( " data-settings='%s'", esc_attr( wp_json_encode( $autoplay_settings ) ) );
		}

		$wrapper_class = sprintf(
			'df_bg_switcher df_bg_switcher--%s df_bg_switcher--content-%s df_bg_switcher--effect-%s df_bg_switcher--content-mode-%s',
			esc_attr($layout_type),
			esc_attr($content_position),
			esc_attr($bg_effect),
			esc_attr($content_mode)
		);

		// Animation class applies only to the always/hover visibility modes — mirror edit.jsx.
		if ('always' === $content_mode || 'hover' === $content_mode) {
			$wrapper_class .= ' df_bg_switcher--anim-' . esc_attr($anim_name);
		}

		if (empty($children_ids)) {
			// Empty state needs the layout class for its display context: base
			// .df_bg_switcher has no `display`; only --flex/--grid provide it.
			$switcher_html = sprintf(
				'<div class="df_bg_switcher df_bg_switcher--%s"><div class="difl__empty"><div class="difl__empty__message"><span class="difl__empty__message__text">No items yet. Add a new item to get started.</span></div></div></div>',
				esc_attr($layout_type)
			);
		} else {
			$switcher_html = sprintf(
				'<div class="%s"%s>%s</div>',
				$wrapper_class,
				$data_attrs,
				$content ?: ''
			);
		}

		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'],
				'scriptDataComponent' => [self::class, 'script_data'],
				'stylesComponent'     => [self::class, 'styles'],
				'parentAttrs'         => $parent_attrs,
				'parentId'            => $parent->id ?? '',
				'parentName'          => $parent->blockName ?? '',
				'children'            => ElementComponents::component(
					[
						'attrs'         => $attrs['module']['decoration'] ?? [],
						'id'            => $block->parsed_block['id'],
						'orderIndex'    => $block->parsed_block['orderIndex'],
						'storeInstance' => $block->parsed_block['storeInstance'],
					]
				) . $switcher_html,
				'childrenIds'         => $children_ids,
			]
		);
	}
}
