---
import { getDynamicStats, getYearDeclension, getClientDeclension, getYearsOfPractice } from '@utils/stats.utils.ts';
import { CONTACT_CONSTANTS } from '@constants/constants.ts';

const dynamicStats = getDynamicStats();
const yearsOfPractice = getYearsOfPractice();

const achievements = [
    {
        number: yearsOfPractice,
        suffix: '',
        text: 'Лет практики',
        type: 'years',
        icon: 'calendar'
    },
    {
        number: dynamicStats[1].number,
        suffix: dynamicStats[1].suffix,
        text: 'Успешных дел',
        type: 'cases',
        icon: 'briefcase'
    },
    {
        number: dynamicStats[2].number,
        suffix: dynamicStats[2].suffix,
        text: 'довольных клиентов',
        type: 'clients',
        icon: 'users'
    },
    {
        number: "24/7",
        suffix: '',
        text: 'На связи',
        type: 'support',
        icon: 'clock'
    }
] as const;

const iconPaths = {
    calendar: "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z",
    briefcase: "M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z",
    users: "M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z",
    clock: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
} as const;

type StatType = typeof achievements[number]['type'];

const getStatText = (stat: typeof achievements[number]): string => {
    const texts: Record<StatType, string> = {
        years: `${stat.number} ${getYearDeclension(stat.number)} практики`,
        cases: 'Успешных дел',
        clients: `${stat.number} ${getClientDeclension(stat.number)}`,
        support: 'Поддержка клиентов'
    };
    return texts[stat.type];
};
---

<section class="relative py-20 bg-gradient-to-b from-gray-50 to-white overflow-hidden -mx-4 md:mx-0">
    <div class="w-full px-4 md:container md:mx-auto md:px-4 md:max-w-7xl">
        <!-- Заголовок -->
        <div class="text-center mb-16">
            <h2 class="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
                Ключевые достижения в <span class="text-[var(--color-blue-primary)]">цифрах</span>
            </h2>
            <div class="w-20 h-1 bg-gradient-to-r from-[var(--color-gold)] to-[var(--color-gold-hover)] mx-auto rounded-full"></div>
        </div>

        <!-- Сетка достижений -->
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-6 mb-16">
            {achievements.map((stat) => (
                <div class="group bg-white/80 backdrop-blur-xl rounded-2xl p-6 md:p-8 shadow-lg border border-white/50 hover:shadow-2xl hover:shadow-[var(--color-blue-primary)]/10 hover:-translate-y-1 transition-all duration-500 text-center relative overflow-hidden">
                    <!-- Декоративный фон -->
                    <div class="absolute inset-0 bg-gradient-to-br from-[var(--color-blue-primary)]/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>

                    <div class="relative z-10">
                        <!-- Иконка -->
                        <div class="w-12 h-12 mx-auto bg-[var(--color-blue-primary)]/10 rounded-xl flex items-center justify-center mb-4 group-hover:bg-[var(--color-blue-primary)] transition-colors duration-300">
                            <svg class="w-6 h-6 text-[var(--color-blue-primary)] group-hover:text-white transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d={iconPaths[stat.icon]}/>
                            </svg>
                        </div>

                        <!-- Число -->
                        <div class="flex items-baseline justify-center gap-1 mb-2">
                            {stat.type !== 'support' ? (
                                <span class="stat-counter text-4xl md:text-5xl font-extrabold text-gray-900" data-target={stat.number}>
                                    0
                                </span>
                            ) : (
                                <span class="text-3xl md:text-4xl font-extrabold text-[var(--color-blue-primary)]">{stat.number}</span>
                            )}
                            <span class="text-2xl font-bold text-[var(--color-blue-primary)]">{stat.suffix}</span>
                        </div>

                        <!-- Текст -->
                        <span class="text-xs md:text-sm font-bold text-gray-500 uppercase tracking-wider">
                            {getStatText(stat)}
                        </span>
                    </div>
                </div>
            ))}
        </div>

        <!-- CTA Блок -->
        <div class="relative bg-gradient-to-r from-[var(--color-blue-primary)] to-blue-700 rounded-3xl p-8 md:p-12 text-center overflow-hidden shadow-2xl shadow-blue-500/30">
            <div class="relative z-10 max-w-2xl mx-auto">
                <h3 class="text-2xl md:text-3xl font-bold text-white mb-4">
                    Готовы обсудить вашу ситуацию?
                </h3>
                <p class="text-blue-100 mb-8">
                    Получите профессиональную консультацию адвоката уже сегодня
                </p>
                <button
                    data-consultation-modal
                    class="inline-block px-8 py-4 bg-white text-[var(--color-blue-primary)] font-bold rounded-xl hover:bg-gray-100 hover:scale-105 hover:shadow-xl transition-all duration-300 shadow-lg cursor-pointer"
                >
                    Получить консультацию
                </button>
            </div>
        </div>
    </div>
</section>

<script>
    const initStatsAnimation = () => {
        const counters = document.querySelectorAll<HTMLElement>('.stat-counter');
        if (!counters.length) return;

        const speed = 2000;

        const animate = (entries: IntersectionObserverEntry[], observer: IntersectionObserver) => {
            entries.forEach(entry => {
                if (!entry.isIntersecting) return;

                const counter = entry.target;
                const target = parseInt(counter.dataset.target || '0', 10);
                let startTime: number | null = null;

                const step = (timestamp: number) => {
                    if (!startTime) startTime = timestamp;
                    const progress = Math.min((timestamp - startTime) / speed, 1);
                    const ease = 1 - Math.pow(1 - progress, 3);
                    
                    counter.textContent = Math.floor(ease * target).toString();

                    if (progress < 1) {
                        requestAnimationFrame(step);
                    } else {
                        counter.textContent = target.toString();
                    }
                };

                requestAnimationFrame(step);
                observer.unobserve(counter);
            });
        };

        const observer = new IntersectionObserver(animate, {
            threshold: 0.5,
            rootMargin: '0px'
        });

        counters.forEach(counter => observer.observe(counter));
    };

    // Запускаем анимацию
    initStatsAnimation();
    
    // Для Astro View Transitions
    document.addEventListener('astro:after-swap', initStatsAnimation);
    document.addEventListener('astro:page-load', initStatsAnimation);
</script>