'use client'

import { useEffect, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { SectionHeader } from '@/components/ui/SectionHeader'

type Node = {
  icon: string
  title: string
  desc: string
  metric: string
  log: string
}

const NODES: Node[] = [
  {
    icon: '📱',
    title: 'Customer Books',
    desc: 'Resident places order via Nearle Deal app',
    metric: 'Active Status',
    log: '// Geofence matched. Nearest 3 stores pinged...',
  },
  {
    icon: '🏪',
    title: 'Store Receives',
    desc: 'Nearest verified store gets instant notification',
    metric: 'Verified Store',
    log: '// Push notification delivered. ETA: 45s...',
  },
  {
    icon: '✔️',
    title: 'Store Confirms',
    desc: 'Store accepts and begins packing the order',
    metric: 'Live Packing',
    log: '// Inventory verified. Packing initiated...',
  },
  {
    icon: '💳',
    title: 'Payment Processed',
    desc: 'Secure digital settlement: 95% merchant, 5% fleet',
    metric: 'Direct Settlement',
    log: '// Escrow verified. Payout queued...',
  },
  {
    icon: '🏍️',
    title: 'Rider Picks Up',
    desc: 'Gear rider collects and begins last-mile delivery',
    metric: 'Route Optimized',
    log: '// Route optimized. Rider en route...',
  },
  {
    icon: '🏠',
    title: 'Delivered',
    desc: "Order reaches resident's door. Trust confirmed.",
    metric: '< 30 min',
    log: '// Delivery confirmed. Rating prompt sent...',
  },
]

function TypewriterLog({ text }: { text: string }) {
  const [displayed, setDisplayed] = useState('')

  useEffect(() => {
    setDisplayed('')
    let idx = 0
    const interval = setInterval(() => {
      setDisplayed((d) => d + text.charAt(idx))
      idx++
      if (idx >= text.length) {
        clearInterval(interval)
      }
    }, 20)
    return () => clearInterval(interval)
  }, [text])

  return (
    <span className="font-mono text-[11px] sm:text-xs flex items-center gap-1.5 text-emerald-400">
      <span>{displayed}</span>
      <span className="w-1.5 h-3.5 bg-emerald-400 inline-block shrink-0 animate-[blink_1s_infinite]" />
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes blink {
          0%, 100% { opacity: 1; }
          50% { opacity: 0; }
        }
      `}} />
    </span>
  )
}

function DetailsCard({ activeNode, activeIndex }: { activeNode: Node; activeIndex: number }) {
  const [rotate, setRotate] = useState({ x: 0, y: 0 })
  const [shine, setShine] = useState({ x: 0, y: 0, opacity: 0 })

  function handleMouseMove(e: React.MouseEvent<HTMLDivElement>) {
    const el = e.currentTarget
    const r = el.getBoundingClientRect()
    const x = e.clientX - r.left
    const y = e.clientY - r.top

    // Smooth angle calculations (tilt range -6 to 6 deg)
    const rx = -((y / r.height) - 0.5) * 12
    const ry = ((x / r.width) - 0.5) * 12

    setRotate({ x: rx, y: ry })
    setShine({ x, y, opacity: 0.15 })
  }

  function handleMouseLeave() {
    setRotate({ x: 0, y: 0 })
    setShine({ x: 0, y: 0, opacity: 0 })
  }

  return (
    <motion.div
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      style={{
        transformStyle: 'preserve-3d',
        transform: `perspective(1000px) rotateX(${rotate.x}deg) rotateY(${rotate.y}deg)`,
        transition: 'transform 0.1s ease-out',
      }}
      className="relative bg-white rounded-3xl border border-nearle-border shadow-nearle-sm p-8 overflow-hidden select-none"
    >
      {/* Light shine overlay */}
      <div
        className="absolute pointer-events-none rounded-full"
        style={{
          width: '320px',
          height: '320px',
          background: 'radial-gradient(circle, rgba(164,103,183,0.15) 0%, rgba(255,255,255,0) 70%)',
          left: `${shine.x - 160}px`,
          top: `${shine.y - 160}px`,
          opacity: shine.opacity,
          transition: 'opacity 0.2s ease',
        }}
      />

      <div className="flex items-center justify-between flex-wrap gap-3" style={{ transform: 'translateZ(10px)' }}>
        <span className="font-mono text-xs tracking-widest uppercase text-purple-primary">
          Step 0{activeIndex + 1} of 06
        </span>
        <span className="bg-purple-soft text-purple-deep border border-purple-lavender/30 rounded-full px-3 py-1 font-mono text-[11px] tracking-widest uppercase shadow-nearle-xs">
          {activeNode.metric}
        </span>
      </div>

      <h3 className="h3-display text-nearle-dark mt-4" style={{ transform: 'translateZ(20px)' }}>
        {activeNode.title}
      </h3>

      <p className="font-body text-nearle-mid mt-3 leading-relaxed" style={{ transform: 'translateZ(15px)' }}>
        {activeNode.desc}
      </p>

      <div
        className="mt-6 inline-flex items-center bg-[#0C0614] text-emerald-300 rounded-full px-5 py-2.5 font-mono text-xs shadow-nearle-sm border border-purple-deep/10"
        style={{ transform: 'translateZ(25px)' }}
      >
        <TypewriterLog text={activeNode.log} />
      </div>
    </motion.div>
  )
}

export function OrderLifecycle() {
  const [active, setActive] = useState(0)
  const [prevActive, setPrevActive] = useState(0)
  const [tilt, setTilt] = useState(0)

  useEffect(() => {
    const id = setInterval(() => {
      setActive((a) => (a + 1) % NODES.length)
    }, 4500)
    return () => clearInterval(id)
  }, [])

  useEffect(() => {
    if (active > prevActive) {
      setTilt(12) // Lean forward
      const t = setTimeout(() => setTilt(0), 650)
      return () => clearTimeout(t)
    } else if (active < prevActive) {
      setTilt(-12) // Lean backward
      const t = setTimeout(() => setTilt(0), 650)
      return () => clearTimeout(t)
    }
  }, [active, prevActive])

  // Track previous step to identify travel direction
  useEffect(() => {
    setPrevActive(active)
  }, [active])

  return (
    <div className="bg-nearle-bgsoft py-24 sm:py-32 px-5 sm:px-8 relative overflow-hidden">
      <div className="absolute inset-0 bg-grid-soft opacity-30 pointer-events-none" />

      <div className="max-w-7xl mx-auto relative z-10">
        <SectionHeader
          label="Order Lifecycle"
          heading="How your order travels"
          sub="Watch the real order journey — the Nearle delivery chain"
          align="center"
        />

        <div className="mt-20 relative">
          {/* Animated 3D/gliding road track for desktop views */}
          <div className="hidden md:block absolute top-[36px] left-[8.33%] right-[8.33%] h-2 -translate-y-1/2">
            <svg width="100%" height="8" className="overflow-visible">
              <defs>
                <linearGradient id="road-progress-grad" x1="0%" y1="0%" x2="100%" y2="0%">
                  <stop offset="0%" stopColor="#683285" />
                  <stop offset="100%" stopColor="#A467B7" />
                </linearGradient>
              </defs>
              {/* Ground Road Track */}
              <line
                x1="0"
                y1="4"
                x2="100%"
                y2="4"
                stroke="#F1EEF4"
                strokeWidth="6"
                strokeLinecap="round"
              />
              {/* Dashlane inside road */}
              <line
                x1="0"
                y1="4"
                x2="100%"
                y2="4"
                stroke="#E2D6EC"
                strokeWidth="2"
                strokeDasharray="4 6"
              />
              {/* Dynamic Fills Glowing Progress */}
              <motion.line
                x1="0"
                y1="4"
                x2={`${(active / 5) * 100}%`}
                y2="4"
                stroke="url(#road-progress-grad)"
                strokeWidth="6"
                strokeLinecap="round"
                animate={{ x2: `${(active / 5) * 100}%` }}
                transition={{ type: 'spring', stiffness: 90, damping: 16 }}
              />
            </svg>

            {/* Gliding scooter rider on road */}
            <motion.div
              className="absolute top-1/2 w-10 h-10 rounded-full bg-white border-2 border-purple-primary shadow-[0_4px_16px_rgba(104,50,133,0.22)] flex items-center justify-center text-xl z-20 overflow-hidden"
              style={{
                y: '-50%',
                x: '-50%',
              }}
              animate={{
                left: `${(active / 5) * 100}%`,
                rotate: tilt,
              }}
              transition={{
                left: { type: 'spring', stiffness: 90, damping: 16 },
                rotate: { type: 'spring', stiffness: 100, damping: 10 },
              }}
            >
              <AnimatePresence mode="wait">
                <motion.span
                  key={active}
                  initial={{ scale: 0, rotate: -45, opacity: 0 }}
                  animate={{ scale: 1, rotate: 0, opacity: 1 }}
                  exit={{ scale: 0, rotate: 45, opacity: 0 }}
                  transition={{ duration: 0.22, ease: 'easeOut' }}
                  className="inline-block"
                >
                  {active === 0 && '📱'}
                  {active === 1 && '🏪'}
                  {active === 2 && '📦'}
                  {active === 3 && '💳'}
                  {active === 4 && '🛵'}
                  {active === 5 && '🛵'}
                </motion.span>
              </AnimatePresence>
            </motion.div>
          </div>

          <ol className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-y-10 gap-x-4 relative">
            {NODES.map((node, i) => (
              <li
                key={node.title}
                className="flex flex-col items-center text-center cursor-pointer group"
                onClick={() => {
                  setPrevActive(active)
                  setActive(i)
                }}
              >
                <div className="relative">
                  <motion.div
                    animate={{
                      scale: i === active ? 1.08 : 1,
                      y: i === active ? [0, -3, 0] : 0,
                    }}
                    transition={{
                      scale: { duration: 0.35 },
                      y: i === active ? { duration: 3, repeat: Infinity, ease: 'easeInOut' } : { duration: 0.3 },
                    }}
                    className={`relative z-10 w-18 h-18 rounded-full flex items-center justify-center text-2xl border-2 transition-all ${
                      i === active
                        ? 'bg-purple-deep text-white border-purple-deep shadow-[0_8px_20px_rgba(104,50,133,0.25)]'
                        : i < active
                          ? 'bg-purple-soft/90 text-purple-deep border-purple-primary/40 shadow-nearle-xs'
                          : 'bg-white/70 backdrop-blur-sm text-nearle-mid border-nearle-border hover:border-purple-primary hover:bg-white'
                    }`}
                  >
                    <span>{node.icon}</span>
                  </motion.div>
                  {i === active && (
                    <>
                      <motion.span
                        className="absolute inset-0 rounded-full border-2 border-purple-primary"
                        animate={{ scale: [1, 1.35], opacity: [0.6, 0] }}
                        transition={{ duration: 1.8, repeat: Infinity, ease: 'easeOut' }}
                      />
                      <motion.span
                        className="absolute inset-0 rounded-full border-2 border-purple-primary"
                        animate={{ scale: [1, 1.6], opacity: [0.35, 0] }}
                        transition={{ duration: 1.8, repeat: Infinity, ease: 'easeOut', delay: 0.5 }}
                      />
                    </>
                  )}
                </div>
                <span className="font-mono text-[9px] text-purple-primary tracking-widest uppercase mt-4 font-bold">
                  Step 0{i + 1}
                </span>
                <span className="font-display font-extrabold text-sm text-nearle-dark mt-1 group-hover:text-purple-primary transition-colors">
                  {node.title}
                </span>
              </li>
            ))}
          </ol>
        </div>

        <div className="mt-16 max-w-3xl mx-auto">
          <AnimatePresence mode="wait">
            <motion.div
              key={active}
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -12 }}
              transition={{ duration: 0.3 }}
            >
              <DetailsCard activeNode={NODES[active]!} activeIndex={active} />
            </motion.div>
          </AnimatePresence>
        </div>
      </div>
    </div>
  )
}
