'use client';

import { useEffect, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';

const stats = [
  { value: 1240, suffix: '+', prefix: '', key: 'users', accent: 'bg-violet-100 text-violet-600' },
  { value: 8700, suffix: '+', prefix: '', key: 'searches', accent: 'bg-blue-100 text-blue-600' },
  { value: 31400, suffix: '+', prefix: '€', key: 'saved', accent: 'bg-emerald-100 text-emerald-600' },
];

function useCountUp(target: number, duration = 1800, started: boolean) {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (!started) return;
    let startTime: number | null = null;
    const step = (timestamp: number) => {
      if (!startTime) startTime = timestamp;
      const progress = Math.min((timestamp - startTime) / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setCount(Math.floor(eased * target));
      if (progress < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
  }, [started, target, duration]);

  return count;
}

function StatCard({
  value, suffix, prefix, description, started,
}: { value: number; suffix: string; prefix: string; description: string; started: boolean }) {
  const count = useCountUp(value, 1800, started);
  const formatted = count >= 1000 ? count.toLocaleString('en-US') : count.toString();

  return (
    <div className="flex-1 flex flex-col items-center text-center px-4 py-8 gap-3 sm:px-10 sm:py-12">
      <div className="text-4xl font-bold text-white tracking-tight tabular-nums leading-none">
        {prefix}{formatted}{suffix}
      </div>
      <p className="text-sm text-white/40 leading-relaxed max-w-[180px]">{description}</p>
    </div>
  );
}

export default function StatisticsSection() {
  const [started, setStarted] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const t = useTranslations('statistics');

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setStarted(true); observer.disconnect(); } },
      { threshold: 0.3 }
    );
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);

  return (
    <section className="py-16 bg-purple-900">
      <div className="max-w-6xl mx-auto px-4 sm:px-6">
        <h2 className="text-2xl font-bold text-white text-center mb-12">
          {t('heading')}
        </h2>

        <div
          ref={ref}
          className="flex flex-col md:flex-row items-stretch rounded-3xl overflow-hidden divide-y md:divide-y-0 md:divide-x divide-white/10"
        >
          {stats.map(({ key, ...rest }) => (
            <StatCard
              key={key}
              {...rest}
              description={t(`${key}.description`)}
              started={started}
            />
          ))}
        </div>

        <div className="flex justify-center mt-10">
          <button
            onClick={() => {
              const el = document.getElementById('pricing-section');
              if (el) window.scrollTo({ top: el.offsetTop - 57, behavior: 'smooth' });
            }}
            className="bg-brand-yellow hover:bg-brand-yellow-dark text-gray-900 font-medium text-sm px-6 py-2.5 rounded-md transition-colors"
          >
            {t('cta')}
          </button>
        </div>
      </div>
    </section>
  );
}
