<?php
namespace AITheme\Elementor\Widgets;

use Elementor\Controls_Manager;
use Elementor\Repeater;

if (!defined('ABSPATH')) exit;

class Testimonials_Slider extends AI_Widget_Base {
    public function get_name() { return 'ai_testimonials_slider'; }
    public function get_title() { return __('Testimonials Slider', 'ai-theme'); }
    public function get_icon() { return 'eicon-slider-push'; }
    public function get_categories() { return array('ai-theme-testimonials'); }

    protected function register_controls() {
        $this->start_controls_section('content_section', ['label' => __('Content', 'ai-theme'), 'tab' => Controls_Manager::TAB_CONTENT]);
        $this->add_control('title', ['label' => __('Title', 'ai-theme'), 'type' => Controls_Manager::TEXT, 'default' => '']);

        $repeater = new Repeater();
        $repeater->add_control('name', ['label' => __('Name', 'ai-theme'), 'type' => Controls_Manager::TEXT]);
        $repeater->add_control('position', ['label' => __('Position', 'ai-theme'), 'type' => Controls_Manager::TEXT]);
        $repeater->add_control('content', ['label' => __('Content', 'ai-theme'), 'type' => Controls_Manager::TEXTAREA]);
        $repeater->add_control('avatar', ['label' => __('Avatar', 'ai-theme'), 'type' => Controls_Manager::MEDIA]);
        $this->add_control('testimonials', ['label' => __('Testimonials', 'ai-theme'), 'type' => Controls_Manager::REPEATER, 'fields' => $repeater->get_controls()]);
        $this->end_controls_section();
    }

    private function detectLanguage($settings) {
        $textToCheck = ($settings['title'] ?? '');
        if (!empty($settings['testimonials'])) {
            foreach ($settings['testimonials'] as $item) {
                $textToCheck .= ($item['name'] ?? '') . ($item['content'] ?? '');
            }
        }
        return preg_match('/[\p{Cyrillic}]/u', $textToCheck) ? 'ru' : 'en';
    }

    private function getDefaultTestimonials($isRu) {
        if ($isRu) {
            return [
                ['name' => 'Анна Михайлова', 'position' => 'Постоянный клиент', 'content' => 'Отличный сервис! Заказываю уже не первый раз, всегда всё приходит вовремя и в отличном качестве. Рекомендую всем!'],
                ['name' => 'Дмитрий Козлов', 'position' => 'Покупатель', 'content' => 'Приятно удивлён скоростью доставки и качеством товара. Менеджеры всегда на связи и помогают с выбором.'],
                ['name' => 'Елена Петрова', 'position' => 'Клиент', 'content' => 'Покупаю здесь регулярно. Цены адекватные, качество отличное. Отдельное спасибо за оперативную поддержку!'],
            ];
        } else {
            return [
                ['name' => 'Sarah Johnson', 'position' => 'Verified Buyer', 'content' => 'Excellent service! I\'ve ordered multiple times and everything always arrives on time and in great quality. Highly recommend!'],
                ['name' => 'Michael Chen', 'position' => 'Customer', 'content' => 'Pleasantly surprised by the fast delivery and product quality. Customer support is always helpful and responsive.'],
                ['name' => 'Emily Davis', 'position' => 'Regular Customer', 'content' => 'I shop here regularly. Fair prices, excellent quality. Special thanks for the quick customer support!'],
            ];
        }
    }

    private function hasValidTestimonials($testimonials) {
        if (empty($testimonials) || !is_array($testimonials)) {
            return false;
        }
        foreach ($testimonials as $t) {
            if (!empty($t['name']) || !empty($t['content'])) {
                return true;
            }
        }
        return false;
    }

    protected function render() {
        $s = $this->get_settings_for_display();
        $lang = $this->detectLanguage($s);
        $isRu = $lang === 'ru';

        $title = !empty($s['title']) ? $s['title'] : ($isRu ? 'Отзывы клиентов' : 'Testimonials');
        $testimonials = $this->hasValidTestimonials($s['testimonials']) ? $s['testimonials'] : $this->getDefaultTestimonials($isRu);
        $first_testimonial = !empty($testimonials) ? $testimonials[0] : null;
        ?>
        <section class="ai-testimonials ai-testimonials-slider py-16 text-white" style="background: linear-gradient(to bottom right, var(--color-primary), var(--color-secondary))">
            <div class="ai-container-narrow">
                <div class="text-center mb-12">
                    <h2 class="text-4xl font-bold mb-4"><?php echo esc_html($title); ?></h2>
                </div>
                <div class="ai-testimonials-carousel grid md:grid-cols-1 gap-8">
                    <?php if ($first_testimonial) : ?>
                    <div class="ai-testimonial-slide bg-white/10 backdrop-blur-sm p-12 rounded-3xl border border-white/20 text-center">
                        <svg class="w-16 h-16 text-white/30 mx-auto mb-6" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M14.017 21v-7.391c0-5.704 3.731-9.57 8.983-10.609l.995 2.151c-2.432.917-3.995 3.638-3.995 5.849h4v10h-9.983zm-14.017 0v-7.391c0-5.704 3.748-9.57 9-10.609l.996 2.151c-2.433.917-3.996 3.638-3.996 5.849h3.983v10h-9.983z"/>
                        </svg>
                        <div class="text-2xl mb-8 leading-relaxed prose prose-invert max-w-none">"<?php echo wp_kses_post($first_testimonial['content'] ?? ''); ?>"</div>
                        <div class="flex flex-col items-center">
                            <?php if (!empty($first_testimonial['avatar']['url'])) : ?>
                            <img src="<?php echo esc_url($first_testimonial['avatar']['url']); ?>" alt="<?php echo esc_attr($first_testimonial['name'] ?? ''); ?>" class="w-20 h-20 rounded-full border-4 border-white/30 mb-4 object-cover">
                            <?php else : ?>
                            <div class="w-20 h-20 rounded-full border-4 border-white/30 mb-4 flex items-center justify-center bg-white/20 text-white font-bold text-2xl">
                                <?php echo esc_html(mb_substr($first_testimonial['name'] ?? 'U', 0, 1)); ?>
                            </div>
                            <?php endif; ?>
                            <p class="font-bold text-xl"><?php echo esc_html($first_testimonial['name'] ?? ''); ?></p>
                            <?php if (!empty($first_testimonial['position'])) : ?>
                            <p class="opacity-90"><?php echo esc_html($first_testimonial['position']); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <?php if (count($testimonials) > 1) : ?>
                <div class="flex justify-center gap-2 mt-8">
                    <?php foreach ($testimonials as $index => $t) : ?>
                    <button class="w-3 h-3 rounded-full <?php echo $index === 0 ? 'bg-white' : 'bg-white/30'; ?>"></button>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </section>
        <?php
    }
}
