<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Prevent direct access

class skill_progress_bar_Widget extends \Elementor\Widget_Base {

    public function get_name() {
        return 'skill_progress_bar';
    }

    public function get_title() {
        return esc_html__( 'نوار پیشرفت مهارت', 'skill' );
    }

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

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

    public function get_keywords() {
        return [ 'نوار پیشرفت', 'مهارت', 'skill', 'progress' ];
    }

    protected function register_controls() {
        $this->start_controls_section(
            'content_section',
            [
                'label' => esc_html__( 'مهارت‌ها', 'skill' ),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'show_title_main',
            [
                'label' => esc_html__( 'نمایش عنوان اصلی ویجت', 'skill' ),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => esc_html__( 'نمایش', 'skill' ),
                'label_off' => esc_html__( 'مخفی', 'skill' ),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'title_main',
            [
                'label' => esc_html__( 'عنوان اصلی ویجت', 'skill' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__( 'قابلیت‌ها', 'skill' ),
                'placeholder' => esc_html__( 'مثلاً: قابلیت‌ها', 'skill' ),
                'condition' => [ 'show_title_main' => 'yes' ],
            ]
        );

        $repeater = new \Elementor\Repeater();

        $repeater->add_control(
            'title',
            [
                'label' => esc_html__( 'عنوان', 'skill' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__( 'مهارت من', 'skill' ),
                'placeholder' => esc_html__( 'عنوان را وارد کنید', 'skill' ),
            ]
        );

        $repeater->add_control(
            'percent',
            [
                'label' => esc_html__( 'درصد پیشرفت', 'skill' ),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => [ '%' ],
                'range' => [
                    '%' => [
                        'min' => 0,
                        'max' => 100,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => '%',
                    'size' => 75,
                ],
            ]
        );
        $repeater->add_control(
            'item_bar_color',
            [
                'label' => esc_html__( 'رنگ نوار (آیتم)', 'skill' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '',
                'description' => esc_html__( 'در صورت خالی بودن، از رنگ عمومی ویجت استفاده می‌شود.', 'skill' ),
            ]
        );
        $repeater->add_control(
            'item_bar_bg',
            [
                'label' => esc_html__( 'پس‌زمینه نوار (آیتم)', 'skill' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '',
            ]
        );

        $this->add_control(
            'skills',
            [
                'label' => esc_html__( 'لیست مهارت‌ها', 'skill' ),
                'type' => \Elementor\Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [
                    [
                        'title' => esc_html__( 'برندسازی محصول', 'skill' ),
                        'percent' => [ 'size' => 95, 'unit' => '%' ],
                    ],
                    [
                        'title' => esc_html__( 'رابط کاربری', 'skill' ),
                        'percent' => [ 'size' => 85, 'unit' => '%' ],
                    ],
                ],
                'title_field' => '{{{ title }}}',
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'style_section',
            [
                'label' => esc_html__( 'استایل', 'skill' ),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'bar_color',
            [
                'label' => esc_html__( 'رنگ نوار پیشرفت', 'skill' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#fff',
                'selectors' => [
                    '{{WRAPPER}} .skill-progress-bar__fill' => 'background: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'bar_bg',
            [
                'label' => esc_html__( 'رنگ پس‌زمینه نوار', 'skill' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#ededed',
                'selectors' => [
                    '{{WRAPPER}} .skill-progress-bar__track' => 'background: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'bar_height',
            [
                'label' => esc_html__( 'ضخامت نوار', 'skill' ),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => [ 'px' ],
                'range' => [
                    'px' => [
                        'min' => 10,
                        'max' => 40,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 24,
                ],
                'selectors' => [
                    '{{WRAPPER}} .skill-progress-bar__track' => 'height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'text_color',
            [
                'label' => esc_html__( 'رنگ متن', 'skill' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#222',
                'selectors' => [
                    '{{WRAPPER}} .skill-progress-bar__label, {{WRAPPER}} .skill-progress-bar__percent, {{WRAPPER}} .skill-progress-bar__main-title' => 'color: {{VALUE}};',
                ],
            ]
        );

        // ... existing code ...
        $this->add_control(
            'text_color',
            [
                'label' => esc_html__( 'رنگ متن', 'skill' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#222',
                'selectors' => [
                    '{{WRAPPER}} .skill-progress-bar__label, {{WRAPPER}} .skill-progress-bar__percent' => 'color: {{VALUE}};',
                ],
            ]
        );

        // Main title style
        $this->add_control(
            'main_title_color',
            [
                'label' => esc_html__( 'رنگ عنوان اصلی', 'skill' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#222',
                'selectors' => [
                    '{{WRAPPER}} .skill-progress-bar__main-title' => 'color: {{VALUE}};',
                ],
                'condition' => [ 'show_title_main' => 'yes' ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'main_title_typography',
                'selector' => '{{WRAPPER}} .skill-progress-bar__main-title',
                'condition' => [ 'show_title_main' => 'yes' ],
            ]
        );

        $this->add_responsive_control(
            'main_title_margin',
            [
                'label' => esc_html__( 'فاصله پایین عنوان اصلی', 'skill' ),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => [ 'px' ],
                'range' => [
                    'px' => [ 'min' => 0, 'max' => 50 ],
                ],
                'default' => [ 'unit' => 'px', 'size' => 12 ],
                'selectors' => [
                    '{{WRAPPER}} .skill-progress-bar__main-title' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                ],
                'condition' => [ 'show_title_main' => 'yes' ],
            ]
        );
// ... existing code ...

        $this->end_controls_section();
    }

    protected function render() {
        $settings = $this->get_settings_for_display();
        $widget_id = $this->get_id();
        if ( empty( $settings['skills'] ) ) return;
        ?>
        <div class="skill-progress-bar-group" dir="rtl" id="skill-progress-<?php echo esc_attr($widget_id); ?>">
            <?php if ( !empty($settings['show_title_main']) && $settings['show_title_main'] === 'yes' && !empty($settings['title_main']) ) : ?>
                <div class="skill-progress-bar__main-title" style="font-weight:700;font-size:24px;margin-bottom:12px;line-height:1.7;"> 
                    <?php echo esc_html($settings['title_main']); ?>
                </div>
            <?php endif; ?>
            <?php foreach ( $settings['skills'] as $item ) :
                $percent = !empty($item['percent']['size']) ? $item['percent']['size'] : 0;
                $bar_color = (isset($item['item_bar_color']) && $item['item_bar_color'] !== '') ? $item['item_bar_color'] : '';
                $bar_bg = (isset($item['item_bar_bg']) && $item['item_bar_bg'] !== '') ? $item['item_bar_bg'] : '';
                $track_style = $bar_bg ? 'background:' . $bar_bg . ';' : '';
                $fill_style = 'width: 0%;' . ( $bar_color ? ' background:' . $bar_color . ';' : '' );
            ?>
            <div class="skill-progress-bar" style="margin-bottom: 18px;">
                <div class="skill-progress-bar__track" style="<?php echo esc_attr($track_style); ?>">
                    <div class="skill-progress-bar__fill" data-target-percent="<?php echo esc_attr($percent); ?>" style="<?php echo esc_attr($fill_style); ?>">
                        <span class="skill-progress-bar__label"><?php echo esc_html($item['title']); ?></span>
                        <span class="skill-progress-bar__percent">0٪</span>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <style>
        .skill-progress-bar__main-title {
            font-weight: 700;
            font-size: 1.1em;
            margin-bottom: 12px;
            line-height: 1.7;
        }
        .skill-progress-bar__track {
            width: 100%;
            background: #ededed;
            border-radius: 999px;
            overflow: hidden;
            position: relative;
        }
        .skill-progress-bar__fill {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            height: 100%;
            background: #fff;
            border-radius: 999px;
            transition: width 1.4s cubic-bezier(.4,0,.2,1);
            padding: 0 16px;
            font-size: 1em;
            position: relative;
            overflow: hidden;
            will-change: width;
        }
        .skill-progress-bar__fill::before {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            left: -40%;
            width: 40%;
            background: linear-gradient(120deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.35) 50%, rgba(255,255,255,0) 100%);
            transform: skewX(-20deg);
            animation: skillShimmer 2.2s ease-in-out infinite;
            pointer-events: none;
        }
        @keyframes skillShimmer {
            0% { left: -40%; }
            100% { left: 120%; }
        }
        .skill-progress-bar__label {
            font-weight: 500;
            font-size: 1em;
            white-space: nowrap;
        }
        .skill-progress-bar__percent {
            font-weight: 700;
            font-size: 1em;
            white-space: nowrap;
        }
        </style>
        <script>
        (function(){
            var root = document.getElementById('skill-progress-<?php echo esc_js($widget_id); ?>');
            if (!root || root.dataset.animated === '1') { return; }
            var startAnimation = function() {
                if (root.dataset.animated === '1') { return; }
                root.dataset.animated = '1';
                var fills = root.querySelectorAll('.skill-progress-bar__fill');
                fills.forEach(function(fill){
                    var target = parseInt(fill.getAttribute('data-target-percent') || '0', 10);
                    var percentEl = fill.querySelector('.skill-progress-bar__percent');
                    var startTime = null;
                    var duration = 1200;
                    function step(ts){
                        if (!startTime) startTime = ts;
                        var progress = Math.min((ts - startTime) / duration, 1);
                        var current = Math.floor(target * progress);
                        fill.style.width = current + '%';
                        if (percentEl) { percentEl.textContent = current + '٪'; }
                        if (progress < 1) { requestAnimationFrame(step); }
                    }
                    requestAnimationFrame(step);
                });
            };
            if ('IntersectionObserver' in window) {
                var io = new IntersectionObserver(function(entries){
                    entries.forEach(function(entry){
                        if (entry.isIntersecting) { startAnimation(); io.disconnect(); }
                    });
                }, { threshold: 0.3 });
                io.observe(root);
            } else {
                startAnimation();
            }
        })();
        </script>
        <?php
    }
}
