import { useState, useRef, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { captureUTMParams } from '@/lib/analytics'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { ArrowRight, Sparkles, Check } from 'lucide-react'

const HERO_TESTIMONIALS = [
  { name: 'Sarah M.', quote: 'Inbox finally under control.', position: 'top-20 -left-10', rotate: '-20deg', side: 'left' as const },
  { name: 'Tom K.', quote: 'Newsletters sorted automatically.', position: 'top-1/2 -left-10 -translate-y-1/2', rotate: '-10deg', side: 'left' as const },
  { name: 'Lisa R.', quote: 'Leads never get lost again.', position: 'top-20 -right-10', rotate: '20deg', side: 'right' as const },
  { name: 'Jan P.', quote: 'Game changer for freelancers.', position: 'bottom-20 -left-10', rotate: '-10deg', side: 'left' as const },
  { name: 'Anna L.', quote: 'Gmail & Outlook in one place.', position: 'bottom-1/2 -right-10 -translate-y-1/2', rotate: '10deg', side: 'right' as const },
  { name: 'Max B.', quote: 'Spam stays out of my inbox.', position: 'bottom-20 -right-10', rotate: '20deg', side: 'right' as const },
]

function useScrollBow(heroRef: React.RefObject<HTMLElement | null>) {
  const [progress, setProgress] = useState(0)
  useEffect(() => {
    const hero = heroRef?.current
    if (!hero) return
    
    let rafId: number | null = null
    const onScroll = () => {
      if (rafId !== null) return
      rafId = requestAnimationFrame(() => {
        const rect = hero.getBoundingClientRect()
        const h = rect.height
        if (h <= 0) {
          rafId = null
          return
        }
        const p = Math.max(0, Math.min(1, -rect.top / h))
        setProgress((prev) => {
          if (Math.abs(prev - p) > 0.05) {
            return p
          }
          return prev
        })
        rafId = null
      })
    }
    onScroll()
    window.addEventListener('scroll', onScroll, { passive: true })
    return () => {
      window.removeEventListener('scroll', onScroll)
      if (rafId !== null) cancelAnimationFrame(rafId)
    }
  }, [heroRef])
  return progress
}

type TestimonialItem = (typeof HERO_TESTIMONIALS)[number]

function HeroEdgeCard({ name, quote, position, rotate, side, scrollProgress }: TestimonialItem & { scrollProgress: number }) {
  const dropY = scrollProgress * 80
  const flyOutX = scrollProgress * 600
  const moveX = side === 'left' ? -flyOutX : flyOutX
  const transform = `translate(${moveX}px, ${dropY}px) rotate(${rotate})`
  const opacity = Math.max(0, 1 - scrollProgress * 1.2)
  const visibility = opacity <= 0 ? 'hidden' : 'visible'
  const styleOpacity = scrollProgress > 0 ? opacity : undefined
  return (
    <div
      className={cn(
        'hero-edge-card absolute z-20 flex items-center gap-1 rounded-md bg-white p-1 shadow-md dark:bg-slate-800 border border-slate-200 dark:border-slate-700',
        position,
        'hidden md:flex transition-all duration-200 ease-out'
      )}
      style={{ transform, ...(styleOpacity !== undefined ? { opacity: styleOpacity } : {}), visibility }}
    >
      <img
        alt="E-Mail"
        width={128}
        height={128}
        className="h-auto max-h-32 w-32 shrink-0 object-contain object-center block m-0"
        src="/logo.png"
      />
      <div className="max-w-[160px]">
        <h3 className="text-sm font-medium text-slate-800 dark:text-slate-200">{name}</h3>
        <p className="text-xs text-slate-600 dark:text-slate-400">{quote}</p>
      </div>
    </div>
  )
}

export function Hero() {
  const navigate = useNavigate()
  const heroRef = useRef<HTMLElement>(null)
  const scrollProgress = useScrollBow(heroRef)

  const handleCTAClick = () => {
    // Capture UTM parameters before navigation
    captureUTMParams()
    navigate('/register')
  }

  return (
    <section ref={heroRef} className="relative min-h-screen flex items-center overflow-hidden">
      {/* Edge cards – stick to sides, animate on scroll (bow out) */}
      {HERO_TESTIMONIALS.map((t) => (
        <HeroEdgeCard key={t.name} {...t} scrollProgress={scrollProgress} />
      ))}

      {/* Background – unchanged */}
      <div className="absolute inset-0 gradient-hero" />
      <div className="absolute inset-0 gradient-mesh opacity-30" />
      
      {/* Grid pattern overlay */}
      <div 
        className="absolute inset-0 opacity-10"
        style={{
          backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        }}
      />

      <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-32">
        <div className="grid lg:grid-cols-2 gap-12 items-center">
          {/* Left side - Text content */}
          <div className="text-center lg:text-left">
            <Badge className="mb-6 bg-primary-500/20 text-primary-200 border-primary-400/30">
              <Sparkles className="w-3 h-3 mr-1" />
              For freelancers & small teams
            </Badge>
            
            <h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold text-white leading-tight mb-6">
              Leads, clients, spam —
              <br />
              <span className="text-transparent bg-clip-text bg-gradient-to-r from-accent-400 to-primary-300">
                sorted automatically.
              </span>
            </h1>
            
            <p className="text-lg sm:text-xl text-slate-300 mb-8 max-w-xl mx-auto lg:mx-0">
              Connect Gmail or Outlook. We put newsletters, promos, and noise in folders so your inbox stays for what pays.
            </p>

            <div className="flex flex-col sm:flex-row gap-4 justify-center lg:justify-start mb-4">
              <Button 
                size="xl" 
                onClick={handleCTAClick}
                className="group bg-accent-500 hover:bg-accent-600"
              >
                Try it free
                <ArrowRight className="w-5 h-5 ml-2 group-hover:translate-x-1 transition-transform" />
              </Button>
            </div>
            <p className="text-sm text-slate-400 mb-8">
              <button
                type="button"
                onClick={() => navigate('/setup?demo=true')}
                className="underline hover:text-slate-300 transition-colors"
              >
                Or try a 30-second demo first
              </button>
            </p>

            {/* Trust badges */}
            <div className="flex flex-wrap gap-6 justify-center lg:justify-start text-slate-400 text-sm">
              <div className="flex items-center gap-2">
                <Check className="w-4 h-4 text-accent-400" />
                No credit card
              </div>
              <div className="flex items-center gap-2">
                <Check className="w-4 h-4 text-accent-400" />
                Gmail & Outlook
              </div>
              <div className="flex items-center gap-2">
                <Check className="w-4 h-4 text-accent-400" />
                GDPR compliant
              </div>
            </div>
          </div>

          {/* Right side - Inbox visual (product screenshot feel) */}
          <div className="relative hidden lg:block">
            <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 max-w-md overflow-hidden">
              <div className="border-b border-slate-200 dark:border-slate-700 px-4 py-2.5">
                <span className="text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Inbox</span>
              </div>
              <div className="divide-y divide-slate-100 dark:divide-slate-800">
                <InboxRow sender="Sarah Chen" subject="Re: Project quote" label="Lead" isFocal />
                <InboxRow sender="Mike, Acme Inc" subject="Invoice #8821" label="Client" />
                <InboxRow sender="Newsletter" subject="Your weekly digest" label="Noise" />
                <InboxRow sender="Support" subject="Your ticket #443" label="Client" />
                <InboxRow sender="Promo" subject="20% off this week" label="Noise" />
              </div>
              <p className="text-xs text-slate-400 dark:text-slate-500 px-4 py-3 border-t border-slate-100 dark:border-slate-800">
                This happens automatically on new emails.
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Scroll indicator */}
      <div className="absolute bottom-8 left-1/2 -translate-x-1/2 animate-bounce">
        <div className="w-6 h-10 rounded-full border-2 border-white/30 flex justify-center pt-2">
          <div className="w-1.5 h-1.5 rounded-full bg-white/60" />
        </div>
      </div>
    </section>
  )
}

type InboxLabel = 'Lead' | 'Client' | 'Noise'

const labelClass: Record<InboxLabel, string> = {
  Lead: 'text-primary-600 dark:text-primary-500',
  Client: 'text-slate-600 dark:text-slate-600',
  Noise: 'text-slate-400 dark:text-slate-500',
}

interface InboxRowProps {
  sender: string
  subject: string
  label: InboxLabel
  isFocal?: boolean
}

function InboxRow({ sender, subject, label, isFocal = false }: InboxRowProps) {
  return (
    <div
      className={cn(
        "flex items-center gap-4 px-4 py-2.5",
        isFocal && "border-l-2 border-l-primary-500 bg-slate-50/80 dark:bg-slate-800/50"
      )}
    >
      <div className="flex-1 min-w-0">
        <p className={cn(
          "truncate",
          isFocal ? "text-sm font-semibold text-slate-900 dark:text-slate-100" : "text-sm font-medium text-slate-600 dark:text-slate-400"
        )}>
          {sender}
        </p>
        <p className="text-xs text-slate-500 dark:text-slate-500 truncate mt-0.5">{subject}</p>
      </div>
      <span className={cn("text-xs flex-shrink-0", labelClass[label])}>{label}</span>
    </div>
  )
}
