"use client"

import { useState, useRef, useCallback, useEffect } from "react"
import type { SaflStatsData } from "@/lib/strapi/types"
import { SectionBadge, ArrowButton } from "./shared"

export default function SaflStats({ data }: { data: SaflStatsData }) {
  const [statsPage, setStatsPage] = useState(0)
  const statsScrollRef = useRef<HTMLDivElement>(null)

  const handleStatsScroll = useCallback(() => {
    if (!statsScrollRef.current) return
    const { scrollLeft } = statsScrollRef.current
    const card = statsScrollRef.current.querySelector<HTMLElement>("[data-stat-card]")
    const cardWidth = card?.offsetWidth || 280
    const gap = window.innerWidth >= 800 ? 24 : 16
    const page = Math.round(scrollLeft / (cardWidth + gap))
    setStatsPage(Math.min(page, data.stats.length - 1))
  }, [data.stats.length])

  const scrollStats = useCallback((direction: "left" | "right") => {
    if (!statsScrollRef.current) return
    const card = statsScrollRef.current.querySelector<HTMLElement>("[data-stat-card]")
    const cardWidth = card?.offsetWidth || 280
    const gap = window.innerWidth >= 800 ? 24 : 16
    statsScrollRef.current.scrollBy({
      left: direction === "right" ? cardWidth + gap : -(cardWidth + gap),
      behavior: "smooth",
    })
  }, [])

  useEffect(() => {
    const el = statsScrollRef.current
    if (!el) return
    el.addEventListener("scroll", handleStatsScroll, { passive: true })
    return () => el.removeEventListener("scroll", handleStatsScroll)
  }, [handleStatsScroll])

  return (
    <section className="max-w-[1296px] mx-auto px-4 lg:px-0 py-8 lg:py-16">
      <div className="flex flex-col gap-[56px]">
        {/* Header */}
        <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-5 lg:gap-6">
          <SectionBadge label={data.badge} variant="gray" icon={data.badgeIcon} />
          <div className="flex flex-col gap-4 lg:gap-6 w-full lg:w-[417px]">
            <p className="text-[16px] text-[rgba(32,38,43,0.6)] leading-[1.5]">
              {data.description}
            </p>
            <div className="w-full h-px bg-[#e5e7eb]" />
          </div>
        </div>

        {/* Stats cards + navigation */}
        <div className="flex flex-col gap-6">
          <div className="-mr-4 lg:mr-0">
            <div
              ref={statsScrollRef}
              className="flex gap-4 lg:gap-6 overflow-x-auto scrollbar-hide snap-x snap-mandatory scroll-smooth pb-4"
            >
              {data.stats.map((stat, i) => (
                <div
                  key={i}
                  data-stat-card
                  className="flex-shrink-0 w-[80vw] lg:w-[calc((100%-48px)/3)] h-[224px] lg:h-[299px] rounded-[16px] border border-[rgba(229,231,235,0.5)] overflow-hidden relative flex flex-col items-start justify-end snap-start"
                  style={{
                    backgroundImage: `url("data:image/svg+xml;utf8,<svg viewBox='0 0 416 299' xmlns='http://www.w3.org/2000/svg' preserveAspectRatio='none'><rect x='0' y='0' height='100%25' width='100%25' fill='url(%23grad)' opacity='1'/><defs><radialGradient id='grad' gradientUnits='userSpaceOnUse' cx='0' cy='0' r='10' gradientTransform='matrix(19.089 -22.582 31.418 21.011 173.24 250.94)'><stop stop-color='rgba(255,232,233,0)' offset='0'/><stop stop-color='rgba(255,232,233,1)' offset='1'/></radialGradient></defs></svg>"), linear-gradient(90deg, #fff 0%, #fff 100%)`,
                  }}
                >
                  {stat.vector ? (
                    <img
                      src={stat.vector}
                      alt=""
                      loading="lazy"
                      className="absolute right-0 top-0 w-[105px] h-[100px] pointer-events-none object-contain"
                      aria-hidden="true"
                    />
                  ) : null}
                  <div className="relative z-10 px-4 lg:px-6 pb-4 lg:pb-6 pt-4 lg:pt-6 flex flex-col gap-2 w-full">
                    <div className="flex flex-col font-bold">
                      <span className="font-accent text-[#20262b] text-[64px] lg:text-[96px] leading-none">
                        {stat.number}
                      </span>
                      <span className="font-accent text-[#20262b] text-[28px] lg:text-[32px] leading-normal">
                        {stat.suffix}
                      </span>
                    </div>
                    <p className="text-[14px] lg:text-[16px] text-[rgba(32,38,43,0.8)] leading-[18px] max-w-[319px]">
                      {stat.description}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Arrows */}
          <div className="flex items-center justify-end w-full pr-4 lg:pr-0">
            <div className="flex items-center gap-[13px]">
              <ArrowButton direction="left" disabled={statsPage === 0} onClick={() => scrollStats("left")} />
              <ArrowButton
                direction="right"
                disabled={statsPage >= data.stats.length - 1}
                onClick={() => scrollStats("right")}
              />
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}
