<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Sifency\Classes\Sifency_Addons_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Image_Size;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Icons_Manager;
use Elementor\Utils;
use Elementor\Plugin as ElementorPlugin;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Icon_Style_Controls;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Item_Style_Controls;
use Sifency\Traits\Sifency_Addons_Help_Controls;

class Sifency_Advanced_Marquee_Scroll_Direction extends Sifency_Addons_Widget_Base {
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Icon_Style_Controls;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Addons_Item_Style_Controls;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-advanced-marquee',
			'title'          => 'Sifency Interactive Marquee',
			'icon'           => 'eicon-exchange',
			'category'       => array( 'sifency-creative-widgets' ),
			'script_depends' => array( 'lenis', 'gsap', 'gsap-scrolltrigger', 'sifency-marquee-scroll-direction-script' ),
			'style_depends'  => array( 'sifency-creative-style' ),
			'keywords'       => array( 'marquee', 'ticker', 'scrolling text', 'gsap', 'interactive', 'template', 'image' ),
		);
	}
	// ─────────────────────────────────────────────────────────────────────────────
	// Controls
	// ─────────────────────────────────────────────────────────────────────────────

	protected function register_controls() {

		// ── Content Type ────────────────────────────────────────────────────────
		$this->start_controls_section(
			'section_content_type',
			array( 'label' => esc_html__( 'Item Type', 'sifency-addons' ) )
		);

		$this->add_control(
			'item_content_type',
			array(
				'label'   => esc_html__( 'Item Content Type', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'text_icon',
				'options' => array(
					'text_icon' => esc_html__( 'Text + Icon', 'sifency-addons' ),
					'rich_text' => esc_html__( 'Rich Text (WP Editor)', 'sifency-addons' ),
					'image'     => esc_html__( 'Image', 'sifency-addons' ),
					'template'  => esc_html__( 'Elementor Template', 'sifency-addons' ),
					'mixed'     => esc_html__( 'Mixed (per-item control)', 'sifency-addons' ),
				),
			)
		);

		$this->end_controls_section();

		// ── Repeater Items ───────────────────────────────────────────────────────
		$this->start_controls_section(
			'section_content',
			array( 'label' => esc_html__( 'Marquee Items', 'sifency-addons' ) )
		);

		$repeater = new Repeater();

		// ── Per-item type (visible only in "mixed" mode, but always stored) ─────
		$repeater->add_control(
			'item_type',
			array(
				'label'   => esc_html__( 'Type', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'text_icon',
				'options' => array(
					'text_icon' => esc_html__( 'Text + Icon', 'sifency-addons' ),
					'rich_text' => esc_html__( 'Rich Text', 'sifency-addons' ),
					'image'     => esc_html__( 'Image', 'sifency-addons' ),
					'template'  => esc_html__( 'Elementor Template', 'sifency-addons' ),
				),
			)
		);

		// ── Text + Icon ──────────────────────────────────────────────────────────
		$repeater->add_control(
			'item_text',
			array(
				'label'       => esc_html__( 'Text', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'MODERN DESIGN', 'sifency-addons' ),
				'label_block' => true,
				'condition'   => array( 'item_type' => 'text_icon' ),
			)
		);

		$repeater->add_control(
			'item_icon',
			array(
				'label'     => esc_html__( 'Separator Icon', 'sifency-addons' ),
				'type'      => Controls_Manager::ICONS,
				'default'   => array(
					'value'   => 'fas fa-star',
					'library' => 'fa-solid',
				),
				'condition' => array( 'item_type' => 'text_icon' ),
			)
		);

		// ── Rich Text (WP Editor) ────────────────────────────────────────────────
		$repeater->add_control(
			'item_rich_text',
			array(
				'label'     => esc_html__( 'Rich Text', 'sifency-addons' ),
				'type'      => Controls_Manager::WYSIWYG,
				'default'   => '<p><strong>Bold Statement</strong> with <em>styled</em> content.</p>',
				'condition' => array( 'item_type' => 'rich_text' ),
			)
		);

		// ── Image ────────────────────────────────────────────────────────────────
		$repeater->add_control(
			'item_image',
			array(
				'label'     => esc_html__( 'Image', 'sifency-addons' ),
				'type'      => Controls_Manager::MEDIA,
				'default'   => array( 'url' => Utils::get_placeholder_image_src() ),
				'condition' => array( 'item_type' => 'image' ),
			)
		);

		$repeater->add_control(
			'item_image_alt',
			array(
				'label'     => esc_html__( 'Image Alt Text', 'sifency-addons' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => '',
				'condition' => array( 'item_type' => 'image' ),
			)
		);

		$repeater->add_control(
			'item_image_link',
			array(
				'label'     => esc_html__( 'Image Link (optional)', 'sifency-addons' ),
				'type'      => Controls_Manager::URL,
				'condition' => array( 'item_type' => 'image' ),
			)
		);

		// ── Elementor Template ───────────────────────────────────────────────────
		$repeater->add_control(
			'item_template_id',
			array(
				'label'       => esc_html__( 'Choose Template', 'sifency-addons' ),
				'type'        => Controls_Manager::SELECT,
				'options'     => function_exists( 'sifency_addons_get_elementor_templates' ) ? sifency_addons_get_elementor_templates() : array(),
				'default'     => 0,
				'label_block' => true,
				'condition'   => array( 'item_type' => 'template' ),
				'description' => esc_html__( 'Templates are built in Elementor → Templates → Saved Templates.', 'sifency-addons' ),
			)
		);

		// ── Shared per-item options ───────────────────────────────────────────────
		$repeater->add_control(
			'item_link',
			array(
				'label'       => esc_html__( 'Item Link (optional)', 'sifency-addons' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => 'https://...',
				'condition'   => array( 'item_type!' => 'image' ), // image has its own link
			)
		);

		$repeater->add_control(
			'item_custom_class',
			array(
				'label'       => esc_html__( 'Custom CSS Class', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXT,
				'placeholder' => 'my-custom-class',
			)
		);

		$this->add_control(
			'marquee_items',
			array(
				'label'       => esc_html__( 'Items', 'sifency-addons' ),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater->get_controls(),
				'default'     => array(
					array(
						'item_type' => 'text_icon',
						'item_text' => 'AWWWARDS WINNING',
					),
					array(
						'item_type' => 'text_icon',
						'item_text' => 'SMOOTH SCROLL',
					),
					array(
						'item_type' => 'text_icon',
						'item_text' => 'GSAP POWERED',
					),
				),
				'title_field' => '{{{ item_text || item_type }}}',
			)
		);

		$this->end_controls_section();

		// ── Image Size (shown when any item uses image) ──────────────────────────
		$this->start_controls_section(
			'section_image_settings',
			array(
				'label'     => esc_html__( 'Image Settings', 'sifency-addons' ),
				'condition' => array( 'item_content_type' => array( 'image', 'mixed' ) ),
			)
		);

		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			array(
				'name'    => 'marquee_image',
				'default' => 'medium',
			)
		);

		$this->add_responsive_control(
			'image_height',
			array(
				'label'      => esc_html__( 'Image Height', 'sifency-addons' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'vh', 'em' ),
				'range'      => array(
					'px' => array(
						'min' => 20,
						'max' => 600,
					),
				),
				'default'    => array(
					'unit' => 'px',
					'size' => 80,
				),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-marquee-image img' => 'height: {{SIZE}}{{UNIT}}; width: auto; object-fit: contain;',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'image_border',
				'selector' => '{{WRAPPER}} .sifency-marquee-image img',
			)
		);

		$this->add_control(
			'image_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'sifency-addons' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-marquee-image img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'image_box_shadow',
				'selector' => '{{WRAPPER}} .sifency-marquee-image img',
			)
		);

		$this->end_controls_section();

		// ── Template Settings ────────────────────────────────────────────────────
		$this->start_controls_section(
			'section_template_settings',
			array(
				'label'     => esc_html__( 'Template Settings', 'sifency-addons' ),
				'condition' => array( 'item_content_type' => array( 'template', 'mixed' ) ),
			)
		);

		$this->add_responsive_control(
			'template_min_width',
			array(
				'label'      => esc_html__( 'Template Min Width', 'sifency-addons' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'vw', '%' ),
				'range'      => array(
					'px' => array(
						'min' => 50,
						'max' => 1200,
					),
				),
				'default'    => array(
					'unit' => 'px',
					'size' => 300,
				),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-marquee-template' => 'min-width: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'template_edit_notice',
			array(
				'type'        => Controls_Manager::NOTICE,
				'notice_type' => 'info',
				'heading'     => esc_html__( 'Editing Templates', 'sifency-addons' ),
				'content'     => esc_html__( 'Edit templates via Elementor → Templates → Saved Templates. Changes reflect here automatically.', 'sifency-addons' ),
			)
		);

		$this->end_controls_section();

		// ── Behavior Settings ────────────────────────────────────────────────────
		$this->start_controls_section(
			'section_settings',
			array( 'label' => esc_html__( 'Behavior Settings', 'sifency-addons' ) )
		);

		$this->add_control(
			'base_speed',
			array(
				'label'   => esc_html__( 'Base Speed', 'sifency-addons' ),
				'type'    => Controls_Manager::SLIDER,
				'range'   => array(
					'px' => array(
						'min'  => 1,
						'max'  => 20,
						'step' => 1,
					),
				),
				'default' => array( 'size' => 5 ),
			)
		);

		$this->add_control(
			'initial_direction',
			array(
				'label'   => esc_html__( 'Initial Direction', 'sifency-addons' ),
				'type'    => Controls_Manager::CHOOSE,
				'options' => array(
					'rtl' => array(
						'title' => 'Right to Left',
						'icon'  => 'eicon-arrow-left',
					),
					'ltr' => array(
						'title' => 'Left to Right',
						'icon'  => 'eicon-arrow-right',
					),
				),
				'default' => 'rtl',
			)
		);

		$this->add_control(
			'interactive_scroll',
			array(
				'label'       => esc_html__( 'Interactive Scroll', 'sifency-addons' ),
				'type'        => Controls_Manager::SWITCHER,
				'default'     => 'yes',
				'description' => esc_html__( 'Changes direction on scroll up/down and accelerates on fast scroll.', 'sifency-addons' ),
			)
		);

		$this->add_control(
			'pause_on_hover',
			array(
				'label'   => esc_html__( 'Pause on Hover', 'sifency-addons' ),
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);

		$this->add_responsive_control(
			'item_gap',
			array(
				'label'      => esc_html__( 'Gap Between Items', 'sifency-addons' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'vw' ),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-marquee-content' => 'gap: {{SIZE}}{{UNIT}}; padding-right: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();

		// ── Help / Typography / Icon ─────────────────────────────────────────────
		$this->add_sifency_addons_help_controls();
		$this->add_sifency_addons_item_style_controls(
			array(
				'selector' => '.sifency-marquee-item',
				'exclude'  => array( 'tabs', 'transition' ),
			)
		);

		$this->add_sifency_addons_master_typography_controls(
			array(
				'selector'  => '.sifency-marquee-text',
				'exclude'   => array( 'tabs', 'transition', 'alignment' ),
				'condition' => array( 'item_content_type' => 'text_icon' ),
			)
		);

		$this->add_sifency_addons_icon_style_controls(
			array(
				'selector'       => '.sifency-marquee-icon',
				'hover_selector' => '.sifency-marquee-item:hover .sifency-marquee-icon',
				'condition'      => array( 'item_content_type' => 'text_icon' ),
			)
		);

		$this->add_sifency_addons_image_style_controls(
			array(
				'prefix'    => 'img_',
				'selector'  => '.sifency-marquee-image img',
				'selectors' => array(
					'image'     => '.sifency-marquee-image img',
					'dimension' => '.sifency-marquee-image img',
					'container' => '.sifency-marquee-image img',
				),
				'condition' => array( 'item_content_type' => 'image' ),
			)
		);
	}

	// ─────────────────────────────────────────────────────────────────────────────
	// Render helpers
	// ─────────────────────────────────────────────────────────────────────────────

	/**
	 * Render a single repeater item based on its resolved type.
	 */
	private function _render_item( array $item, string $global_type, array $image_settings ): void {
		// In "mixed" mode each item drives its own type; otherwise the global type wins.
		$type = ( $global_type === 'mixed' ) ? ( $item['item_type'] ?? 'text_icon' ) : $global_type;

		$custom_class = ! empty( $item['item_custom_class'] )
			? ' ' . esc_attr( $item['item_custom_class'] )
			: '';

		$repeater_class = 'elementor-repeater-item-' . esc_attr( $item['_id'] );

		// Resolve shared link (text_icon / rich_text / template)
		$link_open = $link_close = '';
		if ( $type !== 'image' && ! empty( $item['item_link']['url'] ) ) {
			$link_tag = 'a href="' . esc_url( $item['item_link']['url'] ) . '"';
			if ( ! empty( $item['item_link']['is_external'] ) ) {
				$link_tag .= ' target="_blank"';
			}
			if ( ! empty( $item['item_link']['nofollow'] ) ) {
				$link_tag .= ' rel="nofollow"';
			}
			$link_open  = '<' . $link_tag . ' class="sifency-marquee-link">';
			$link_close = '</a>';
		}

		echo '<div class="sifency-marquee-item ' . esc_attr( $repeater_class ) . esc_attr( $custom_class ) . '" data-type="' . esc_attr( $type ) . '">';

		switch ( $type ) {

			// ── Text + Icon ───────────────────────────────────────────────────
			case 'text_icon':
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped HTML link tag
				echo $link_open;
				if ( ! empty( $item['item_text'] ) ) {
					echo '<span class="sifency-marquee-text">' . esc_html( $item['item_text'] ) . '</span>';
				}
				if ( ! empty( $item['item_icon']['value'] ) ) {
					echo '<span class="sifency-marquee-icon" aria-hidden="true">';
					Icons_Manager::render_icon( $item['item_icon'], array( 'aria-hidden' => 'true' ) );
					echo '</span>';
				}
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped HTML link tag
				echo $link_close;
				break;

			// ── Rich Text (WP Editor / WYSIWYG) ──────────────────────────────
			case 'rich_text':
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped HTML link tag
				echo $link_open;
				if ( ! empty( $item['item_rich_text'] ) ) {
					echo '<div class="sifency-marquee-rich-text">';
					// wp_kses_post preserves safe HTML tags (strong, em, a, br, etc.)
					echo wp_kses_post( $item['item_rich_text'] );
					echo '</div>';
				}
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped HTML link tag
				echo $link_close;
				break;

			// ── Image ─────────────────────────────────────────────────────────
			case 'image':
				if ( ! empty( $item['item_image']['id'] ) || ! empty( $item['item_image']['url'] ) ) {
					$img_link_open = $img_link_close = '';
					if ( ! empty( $item['item_image_link']['url'] ) ) {
						$a = 'a href="' . esc_url( $item['item_image_link']['url'] ) . '"';
						if ( ! empty( $item['item_image_link']['is_external'] ) ) {
							$a .= ' target="_blank"';
						}
						if ( ! empty( $item['item_image_link']['nofollow'] ) ) {
							$a .= ' rel="nofollow"';
						}
						$img_link_open  = '<' . $a . '>';
						$img_link_close = '</a>';
					}

					$alt = ! empty( $item['item_image_alt'] )
						? esc_attr( $item['item_image_alt'] )
						: ( ! empty( $item['item_image']['alt'] ) ? esc_attr( $item['item_image']['alt'] ) : '' );

					echo '<span class="sifency-marquee-image">';
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped HTML link tag
					echo $img_link_open;

					if ( ! empty( $item['item_image']['id'] ) ) {
						// Use Elementor's image-size group for proper srcset
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor image attachment markup
						echo wp_kses_post(
							Group_Control_Image_Size::get_attachment_image_html(
								array_merge( $image_settings, array( 'image' => $item['item_image'] ) ),
								'marquee_image',
								'image'
							)
						);
					} else {
						echo '<img src="' . esc_url( $item['item_image']['url'] ) . '" alt="' . esc_attr( $alt ) . '" loading="lazy">';
					}

                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped HTML link tag
					echo $img_link_close;
					echo '</span>';
				}
				break;

			// ── Elementor Template ────────────────────────────────────────────
			case 'template':
				$template_id = absint( $item['item_template_id'] ?? 0 );
				if ( $template_id > 0 ) {
					echo '<div class="sifency-marquee-template">';
					// Render template — disable scripts/styles injection inside marquee
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor builder template output
					echo ElementorPlugin::instance()->frontend->get_builder_content_for_display(
						$template_id,
						false // $with_css — avoid style tag duplication
					);
					echo '</div>';
				} elseif ( ElementorPlugin::$instance->editor->is_edit_mode() ) {
						echo '<div class="sifency-marquee-template sifency-template-placeholder">';
						echo '<span>' . esc_html__( 'No template selected — choose one in the repeater.', 'sifency-addons' ) . '</span>';
						echo '</div>';
				}
				break;
		}

		echo '</div>'; // .sifency-marquee-item
	}

	// ─────────────────────────────────────────────────────────────────────────────
	// Render
	// ─────────────────────────────────────────────────────────────────────────────

	protected function render_dom( array $context ) {
		$settings    = $this->get_settings_for_display();
		$wrapper_id  = esc_attr( $context['dom_id'] );
		$items       = $settings['marquee_items'] ?? array();
		$global_type = $settings['item_content_type'] ?? 'text_icon';

		if ( empty( $items ) ) {
			return;
		}

		// Image size settings passed down to each item renderer
		$image_settings = array(
			'marquee_image_size'             => $settings['marquee_image_size'] ?? 'medium',
			'marquee_image_custom_dimension' => $settings['marquee_image_custom_dimension'] ?? array(),
		);

		$data_attrs = implode(
			' ',
			array(
				'data-speed="' . esc_attr( $settings['base_speed']['size'] ?? 5 ) . '"',
				'data-dir="' . esc_attr( $settings['initial_direction'] ?? 'rtl' ) . '"',
				'data-interactive="' . ( $settings['interactive_scroll'] === 'yes' ? 'true' : 'false' ) . '"',
				'data-pause-hover="' . ( ( $settings['pause_on_hover'] ?? 'yes' ) === 'yes' ? 'true' : 'false' ) . '"',
				'data-type="' . esc_attr( $global_type ) . '"',
			)
		);

		// Closure renders one full pass of items (called twice for seamless loop)
		$render_pass = function () use ( $items, $global_type, $image_settings ): void {
			echo '<div class="sifency-marquee-content">';
			foreach ( $items as $item ) {
				$this->_render_item( $item, $global_type, $image_settings );
			}
			echo '</div>';
		};

		?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>"
			class="sifency-marquee-wrapper"
             <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped data attributes
				echo $data_attrs;
				?>
			role="marquee"
			aria-label="<?php esc_attr_e( 'Scrolling content', 'sifency-addons' ); ?>">

			<div class="sifency-marquee-track">
				<?php
				$render_pass(); // original pass
				$render_pass(); // duplicate pass for seamless infinite loop
				?>
			</div>

		</div>
		<?php
	}
}
