<?php
namespace HugeAddons\Widgets;

use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Widget_Base;
use Elementor\Utils;
use Elementor\Group_Control_Typography;


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

class HugeLottieWidget extends \Elementor\Widget_Base
{

    public function get_name()
    {
        return 'thha-huge-lottie';
    }

    public function get_title()
    {
        return __('Huge Lottie', 'huge-lottie-widget');
    }

    public function get_icon()
    {
        return 'eicon-animation';
    }

    public function get_categories()
    {
        return ['thha-addons-category'];
    }

    public function get_script_depends()
    {
        return ['lottie-web', 'huge-lottie-widget'];
    }

    protected function _register_controls()
    {
        // Content Tab - Main Wrapper Section
        $this->start_controls_section(
            'huge_lottie_section',
            [
                'label' => __('Huge Lottie', 'huge-lottie-widget'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        // Animation Source Section
        $this->add_control(
            'animation_source_heading',
            [
                'label' => __('Animation Source', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $this->add_control(
            'source',
            [
                'label' => __('Source', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'url' => __('External URL', 'huge-lottie-widget'),
                    'file' => __('Upload File', 'huge-lottie-widget'),
                ],
                'default' => 'url',
            ]
        );

        $this->add_control(
            'lottie_url',
            [
                'label' => __('Lottie URL', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'input_type' => 'url',
                'placeholder' => __('https://example.com/animation.json', 'huge-lottie-widget'),
                'condition' => [
                    'source' => 'url',
                ],
            ]
        );

        $this->add_control(
            'lottie_file',
            [
                'label' => __('Upload Lottie File', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::MEDIA,
                'media_type' => 'application/json',
                'condition' => [
                    'source' => 'file',
                ],
            ]
        );

        // Animation Settings Section
        $this->add_control(
            'animation_settings_heading',
            [
                'label' => __('Animation Settings', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $this->add_responsive_control(
            'width',
            [
                'label' => __('Width', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px', '%', 'vw'],
                'range' => [
                    'px' => [
                        'min' => 100,
                        'max' => 2000,
                        'step' => 5,
                    ],
                    '%' => [
                        'min' => 1,
                        'max' => 100,
                    ],
                    'vw' => [
                        'min' => 1,
                        'max' => 100,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 300,
                ],
            ]
        );

        $this->add_responsive_control(
            'height',
            [
                'label' => __('Height', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px', '%', 'vh'],
                'range' => [
                    'px' => [
                        'min' => 100,
                        'max' => 2000,
                        'step' => 5,
                    ],
                    '%' => [
                        'min' => 1,
                        'max' => 100,
                    ],
                    'vh' => [
                        'min' => 1,
                        'max' => 100,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 300,
                ],
            ]
        );

        $this->add_control(
            'autoplay',
            [
                'label' => __('Autoplay', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'huge-lottie-widget'),
                'label_off' => __('No', 'huge-lottie-widget'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'loop',
            [
                'label' => __('Loop', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'huge-lottie-widget'),
                'label_off' => __('No', 'huge-lottie-widget'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'loop_count',
            [
                'label' => __('Loop Count', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'min' => 1,
                'max' => 10,
                'step' => 1,
                'condition' => [
                    'loop' => 'yes',
                ],
                'description' => __('Set how many times the animation should loop. Minimum: 1, Maximum: 10, Step: 1. Works only when looping is enabled.', 'huge-lottie-widget'),
            ]
        );

        $this->add_control(
            'speed',
            [
                'label' => __('Speed', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'min' => 0.1,
                'max' => 5,
                'step' => 0.1,
                'default' => 1,
                'description' => __('Set animation speed. Minimum: 0.1, Maximum: 5, Step: 0.1. Default is 1 (normal speed).', 'huge-lottie-widget'),
            ]
        );

        $this->add_control(
            'reverse',
            [
                'label' => __('Reverse', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'huge-lottie-widget'),
                'label_off' => __('No', 'huge-lottie-widget'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'hover_action',
            [
                'label' => __('On Hover', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'none',
                'options' => [
                    'none' => __('None', 'huge-lottie-widget'),
                    'play' => __('Play', 'huge-lottie-widget'),
                    'pause' => __('Pause', 'huge-lottie-widget'),
                    'reverse' => __('Reverse', 'huge-lottie-widget'),
                ],
            ]
        );

        // Content Section
        $this->add_control(
            'content_heading',
            [
                'label' => __('Content', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $this->add_control(
            'show_title',
            [
                'label' => __('Show Title', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'huge-lottie-widget'),
                'label_off' => __('No', 'huge-lottie-widget'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'title_text',
            [
                'label' => __('Title', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => __('Animation Title', 'huge-lottie-widget'),
                'placeholder' => __('Enter your title here', 'huge-lottie-widget'),
                'condition' => [
                    'show_title' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'show_content',
            [
                'label' => __('Show Content', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'huge-lottie-widget'),
                'label_off' => __('No', 'huge-lottie-widget'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'content_text',
            [
                'label' => __('Content', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::TEXTAREA,
                'default' => __('Your animation description goes here', 'huge-lottie-widget'),
                'placeholder' => __('Enter your content here', 'huge-lottie-widget'),
                'condition' => [
                    'show_content' => 'yes',
                ],
            ]
        );


        $this->end_controls_section();

        // Style Tab - Main Wrapper Section
        $this->start_controls_section(
            'huge_lottie_style_section',
            [
                'label' => __('Huge Lottie', 'huge-lottie-widget'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );

        // Animation Style Section

        $this->add_control(
            'align',
            [
                'label' => __('Alignment', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => __('Left', 'huge-lottie-widget'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => __('Center', 'huge-lottie-widget'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'right' => [
                        'title' => __('Right', 'huge-lottie-widget'),
                        'icon' => 'eicon-text-align-right',
                    ],
                ],
                'default' => 'left',
                'toggle' => true,
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper' => 'text-align: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Background::get_type(),
            [
                'name' => 'wrapper_background',
                'label' => __('Background', 'huge-lottie-widget'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .huge-lottie-wrapper',
            ]
        );

        $this->add_responsive_control(
            'wrapper_padding',
            [
                'label' => __('Padding', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'wrapper_margin',
            [
                'label' => __('Margin', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            [
                'name' => 'wrapper_border',
                'label' => __('Border', 'huge-lottie-widget'),
                'selector' => '{{WRAPPER}} .huge-lottie-wrapper',
            ]
        );

        $this->add_responsive_control(
            'wrapper_border_radius',
            [
                'label' => __('Border Radius', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'wrapper_box_shadow',
                'label' => __('Box Shadow', 'huge-lottie-widget'),
                'selector' => '{{WRAPPER}} .huge-lottie-wrapper',
            ]
        );

        // hover section heading
        $this->add_control(
            'wrapper_hover_heading',
            [
                'label' => __('Hover Effects', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Background::get_type(),
            [
                'name' => 'wrapper_hover_background',
                'label' => __('Background', 'huge-lottie-widget'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .huge-lottie-wrapper:hover',
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            [
                'name' => 'wrapper_hover_border',
                'label' => __('Border', 'huge-lottie-widget'),
                'selector' => '{{WRAPPER}} .huge-lottie-wrapper:hover',
            ]
        );

        $this->add_responsive_control(
            'wrapper_hover_border_radius',
            [
                'label' => __('Border Radius', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper:hover' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'wrapper_hover_box_shadow',
                'label' => __('Box Shadow', 'huge-lottie-widget'),
                'selector' => '{{WRAPPER}} .huge-lottie-wrapper:hover',
            ]
        );

        $this->add_control(
            'wrapper_hover_animation',
            [
                'label' => __('Hover Animation', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HOVER_ANIMATION,
            ]
        );

        $this->add_control(
            'wrapper_hover_transition',
            [
                'label' => __('Transition Duration', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'range' => [
                    'px' => [
                        'max' => 3,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'size' => 0.3,
                ],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper' => 'transition: all {{SIZE}}s ease;',
                ],
            ]
        );


        // Container Style Section
        $this->add_control(
            'container_style_heading',
            [
                'label' => __('Animation', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        // Background
        $this->add_group_control(
            \Elementor\Group_Control_Background::get_type(),
            [
                'name' => 'container_background',
                'label' => __('Background', 'huge-lottie-widget'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .huge-lottie-container',
            ]
        );

        // Padding
        $this->add_responsive_control(
            'container_padding',
            [
                'label' => __('Padding', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-container' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        // Border
        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            [
                'name' => 'container_border',
                'label' => __('Border', 'huge-lottie-widget'),
                'selector' => '{{WRAPPER}} .huge-lottie-container',
            ]
        );

        // Border Radius
        $this->add_responsive_control(
            'container_border_radius',
            [
                'label' => __('Border Radius', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-container' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        // Box Shadow
        $this->add_group_control(
            \Elementor\Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'container_box_shadow',
                'label' => __('Box Shadow', 'huge-lottie-widget'),
                'selector' => '{{WRAPPER}} .huge-lottie-container',
            ]
        );

        // Title Style Section
        $this->add_control(
            'title_style_heading',
            [
                'label' => __('Title', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
                'condition' => [
                    'show_title' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'title_color',
            [
                'label' => __('Color', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-title' => 'color: {{VALUE}};',
                ],
                'condition' => [
                    'show_title' => 'yes',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'title_typography',
                'selector' => '{{WRAPPER}} .huge-lottie-title',
                'condition' => [
                    'show_title' => 'yes',
                ],
            ]
        );

        $this->add_responsive_control(
            'title_spacing',
            [
                'label' => __('Spacing', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-title' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
                'condition' => [
                    'show_title' => 'yes',
                ],
            ]
        );

        // color heading 
        $this->add_control(
            'title_color_heading',
            [
                'label' => __('Title Hover Color', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
                'condition' => [
                    'show_title' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'title_hover_color',
            [
                'label' => __('Hover Color', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper:hover .huge-lottie-title' => 'color: {{VALUE}};',
                ],
                'condition' => [
                    'show_title' => 'yes',
                ],
            ]
        );

        // Content Style Section
        $this->add_control(
            'content_style_heading',
            [
                'label' => __('Content', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
                'condition' => [
                    'show_content' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'content_color',
            [
                'label' => __('Color', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-content' => 'color: {{VALUE}};',
                ],
                'condition' => [
                    'show_content' => 'yes',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'content_typography',
                'selector' => '{{WRAPPER}} .huge-lottie-content',
                'condition' => [
                    'show_content' => 'yes',
                ],
            ]
        );

        $this->add_responsive_control(
            'content_spacing',
            [
                'label' => __('Spacing', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-content' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
                'condition' => [
                    'show_content' => 'yes',
                ],
            ]
        );

        // Content Hover Style Section
        $this->add_control(
            'content_hover_color_heading',
            [
                'label' => __('Content Hover Color', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
                'condition' => [
                    'show_content' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'content_hover_color',
            [
                'label' => __('Hover Content Color', 'huge-lottie-widget'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .huge-lottie-wrapper:hover .huge-lottie-content' => 'color: {{VALUE}};',
                ],
                'condition' => [
                    'show_content' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render the widget output on the frontend.
     *
     * Written in PHP and used to generate the final HTML.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();

        // Add hover animation class if set
        $this->add_render_attribute('_wrapper', [
            'class' => [
                'huge-lottie-wrapper',
                !empty($settings['wrapper_hover_animation']) ? 'elementor-animation-' . $settings['wrapper_hover_animation'] : ''
            ]
        ]);

        // Check if we have either URL or file
        $has_lottie = ($settings['source'] === 'url' && !empty($settings['lottie_url'])) ||
            ($settings['source'] === 'file' && !empty($settings['lottie_file']['url']));

        if (!$has_lottie) {
            echo __('Please provide a Lottie animation', 'huge-lottie-widget');
            return;
        }

        wp_enqueue_script('lottie-web');
        wp_enqueue_script('huge-lottie-widget');

        $width = $settings['width']['size'] . $settings['width']['unit'];
        $height = $settings['height']['size'] . $settings['height']['unit'];
        $autoplay = $settings['autoplay'] === 'yes' ? true : false;
        $loop = $settings['loop'] === 'yes' ? true : false;
        $reverse = $settings['reverse'] === 'yes' ? -1 : 1;
        $loop_count = $settings['loop'] === 'yes' ? $settings['loop_count'] : 0;
        $speed = $settings['speed'];
        $hover_action = $settings['hover_action'];

        // Get the correct source based on selection
        $lottie_src = ($settings['source'] === 'file') ?
            $settings['lottie_file']['url'] :
            $settings['lottie_url'];

        $container_id = 'huge-lottie-' . $this->get_id();
        $animation_id = $container_id . '-animation';
?>

        <div <?php echo $this->get_render_attribute_string('_wrapper'); ?>>


            <div id="<?php echo esc_attr($container_id); ?>" class="huge-lottie-container"
                style="width: <?php echo esc_attr($width); ?>; height: <?php echo esc_attr($height); ?>;">
                <div id="<?php echo esc_attr($animation_id); ?>" style="width: 100%; height: 100%;"></div>
            </div>

            <?php if ($settings['show_title'] === 'yes' && !empty($settings['title_text'])) : ?>
                <h3 class="huge-lottie-title"><?php echo esc_html($settings['title_text']); ?></h3>
            <?php endif; ?>

            <?php if ($settings['show_content'] === 'yes' && !empty($settings['content_text'])) : ?>
                <div class="huge-lottie-content"><?php echo wp_kses_post($settings['content_text']); ?></div>
            <?php endif; ?>
        </div>

        <script>
            jQuery(document).ready(function($) {
                if (typeof lottie === 'undefined') {
                    console.error('Lottie library not loaded');
                    return;
                }

                const container = document.getElementById('<?php echo $container_id; ?>');
                const animationElement = document.getElementById('<?php echo $animation_id; ?>');

                if (!container || !animationElement) return;

                // Animation configuration
                const animConfig = {
                    container: animationElement,
                    renderer: 'svg',
                    loop: false, // Always handle looping manually
                    autoplay: <?php echo $autoplay ? 'true' : 'false'; ?>,
                    path: '<?php echo esc_url($lottie_src); ?>',
                    rendererSettings: {
                        preserveAspectRatio: 'xMidYMid meet'
                    }
                };

                // Initialize animation
                const anim = lottie.loadAnimation(animConfig);
                anim.setSpeed(<?php echo $speed; ?>);
                anim.setDirection(<?php echo $reverse; ?>);

                // Loop control variables
                let loopCounter = 0;
                const hasLoopCount = <?php echo ($loop && $loop_count > 0) ? 'true' : 'false'; ?>;
                const maxLoops = <?php echo ($loop && $loop_count > 0) ? $loop_count : 0; ?>;
                let currentDirection = <?php echo $reverse; ?>;
                let isReversed = false;
                let wasPlaying = false;

                // Function to handle animation completion
                function handleAnimationComplete() {
                    if (hasLoopCount) {
                        loopCounter++;
                        if (loopCounter < maxLoops) {
                            // Play again from start/end based on direction
                            if (currentDirection === 1) {
                                anim.goToAndPlay(0, true);
                            } else {
                                anim.goToAndPlay(anim.totalFrames, true);
                            }
                        }
                    } else if (<?php echo $loop ? 'true' : 'false'; ?>) {
                        // Infinite loop - play again based on current direction
                        if (currentDirection === 1) {
                            anim.goToAndPlay(0, true);
                        } else {
                            anim.goToAndPlay(anim.totalFrames, true);
                        }
                    }
                }

                // Set up complete event listener
                anim.addEventListener('complete', handleAnimationComplete);

                // Reset loop counter when direction changes
                function resetLoopCounter() {
                    loopCounter = 0;
                }

                // Hover actions
                <?php if ($hover_action !== 'none') : ?>
                    container.addEventListener('mouseenter', function() {
                        wasPlaying = !anim.isPaused;

                        switch ('<?php echo $hover_action; ?>') {
                            case 'play':
                                anim.play();
                                break;
                            case 'pause':
                                anim.pause();
                                break;
                            case 'reverse':
                                isReversed = true;
                                resetLoopCounter();
                                currentDirection = -1 * <?php echo $reverse; ?>;
                                anim.setDirection(currentDirection);
                                // Start from appropriate end based on direction
                                if (currentDirection === 1) {
                                    anim.goToAndPlay(0, true);
                                } else {
                                    anim.goToAndPlay(anim.totalFrames, true);
                                }
                                break;
                        }
                    });

                    container.addEventListener('mouseleave', function() {
                        switch ('<?php echo $hover_action; ?>') {
                            case 'play':
                                anim.pause();
                                break;
                            case 'pause':
                                if (wasPlaying) {
                                    anim.play();
                                }
                                break;
                            case 'reverse':
                                if (isReversed) {
                                    resetLoopCounter();
                                    currentDirection = <?php echo $reverse; ?>;
                                    anim.setDirection(currentDirection);
                                    if (!wasPlaying) {
                                        anim.pause();
                                    } else {
                                        // Continue playing from correct position
                                        if (currentDirection === 1) {
                                            anim.goToAndPlay(anim.currentFrame, true);
                                        } else {
                                            anim.goToAndPlay(anim.totalFrames - anim.currentFrame, true);
                                        }
                                    }
                                    isReversed = false;
                                }
                                break;
                        }
                    });
                <?php endif; ?>

                // Initialize playback based on settings
                anim.addEventListener('DOMLoaded', function() {
                    if (<?php echo $autoplay ? 'true' : 'false'; ?>) {
                        // Start from appropriate end based on initial direction
                        if (<?php echo $reverse; ?> === 1) {
                            anim.goToAndPlay(0, true);
                        } else {
                            anim.goToAndPlay(anim.totalFrames, true);
                        }
                    }
                });
            });
        </script>
<?php
    }
}
