'use client'

import Link from 'next/link'
import { motion, useInView, useMotionValue, useSpring, useTransform } from 'framer-motion'
import { useRef, useEffect } from 'react'
import { Shield, CalendarPlus, CreditCard, KeyRound, Box, Crown, Warehouse, ArrowRight, Star } from 'lucide-react'
import PageTransition from '@/components/PageTransition'
import { services } from '@/lib/mock-data'
import { formatPrice } from '@/lib/utils'

// Animated counter
function AnimatedNumber({ value, suffix = '' }: { value: number; suffix?: string }) {
  const ref = useRef<HTMLSpanElement>(null)
  const motionValue = useMotionValue(0)
  const spring = useSpring(motionValue, { duration: 1200, bounce: 0 })
  const rounded = useTransform(spring, (v) => Math.round(v))
  const inView = useInView(ref, { once: true, margin: '-80px' })

  useEffect(() => {
    if (inView) motionValue.set(value)
  }, [inView, motionValue, value])

  return (
    <span ref={ref}>
      <motion.span>{rounded}</motion.span>
      {suffix}
    </span>
  )
}

const serviceIcons: Record<string, React.ReactNode> = {
  Box: <Box className="w-7 h-7" />,
  Crown: <Crown className="w-7 h-7" />,
  Warehouse: <Warehouse className="w-7 h-7" />,
}

const floatingVariants = {
  animate: (i: number) => ({
    y: [0, -18, 0],
    x: [0, i % 2 === 0 ? 10 : -10, 0],
    transition: {
      duration: 4 + i * 0.8,
      repeat: Infinity,
      ease: 'easeInOut',
    },
  }),
}

// Section animations removed — whileInView unreliable on SSG pages

