<?php

namespace Unlockafe_addons\Widgets;

use Unlockafe_addons\Traits\Utils as UnlockafeUtils;
use Unlockafe_addons\Traits\Widget_helper;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Text_Shadow;
use Elementor\Group_Control_Background;

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

/**
 * Animated Text Widget
 *
 * @since 1.0.0
 */
class Animated_Text extends Widget_Base
{
    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     */
    public function get_name()
    {
        return 'unlockafe-animated-text';
    }

    /**
     * Retrieve the widget title.
     */
    public function get_title()
    {
        return __('Animated Text', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     */
    public function get_icon()
    {
        return 'eicon-animation-text ulicon';
    }

    /**
     * Retrieve the list of categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of keywords.
     */
    public function get_keywords()
    {
        return ['animated', 'text', 'typing', 'typewriter', 'animation', 'rotating', 'fade'];
    }

    /**
     * Retrieve the list of scripts.
     */
    public function get_script_depends()
    {
        return ['unlockafe-animated-text-scripts'];
    }

    /**
     * Retrieve the list of styles.
     */
    public function get_style_depends()
    {
        return ['unlockafe-animated-text-style', 'font-awesome'];
    }

    /**
     * Register widget controls.
     */
    protected function register_controls()
    {
        $this->register_content_controls();
        $this->register_style_controls();
    }

    /**
     * Register content controls.
     */
    protected function register_content_controls()
    {
        // General Settings
        $this->start_controls_section(
            'general_section',
            [
                'label' => __('General Settings', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'animation_type',
            [
                'label' => __('Animation Type', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'typewriter' => __('Typewriter', 'unlock-addons-for-elementor'),
                    'rotating' => __('Rotating Words', 'unlock-addons-for-elementor'),
                    'fade' => __('Fade In/Out', 'unlock-addons-for-elementor'),
                    'slide' => __('Slide Up', 'unlock-addons-for-elementor'),
                    'blur' => __('Blur In', 'unlock-addons-for-elementor'),
                    'glitch' => __('Glitch Effect', 'unlock-addons-for-elementor'),
                    'gradient' => __('Gradient Animation', 'unlock-addons-for-elementor'),
                    'wave' => __('Wave Animation', 'unlock-addons-for-elementor'),
                ],
                'default' => 'typewriter',
            ]
        );

        $this->add_control(
            'prefix_text',
            [
                'label' => __('Prefix Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('I am', 'unlock-addons-for-elementor'),
                'placeholder' => __('Text before animation', 'unlock-addons-for-elementor'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $this->add_control(
            'suffix_text',
            [
                'label' => __('Suffix Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '',
                'placeholder' => __('Text after animation', 'unlock-addons-for-elementor'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $this->add_control(
            'animated_text',
            [
                'label' => __('Animated Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => __('Developer', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter text to animate', 'unlock-addons-for-elementor'),
                'description' => __('Single text field. Use "Animated Words" repeater below for multiple words.', 'unlock-addons-for-elementor'),
                'condition' => [
                    'animation_type!' => ['rotating'],
                    'use_animated_words!' => 'yes',
                ],
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $this->add_control(
            'use_animated_words',
            [
                'label' => __('Use Multiple Words', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
                'condition' => [
                    'animation_type!' => 'rotating',
                ],
                'description' => __('Enable to use repeater for multiple animated words', 'unlock-addons-for-elementor'),
            ]
        );

        // Repeater for Rotating Words (specific to rotating animation)
        $rotating_repeater = new \Elementor\Repeater();
        $rotating_repeater->add_control(
            'rotating_word',
            [
                'label' => __('Word', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => __('Developer', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter word', 'unlock-addons-for-elementor'),
                'rows' => 2,
            ]
        );

        $this->add_control(
            'rotating_words',
            [
                'label' => __('Rotating Words', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $rotating_repeater->get_controls(),
                'default' => [
                    [
                        'rotating_word' => __('Developer', 'unlock-addons-for-elementor'),
                    ],
                    [
                        'rotating_word' => __('Designer', 'unlock-addons-for-elementor'),
                    ],
                    [
                        'rotating_word' => __('Creator', 'unlock-addons-for-elementor'),
                    ],
                ],
                'title_field' => '{{{ rotating_word }}}',
                'condition' => [
                    'animation_type' => 'rotating',
                ],
            ]
        );

        // Repeater for Animated Words (for all other animation types)
        $animated_words_repeater = new \Elementor\Repeater();
        $animated_words_repeater->add_control(
            'animated_word',
            [
                'label' => __('Word/Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => __('Developer', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter word or text', 'unlock-addons-for-elementor'),
                'rows' => 2,
            ]
        );

        $this->add_control(
            'animated_words',
            [
                'label' => __('Animated Words', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $animated_words_repeater->get_controls(),
                'default' => [
                    [
                        'animated_word' => __('Developer', 'unlock-addons-for-elementor'),
                    ],
                    [
                        'animated_word' => __('Designer', 'unlock-addons-for-elementor'),
                    ],
                    [
                        'animated_word' => __('Creator', 'unlock-addons-for-elementor'),
                    ],
                ],
                'title_field' => '{{{ animated_word }}}',
                'condition' => [
                    'animation_type!' => 'rotating',
                    'use_animated_words' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'show_cursor',
            [
                'label' => __('Show Cursor', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
                'condition' => [
                    'animation_type' => 'typewriter',
                ],
            ]
        );

        $this->add_control(
            'animation_speed',
            [
                'label' => __('Animation Speed', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['ms', 's'],
                'range' => [
                    'ms' => [
                        'min' => 50,
                        'max' => 2000,
                        'step' => 50,
                    ],
                    's' => [
                        'min' => 0.5,
                        'max' => 5,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'unit' => 's',
                    'size' => 2,
                ],
                'description' => __('Lower value = faster animation. For typewriter/rotating, this controls character/word speed. For other animations, this controls duration.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'loop_animation',
            [
                'label' => __('Loop Animation', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'animate_on_scroll',
            [
                'label' => __('Animate on Scroll', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register style controls.
     */
    protected function register_style_controls()
    {
        // Container Style
        $this->start_controls_section(
            'container_style_section',
            [
                'label' => __('Container', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'text_alignment',
            [
                'label' => __('Alignment', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => __('Left', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => __('Center', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'right' => [
                        'title' => __('Right', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-right',
                    ],
                ],
                'default' => 'left',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-animated-text-wrapper' => 'text-align: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Prefix/Suffix Style
        $this->start_controls_section(
            'static_text_style_section',
            [
                'label' => __('Prefix & Suffix Text', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'static_text_color',
            [
                'label' => __('Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-animated-text-prefix' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .unlockafe-animated-text-suffix' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'static_text_typography',
                'selector' => '{{WRAPPER}} .unlockafe-animated-text-prefix, {{WRAPPER}} .unlockafe-animated-text-suffix',
            ]
        );

        $this->end_controls_section();

        // Animated Text Style
        $this->start_controls_section(
            'animated_text_style_section',
            [
                'label' => __('Animated Text', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'animated_text_color',
            [
                'label' => __('Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-animated-text-animated' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'animated_text_typography',
                'selector' => '{{WRAPPER}} .unlockafe-animated-text-animated',
            ]
        );

        $this->add_group_control(
            Group_Control_Text_Shadow::get_type(),
            [
                'name' => 'animated_text_shadow',
                'label' => __('Text Shadow', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlockafe-animated-text-animated',
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'animated_text_background',
                'label' => __('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlockafe-animated-text-animated',
                'condition' => [
                    'animation_type' => 'gradient',
                ],
            ]
        );

        $this->add_responsive_control(
            'animated_text_height',
            [
                'label' => __('Height', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em', 'rem', 'vh'],
                'range' => [
                    'px' => [
                        'min' => 20,
                        'max' => 500,
                        'step' => 1,
                    ],
                    'em' => [
                        'min' => 1,
                        'max' => 30,
                        'step' => 0.1,
                    ],
                    'rem' => [
                        'min' => 1,
                        'max' => 30,
                        'step' => 0.1,
                    ],
                    'vh' => [
                        'min' => 1,
                        'max' => 100,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-animated-text-animated' => 'height: {{SIZE}}{{UNIT}} !important; min-height: {{SIZE}}{{UNIT}} !important; line-height: {{SIZE}}{{UNIT}} !important;',
                ],
                'separator' => 'before',
            ]
        );

        $this->end_controls_section();

        // Cursor Style
        $this->start_controls_section(
            'cursor_style_section',
            [
                'label' => __('Cursor', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'cursor_color',
            [
                'label' => __('Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#667eea',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-animated-text-cursor' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'cursor_width',
            [
                'label' => __('Width', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em', '%'],
                'range' => [
                    'px' => [
                        'min' => 1,
                        'max' => 10,
                        'step' => 1,
                    ],
                    'em' => [
                        'min' => 0.1,
                        'max' => 1,
                        'step' => 0.1,
                    ],
                    '%' => [
                        'min' => 1,
                        'max' => 100,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 2,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-animated-text-cursor' => 'border-right-width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'cursor_height',
            [
                'label' => __('Height', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em', 'rem'],
                'range' => [
                    'px' => [
                        'min' => 10,
                        'max' => 200,
                        'step' => 1,
                    ],
                    'em' => [
                        'min' => 0.5,
                        'max' => 10,
                        'step' => 0.1,
                    ],
                    'rem' => [
                        'min' => 0.5,
                        'max' => 10,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-animated-text-cursor' => 'height: {{SIZE}}{{UNIT}} !important; min-height: {{SIZE}}{{UNIT}} !important; line-height: {{SIZE}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render widget output on the frontend.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $animation_type = $settings['animation_type'] ?? 'typewriter';
        $prefix_text = !empty($settings['prefix_text']) ? esc_html($settings['prefix_text']) : '';
        $suffix_text = !empty($settings['suffix_text']) ? esc_html($settings['suffix_text']) : '';
        $animated_text = !empty($settings['animated_text']) ? esc_html($settings['animated_text']) : '';
        $use_animated_words = !empty($settings['use_animated_words']) && $settings['use_animated_words'] === 'yes';
        $rotating_words = !empty($settings['rotating_words']) ? $settings['rotating_words'] : [];
        $animated_words = !empty($settings['animated_words']) ? $settings['animated_words'] : [];
        $show_cursor = $settings['show_cursor'] === 'yes';
        // Get animation speed - convert to appropriate unit
        $animation_speed_value = !empty($settings['animation_speed']['size']) ? floatval($settings['animation_speed']['size']) : 2;
        $animation_speed_unit = !empty($settings['animation_speed']['unit']) ? $settings['animation_speed']['unit'] : 's';
        // Convert to milliseconds for typewriter/rotating, keep as is for CSS animations
        $animation_speed_ms = ($animation_speed_unit === 's') ? ($animation_speed_value * 1000) : $animation_speed_value;
        $animation_speed_css = $animation_speed_value . $animation_speed_unit;
        $loop_animation = $settings['loop_animation'] === 'yes';
        $animate_on_scroll = $settings['animate_on_scroll'] === 'yes';

        $wrapper_class = 'unlockafe-animated-text-wrapper';
        $wrapper_class .= ' unlockafe-animated-' . esc_attr($animation_type);

        // Prepare rotating words data
        $rotating_words_data = [];
        if ($animation_type === 'rotating' && !empty($rotating_words)) {
            foreach ($rotating_words as $word) {
                if (!empty($word['rotating_word'])) {
                    // Handle TEXTAREA - take first line only for rotating words
                    $word_text = $word['rotating_word'];
                    $lines = explode("\n", $word_text);
                    $first_line = trim($lines[0]);
                    if (!empty($first_line)) {
                        $rotating_words_data[] = esc_html($first_line);
                    }
                }
            }
        }

        // Prepare animated words data for all other animation types
        $animated_words_data = [];
        if ($animation_type !== 'rotating' && $use_animated_words && !empty($animated_words)) {
            foreach ($animated_words as $word) {
                if (!empty($word['animated_word'])) {
                    // Handle TEXTAREA - take first line
                    $word_text = $word['animated_word'];
                    $lines = explode("\n", $word_text);
                    $first_line = trim($lines[0]);
                    if (!empty($first_line)) {
                        $animated_words_data[] = esc_html($first_line);
                    }
                }
            }
        }

        ?>
        <div class="<?php echo esc_attr($wrapper_class); ?>" 
             style="display: flex !important; align-items: center !important; flex-wrap: nowrap !important; flex-direction: row !important; white-space: nowrap !important; width: auto !important; max-width: none !important;"
             data-animation-type="<?php echo esc_attr($animation_type); ?>"
             data-animation-speed="<?php echo esc_attr($animation_speed_ms); ?>"
             data-animation-speed-css="<?php echo esc_attr($animation_speed_css); ?>"
             data-loop="<?php echo $loop_animation ? 'yes' : 'no'; ?>"
             data-animate-on-scroll="<?php echo $animate_on_scroll ? 'yes' : 'no'; ?>"
             data-rotating-words='<?php echo json_encode($rotating_words_data); ?>'
             data-animated-words='<?php echo json_encode($animated_words_data); ?>'
             data-use-animated-words="<?php echo $use_animated_words ? 'yes' : 'no'; ?>"
             data-animated-text="<?php echo esc_attr($animated_text); ?>"
             data-id="<?php echo esc_attr($this->get_id()); ?>">
            
            <?php if ($prefix_text): ?>
                <span class="unlockafe-animated-text-prefix"><?php echo $prefix_text; ?> </span>
            <?php endif; ?>

            <span class="unlockafe-animated-text-animated">
                <?php if ($animation_type === 'rotating' && !empty($rotating_words_data)): ?>
                    <span class="unlockafe-rotating-word"><?php echo $rotating_words_data[0]; ?></span>
                <?php elseif ($animation_type === 'typewriter'): ?>
                    <span class="unlockafe-typewriter-text"></span>
                <?php elseif ($use_animated_words && !empty($animated_words_data)): ?>
                    <span class="unlockafe-animated-word"><?php echo $animated_words_data[0]; ?></span>
                <?php else: ?>
                    <?php echo $animated_text; ?>
                <?php endif; ?>
            </span>

            <?php if ($show_cursor && $animation_type === 'typewriter'): ?>
                <span class="unlockafe-animated-text-cursor">|</span>
            <?php endif; ?>

            <?php if ($suffix_text): ?>
                <span class="unlockafe-animated-text-suffix"> <?php echo $suffix_text; ?></span>
            <?php endif; ?>
        </div>
        <?php
    }
}


