'use client';

import { animate, useInView, useReducedMotion } from 'framer-motion';
import { useEffect, useRef, useState } from 'react';

import { Container, Section } from '@/components/layout/container';
import { Reveal } from '@/components/motion/reveal';

// TODO replace with real data. All four figures are placeholders.
const stats = [
  { value: 40, prefix: '', suffix: '+', label: 'couriers supported' },
  { value: 200, prefix: '', suffix: '+', label: 'countries and regions' },
  { value: 30, prefix: 'under ', suffix: 's', label: 'average label time' },
  { value: 24, prefix: '', suffix: ' hour', label: 'support response' },
] as const;

function CountUp({ value, start }: { value: number; start: boolean }) {
  const reduce = useReducedMotion();
  const [current, setCurrent] = useState(0);

  useEffect(() => {
    if (!start) return undefined;
    const controls = animate(0, value, {
      duration: reduce ? 0 : 1.4,
      ease: [0.2, 0.8, 0.2, 1],
      onUpdate: (latest) => setCurrent(Math.round(latest)),
    });
    return () => controls.stop();
  }, [reduce, start, value]);

  return <span className="tabular-nums">{current}</span>;
}

export function StatsBand() {
  const ref = useRef<HTMLDivElement>(null);
  const inView = useInView(ref, { once: true, margin: '-80px' });

  return (
    <Section className="!py-6 md:!py-10">
      <Container>
        <Reveal>
          <div ref={ref} className="bg-ink relative overflow-hidden rounded-2xl px-6 py-12 text-primary-foreground shadow-lg md:px-12 md:py-14">
            <div className="pointer-events-none absolute inset-0 bg-grid opacity-[0.12] [--border:255_255_255]" aria-hidden="true" />
            <div className="pointer-events-none absolute -right-20 -top-24 h-64 w-64 rounded-full bg-accent/30 blur-3xl" aria-hidden="true" />
            <dl className="relative grid grid-cols-2 gap-x-6 gap-y-10 lg:grid-cols-4">
              {stats.map((stat) => (
                <div key={stat.label} className="flex flex-col lg:border-l lg:border-primary-foreground/10 lg:pl-6 lg:first:border-l-0 lg:first:pl-0">
                  <dt className="order-2 mt-2 text-[13px] text-primary-foreground/70">{stat.label}</dt>
                  <dd className="order-1 font-display text-[2.25rem] font-extrabold leading-none tracking-[-0.03em] text-primary-foreground md:text-display-lg">
                    {stat.prefix === '' ? null : <span className="mr-1 text-[0.45em] font-bold tracking-normal text-primary-foreground/70">{stat.prefix.trim()}</span>}
                    <CountUp value={stat.value} start={inView} />
                    <span className="text-[0.7em]">{stat.suffix}</span>
                  </dd>
                </div>
              ))}
            </dl>
          </div>
        </Reveal>
      </Container>
    </Section>
  );
}
