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

use Sifency\Classes\Sifency_Addons_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Sifency\Traits\Sifency_Addons_Help_Controls;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Custom_CSS_Controls;

class Sifency_Staggered_Text extends Sifency_Addons_Widget_Base {
	use Sifency_Addons_Help_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Custom_CSS_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-staggered-text',
			'title'          => 'Sifency Animated Headline',
			'icon'           => 'eicon-animation-text',
			'category'       => array( 'sifency-creative-widgets' ),
			'script_depends' => array( 'gsap', 'gsap-scrolltrigger', 'sifency-stagger-text-script' ),
			'style_depends'  => array( 'sifency-sun-style' ),
			'keywords'       => array( 'text', 'reveal', 'stagger', 'letters', 'scale', 'animation' ),
		);
	}

	protected function register_controls() {
		// --- Content Section ---
		$this->start_controls_section(
			'section_content',
			array( 'label' => esc_html__( 'Headline Content', 'sifency-addons' ) )
		);

		$source_options = array(
			'custom'       => esc_html__( 'Custom Text (Static)', 'sifency-addons' ),
			'post_title'   => esc_html__( 'Post Title', 'sifency-addons' ),
			'the_excerpt'  => esc_html__( 'Post Excerpt', 'sifency-addons' ),
			'the_content'  => esc_html__( 'Post Content (Limited)', 'sifency-addons' ),
			'archive'      => esc_html__( 'Archive Title', 'sifency-addons' ),
			'site_title'   => esc_html__( 'Site Title', 'sifency-addons' ),
			'site_tagline' => esc_html__( 'Site Tagline', 'sifency-addons' ),
		);
		if ( function_exists( 'get_field' ) ) {
			$source_options['acf_field'] = esc_html__( 'ACF Field', 'sifency-addons' );
		}

		$this->add_control(
			'title_source',
			array(
				'label'   => esc_html__( 'Source', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => $source_options,
				'default' => 'custom',
			)
		);

		$this->add_control(
			'headline_text',
			array(
				'label'       => esc_html__( 'Text', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXTAREA,
				'default'     => esc_html__( 'CunnetAgency', 'sifency-addons' ),
				'description' => 'The JS will automatically split this into animated letters.',
				'condition'   => array( 'title_source' => 'custom' ),
			)
		);

		$this->add_control(
			'acf_field_name',
			array(
				'label'       => esc_html__( 'ACF Field Name', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXT,
				'condition'   => array( 'title_source' => 'acf_field' ),
				'description' => esc_html__( 'Enter the ACF field key (e.g., my_custom_field).', 'sifency-addons' ),
			)
		);

		$this->add_control(
			'excerpt_length',
			array(
				'label'       => esc_html__( 'Excerpt Length (Words)', 'sifency-addons' ),
				'type'        => Controls_Manager::NUMBER,
				'default'     => 20,
				'condition'   => array( 'title_source' => array( 'the_content', 'the_excerpt' ) ),
				'description' => esc_html__( 'Controls the number of words shown.', 'sifency-addons' ),
			)
		);

		$this->add_control(
			'link',
			array(
				'label'       => esc_html__( 'Link', 'sifency-addons' ),
				'type'        => Controls_Manager::URL,
				'dynamic'     => array(
					'active' => true,
				),
				'placeholder' => esc_html__( 'https://your-link.com', 'sifency-addons' ),
				'default'     => array(
					'url' => '',
				),
			)
		);

		$this->add_control(
			'html_tag',
			array(
				'label'   => esc_html__( 'HTML Tag', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'h1'   => 'H1',
					'h2'   => 'H2',
					'h3'   => 'H3',
					'h4'   => 'H4',
					'h5'   => 'H5',
					'h6'   => 'H6',
					'p'    => 'p',
					'div'  => 'div',
					'span' => 'span',
				),
				'default' => 'h2',
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_animation',
			array( 'label' => esc_html__( 'Animation Settings', 'sifency-addons' ) )
		);

		$this->add_control(
			'anim_type',
			array(
				'label'   => esc_html__( 'Animation Style', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'reveal'           => 'Mask Reveal (Slide Up)',
					'scale'            => 'Scale & Fade In',

					// ── 1. Classic Fades & Slides ──────────────────────────
					'fade-in'          => 'Fade In',
					'fade-up'          => 'Fade Up',
					'fade-down'        => 'Fade Down',
					'slide-left'       => 'Slide In Left',
					'slide-right'      => 'Slide In Right',

					// ── 2. Reveals & Masking ───────────────────────────────
					'mask-up'          => 'Mask Reveal (Slide Up)',
					'mask-down'        => 'Mask Reveal (Slide Down)',
					'mask-left'        => 'Mask Reveal (Slide Left)',
					'mask-right'       => 'Mask Reveal (Slide Right)',
					'blur-in'          => 'Blur In Reveal',
					'wipe-right'       => 'Wipe Reveal Right',
					'curtain-open'     => 'Curtain Open',
					'venetian-blinds'  => 'Venetian Blinds',
					'paint-brush'      => 'Paint Brush Stroke',

					// ── 3. Typography & Styles ─────────────────────────────
					'typewriter'       => 'Typewriter Effect',
					'zoom-in'          => 'Zoom In / Scale',
					'zoom-out'         => 'Zoom Out',
					'letter-spacing'   => 'Letter Spacing Contract',
					'stamp-in'         => 'Stamp Impact',
					'uppercase-slam'   => 'Uppercase Slam Down',
					'italic-slide'     => 'Italic Slide In',
					'ticker-tape'      => 'Ticker Tape',
					'weight-shift'     => 'Weight Shift',

					// ── 4. 3D & Perspective ────────────────────────────────
					'flip-x'           => '3D Flip X',
					'flip-y'           => '3D Flip Y',
					'flip-z'           => '3D Flip Z Axis',
					'rotate-3d'        => '3D Rotate & Twist',
					'perspective-tilt' => 'Perspective Tilt',
					'swing'            => 'Swing In',
					'cube-rotate'      => 'Cube Rotate In',
					'card-flip'        => 'Card Flip In',
					'fold-in'          => 'Paper Fold In',
					'casino-flip'      => 'Casino Barrel Roll',
					'depth-emerge'     => 'Depth Emerge',
					'depth-blur'       => 'Depth Blur In',
					'tunnel-in'        => 'Tunnel Zoom In',

					// ── 5. Physics & Staggered ─────────────────────────────
					'bounce-in'        => 'Bounce In',
					'elastic-drop'     => 'Elastic Drop',
					'rubber-band'      => 'Rubber Band',
					'jello'            => 'Jello Effect',
					'gravity-fall'     => 'Gravity Fall',
					'pendulum'         => 'Pendulum Swing',
					'slingshot'        => 'Slingshot Launch',
					'ricochet'         => 'Ricochet Bounce',
					'slot-machine'     => 'Slot Machine Drop',
					'pop-bounce'       => 'Pop & Bounce',
					'spring-pop'       => 'Spring Pop',
					'heartbeat'        => 'Heartbeat Entrance',

					// ── 6. Wave & Rhythm ───────────────────────────────────
					'wave-up'          => 'Wave Rise (Sine)',
					'wave-down'        => 'Wave Fall (Sine)',
					'ripple'           => 'Ripple Expand',
					'pulse-in'         => 'Pulse In',

					// ── 7. Futuristic / Sci-Fi ─────────────────────────────
					'neon-flicker'     => '⚡ Neon Light Flicker',
					'neon-on'          => '⚡ Neon Power On',
					'cyber-glitch'     => '⚡ Cyberpunk Glitch',
					'hologram'         => '⚡ Hologram Materialize',
					'matrix-rain'      => '⚡ Matrix Rain Drop',
					'circuit-trace'    => '⚡ Circuit Board Trace',
					'pixel-dissolve'   => '⚡ Pixel Dissolve',
					'scan-line'        => '⚡ Scan Line Reveal',
					'data-stream'      => '⚡ Data Stream In',
					'quantum-leap'     => '⚡ Quantum Leap',
					'warp-drive'       => '⚡ Warp Drive In',
					'energy-surge'     => '⚡ Energy Surge',

					// ── 8. Light & Energy ──────────────────────────────────
					'light-speed'      => '✦ Light Speed In',
					'flash-in'         => '✦ Flash Bang In',
					'glow-pulse'       => '✦ Glow Pulse In',

					// ── 9. Particle / Organic ──────────────────────────────
					'shatter'          => '✦ Shatter Assemble',
					'implode'          => '✦ Implode Assemble',
					'explode-in'       => '✦ Explode Together',
					'smoke-rise'       => '✦ Smoke Rise',
					'liquid-flow'      => '✦ Liquid Flow In',
					'dust-settle'      => '✦ Dust Settle',
					'orbit-in'         => '✦ Orbit In',
					'spiral-in'        => '✦ Spiral In',
					'vortex'           => '✦ Vortex Spin',
					'magnetic-pull'    => '✦ Magnetic Pull',
					'rise-spin'        => '✦ Rise & Spin',

					// ── 10. Creative & Artistic ────────────────────────────
					'glitch-in'        => 'Glitch In (Opacity/X)',
					'wobble'           => 'Wobble Drop',
					'random-scatter'   => 'Random Scatter',
					'morph-in'         => 'Morph Scale In',
					'shockwave'        => 'Shockwave Burst',
					'dissolve-up'      => 'Dissolve Up',
					'fall-rotate'      => 'Fall & Rotate',
					'stretch-x'        => 'Stretch X Elastic',
					'stretch-y'        => 'Stretch Y Elastic',
					'wind-sweep'       => 'Wind Sweep',
					'retro-fade'       => 'Retro Fade',
					'slide-up-fade'    => 'Slide Up + Blur Fade',
					'slide-down-fade'  => 'Slide Down + Blur Fade',
				),
				'default' => 'reveal',
			)
		);
		$this->add_control(
			'split_type',
			array(
				'label'   => esc_html__( 'Split By', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'chars' => 'Characters (Letters)',
					'words' => 'Words',
				),
				'default' => 'chars',
			)
		);
		$this->add_control(
			'stagger_speed',
			array(
				'label'       => esc_html__( 'Stagger Delay (s)', 'sifency-addons' ),
				'type'        => Controls_Manager::SLIDER,
				'range'       => array(
					'px' => array(
						'min'  => 0.01,
						'max'  => 0.2,
						'step' => 0.01,
					),
				),
				'default'     => array( 'size' => 0.03 ),
				'description' => 'Delay between each letter animating.',
			)
		);

		$this->add_control(
			'anim_duration',
			array(
				'label'     => esc_html__( 'Animation Duration (s)', 'sifency-addons' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min'  => 0.5,
						'max'  => 5,
						'step' => 0.1,
					),
				),
				'default'   => array( 'size' => 1 ),
				'condition' => array( 'scrub_enabled!' => 'yes' ),
			)
		);

		$this->add_control(
			'anim_ease',
			array(
				'label'   => esc_html__( 'Easing', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'power3.out'          => 'Power 3 Out (Smooth)',
					'power4.out'          => 'Power 4 Out (Strong)',
					'expo.out'            => 'Expo Out (Cinematic)',
					'back.out(1.7)'       => 'Back Out (Pop)',
					'elastic.out(1, 0.3)' => 'Elastic Out',
					'none'                => 'Linear',
				),
				'default' => 'power3.out',
			)
		);

		$this->add_control(
			'stagger_from',
			array(
				'label'   => esc_html__( 'Stagger Direction', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'start'  => 'Start',
					'end'    => 'End',
					'center' => 'Center',
					'edges'  => 'Edges',
					'random' => 'Random',
				),
				'default' => 'start',
			)
		);

		$this->add_control(
			'hr_scroll',
			array( 'type' => Controls_Manager::DIVIDER )
		);

		$this->add_control(
			'scrub_enabled',
			array(
				'label'        => esc_html__( 'Scrub Animation', 'sifency-addons' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'sifency-addons' ),
				'label_off'    => esc_html__( 'No', 'sifency-addons' ),
				'return_value' => 'yes',
				'default'      => '',
				'description'  => 'Animation progress tied to scroll position.',
			)
		);

		$this->add_control(
			'scrub_speed',
			array(
				'label'     => esc_html__( 'Scrub Smoothing', 'sifency-addons' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min'  => 0.1,
						'max'  => 3,
						'step' => 0.1,
					),
				),
				'default'   => array( 'size' => 1 ),
				'condition' => array( 'scrub_enabled' => 'yes' ),
			)
		);

		$this->add_control(
			'scroll_start',
			array(
				'label'       => esc_html__( 'Viewport Start (%)', 'sifency-addons' ),
				'type'        => Controls_Manager::SLIDER,
				'range'       => array(
					'px' => array(
						'min' => 0,
						'max' => 100,
					),
				),
				'default'     => array( 'size' => 90 ),
				'description' => 'Animation triggers when element reaches this % of viewport.',
			)
		);

		$this->add_control(
			'anim_repeat',
			array(
				'label'        => esc_html__( 'Repeat Animation', 'sifency-addons' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'sifency-addons' ),
				'label_off'    => esc_html__( 'No', 'sifency-addons' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'description'  => 'Restart animation when scrolling back up.',
				'condition'    => array( 'scrub_enabled!' => 'yes' ),
			)
		);

		$this->end_controls_section();
		$this->add_sifency_addons_master_typography_controls(
			array(
				'label'           => esc_html__( 'Typography', 'sifency-addons' ),
				'selector'        => '.sifency-anim-heading',
				'show_blend_mode' => true,
				'exclude'         => array( 'tabs', 'bg', 'radius', 'border', 'transition' ),
			)
		);

		$this->add_sifency_addons_custom_css_controls();
	}

	protected function render_dom( array $context ) {
		$this->sifency_addons_render_custom_css();
		$settings   = $this->get_settings_for_display();
		$wrapper_id = esc_attr( $context['dom_id'] );

		$text = '';
		if ( function_exists( 'sifency_addons_get_dynamic_text' ) ) {
			// Map headline_text to heading_text for custom fallback function compatibility
			if ( ! isset( $settings['heading_text'] ) && isset( $settings['headline_text'] ) ) {
				$settings['heading_text'] = $settings['headline_text'];
			}
			$text = sifency_addons_get_dynamic_text(
				$settings,
				array(
					'excerpt_length' => $settings['excerpt_length'] ?? 20,
				)
			);
		} else {
			$text = $settings['headline_text'];
		}

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

		$tag       = tag_escape( $settings['html_tag'] );
		$anim_type = $settings['anim_type'];

		$config = array(
			'stagger'      => $settings['stagger_speed']['size'] ?? 0.03,
			'stagger_from' => $settings['stagger_from'],
			'duration'     => $settings['anim_duration']['size'] ?? 1,
			'ease'         => $settings['anim_ease'],
			'type'         => $anim_type,
			'split'        => $settings['split_type'],
			'scrub'        => $settings['scrub_enabled'] === 'yes' ? ( $settings['scrub_speed']['size'] ?? 1 ) : false,
			'repeat'       => $settings['anim_repeat'] === 'yes',
			'start'        => $settings['scroll_start']['size'] ?? 90,
		);

		if ( ! empty( $settings['link']['url'] ) ) {
			$this->add_link_attributes( 'link', $settings['link'] );
		}

		?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>" class="sifency-anim-heading-wrapper">
			
			<<?php echo tag_escape( $tag ); ?> class="sifency-anim-heading" data-config='<?php echo esc_attr( wp_json_encode( $config ) ); ?>'>
				<?php if ( ! empty( $settings['link']['url'] ) ) : ?>
					<a <?php $this->print_render_attribute_string( 'link' ); ?>>
						<?php echo wp_kses_post( $text ); ?>
					</a>
				<?php else : ?>
					<?php echo wp_kses_post( $text ); ?>
				<?php endif; ?>
			</<?php echo tag_escape( $tag ); ?>>

		</div>
		<?php
	}
}