export default function HomePage() {
  const steps = [
    {
      icon: <CalendarPlus className="w-7 h-7" />,
      title: 'Réservez votre créneau',
      desc: 'Choisissez votre espace et l\'horaire qui vous convient',
      color: 'bg-brand-50 text-brand-600',
    },
    {
      icon: <CreditCard className="w-7 h-7" />,
      title: 'Payez en ligne',
      desc: 'Caution sécurisée, vous ne payez que ce que vous consommez',
      color: 'bg-purple-50 text-purple-600',
    },
    {
      icon: <KeyRound className="w-7 h-7" />,
      title: 'Accédez instantanément',
      desc: 'Code PIN ou QR code, votre accès est prêt en 1 seconde',
      color: 'bg-emerald-50 text-emerald-600',
    },
  ]

  const statsData = [
    { label: 'réservations', value: 47, suffix: '' },
    { label: 'durée moyenne', value: 95, suffix: 'min' },
    { label: 'économisés', value: 124, suffix: '€' },
    { label: 'satisfaction', value: 98, suffix: '%' },
  ]

  return (
    <PageTransition>
      {/* Hero */}
      <section className="relative overflow-hidden bg-gradient-to-br from-brand-600 to-brand-900 text-white min-h-[88vh] flex items-center">
        {/* Floating blobs */}
        {[0, 1, 2, 3, 4].map((i) => (
          <motion.div
            key={i}
            custom={i}
            variants={floatingVariants}
            animate="animate"
            className="absolute rounded-full opacity-10 blur-2xl pointer-events-none"
            style={{
              width: `${120 + i * 60}px`,
              height: `${120 + i * 60}px`,
              background: i % 2 === 0 ? '#818cf8' : '#c7d2fe',
              top: `${10 + i * 15}%`,
              left: `${5 + i * 18}%`,
            }}
          />
        ))}

        <div className="relative z-10 max-w-6xl mx-auto px-4 py-20 text-center w-full">
          <motion.div
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.5 }}
            className="flex items-center justify-center gap-3 mb-6"
          >
            <div className="bg-white/20 rounded-2xl p-3 backdrop-blur-sm">
              <Shield className="w-8 h-8 text-white" />
            </div>
            <span className="text-2xl font-bold tracking-tight">SmartAccès</span>
          </motion.div>

          <motion.h1
            initial={{ opacity: 0, y: 24 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.15 }}
            className="text-4xl md:text-6xl font-bold leading-tight mb-5 max-w-3xl mx-auto"
          >
            Réservez, payez, accédez.{' '}
            <span className="text-brand-200">En toute autonomie.</span>
          </motion.h1>

          <motion.p
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.28 }}
            className="text-lg md:text-xl text-brand-100 max-w-xl mx-auto mb-10"
          >
            La solution intelligente pour un accès sécurisé à vos espaces, 24h/24.
          </motion.p>

          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.42 }}
          >
            <Link href="/reserver">
              <motion.span
                whileHover={{ scale: 1.04 }}
                whileTap={{ scale: 0.97 }}
                className="inline-flex items-center gap-2 bg-white text-brand-700 font-semibold px-8 py-4 rounded-2xl shadow-lg shadow-brand-900/30 text-lg cursor-pointer select-none"
              >
                Réserver un espace
                <ArrowRight className="w-5 h-5" />
              </motion.span>
            </Link>
          </motion.div>
        </div>
      </section>

      {/* Stats row */}
      <section className="bg-white border-b border-gray-100">
        <div className="max-w-6xl mx-auto px-4 py-10 grid grid-cols-2 md:grid-cols-4 gap-6">
          {statsData.map((stat, i) => (
            <div key={i} className="text-center">
              <p className="text-3xl md:text-4xl font-bold text-brand-600">
                <AnimatedNumber value={stat.value} suffix={stat.suffix} />
              </p>
              <p className="text-sm text-gray-500 mt-1 capitalize">{stat.label}</p>
            </div>
          ))}
        </div>
      </section>

      {/* Comment ça marche */}
      <section className="bg-gray-50 py-20 px-4">
        <div className="max-w-6xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-3">Comment ça marche</h2>
            <p className="text-gray-500 text-base max-w-sm mx-auto">Trois étapes, c&apos;est tout.</p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {steps.map((step, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, y: 24 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, delay: 0.6 + i * 0.15 }}
                className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100 relative"
              >
                <div className="absolute -top-3 -left-3 w-8 h-8 bg-brand-600 text-white text-sm font-bold rounded-full flex items-center justify-center shadow">
                  {i + 1}
                </div>
                <div className={`w-14 h-14 rounded-xl ${step.color} flex items-center justify-center mb-4`}>
                  {step.icon}
                </div>
                <h3 className="font-semibold text-gray-900 mb-2 text-base">{step.title}</h3>
                <p className="text-gray-500 text-sm leading-relaxed">{step.desc}</p>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* Services preview */}
      <section className="bg-white py-20 px-4">
        <div className="max-w-6xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-3">Nos espaces</h2>
            <p className="text-gray-500 text-base max-w-sm mx-auto">
              Des espaces adaptés à chaque besoin, disponibles immédiatement.
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {services.map((service, i) => (
              <motion.div
                key={service.id}
                initial={{ opacity: 0, y: 24 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, delay: 0.8 + i * 0.12 }}
                className="bg-gray-50 rounded-2xl p-6 border border-gray-100 flex flex-col gap-4"
              >
                <div className="flex items-start justify-between">
                  <div className="bg-brand-50 text-brand-600 w-12 h-12 rounded-xl flex items-center justify-center">
                    {serviceIcons[service.icon]}
                  </div>
                  <span className="flex items-center gap-1.5 text-sm">
                    <span
                      className={`w-2 h-2 rounded-full ${
                        service.available > 0 ? 'bg-emerald-400' : 'bg-red-400'
                      }`}
                    />
                    <span className={service.available > 0 ? 'text-emerald-600' : 'text-red-500'}>
                      {service.available > 0 ? `${service.available} disponible(s)` : 'Complet'}
                    </span>
                  </span>
                </div>

                <div>
                  <h3 className="font-semibold text-gray-900 text-base mb-1">{service.name}</h3>
                  <p className="text-sm text-gray-500 leading-relaxed">{service.description}</p>
                </div>

                <div className="flex items-center justify-between mt-auto">
                  <div>
                    <p className="text-lg font-bold text-brand-600">
                      {formatPrice(service.pricePerHour)}<span className="text-sm font-normal text-gray-400">/h</span>
                    </p>
                    <p className="text-xs text-gray-400">Caution : {formatPrice(service.deposit)}</p>
                  </div>

                  <Link href={`/reserver?service=${service.id}`}>
                    <motion.span
                      whileHover={{ scale: 1.04 }}
                      whileTap={{ scale: 0.97 }}
                      className="inline-flex items-center gap-1.5 bg-brand-600 text-white text-sm font-semibold px-4 py-2 rounded-xl cursor-pointer select-none"
                    >
                      Réserver
                      <ArrowRight className="w-4 h-4" />
                    </motion.span>
                  </Link>
                </div>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* Footer CTA */}
      <section className="bg-gradient-to-br from-brand-700 to-brand-950 py-20 px-4">
        <div className="max-w-xl mx-auto text-center">
          <div className="flex items-center justify-center gap-1 mb-4">
            {[...Array(5)].map((_, i) => (
              <Star key={i} className="w-5 h-5 text-yellow-400 fill-yellow-400" />
            ))}
          </div>
          <h2 className="text-3xl md:text-4xl font-bold text-white mb-4">
            Prêt à commencer ?
          </h2>
          <p className="text-brand-200 mb-10 text-base">
            Accédez à votre espace en moins de 2 minutes. Sans attente, sans intermédiaire.
          </p>
          <Link href="/reserver">
            <motion.span
              whileHover={{ scale: 1.04 }}
              whileTap={{ scale: 0.97 }}
              className="inline-flex items-center gap-2 bg-white text-brand-700 font-semibold px-8 py-4 rounded-2xl shadow-lg text-lg cursor-pointer select-none"
            >
              Réserver maintenant
              <ArrowRight className="w-5 h-5" />
            </motion.span>
          </Link>
        </div>
      </section>
    </PageTransition>
  )
}
