'use client'

import { useEffect, useState, useMemo, useRef } from 'react'
import { useParams } from 'next/navigation'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import {
  ArrowLeft,
  TrendingUp,
  TrendingDown,
  Minus,
  Calendar,
  Globe,
  Building,
  ExternalLink,
  Search,
  ChevronRight,
  Check,
  X,
  Lock,
  RefreshCw,
  Clock,
  Shield,
  Zap,
  AlertTriangle,
  Sparkles,
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface TldDetails {
  tld: string
  type: string
  description: string
  registry: string
  introduced: number
  trend: string
  trend_reason: string
  pricing: {
    avg: number
    min: number
    max: number
  }
  registrars: Array<{
    name: string
    registration_price: number
    renewal_price: number
    transfer_price: number
  }>
  cheapest_registrar: string
  // New fields from table
  min_renewal_price: number
  price_change_1y: number
  price_change_3y: number
  risk_level: 'low' | 'medium' | 'high'
  risk_reason: string
}

interface TldHistory {
  tld: string
  type?: string
  description?: string
  registry?: string
  current_price: number
  price_change_7d: number
  price_change_30d: number
  price_change_90d: number
  trend: string
  trend_reason: string
  history: Array<{
    date: string
    price: number
  }>
  source?: string
}

interface DomainCheckResult {
  domain: string
  is_available: boolean
  status: string
  registrar?: string | null
  creation_date?: string | null
  expiration_date?: string | null
}

// Registrar URLs
const REGISTRAR_URLS: Record<string, string> = {
  'Namecheap': 'https://www.namecheap.com/domains/registration/results/?domain=',
  'Porkbun': 'https://porkbun.com/checkout/search?q=',
  'Cloudflare': 'https://www.cloudflare.com/products/registrar/',
  'Google Domains': 'https://domains.google.com/registrar/search?searchTerm=',
  'GoDaddy': 'https://www.godaddy.com/domainsearch/find?domainToCheck=',
  'porkbun': 'https://porkbun.com/checkout/search?q=',
  'Dynadot': 'https://www.dynadot.com/domain/search?domain=',
  'Hover': 'https://www.hover.com/domains/results?q=',
}

// Related TLDs
const RELATED_TLDS: Record<string, string[]> = {
  'com': ['net', 'org', 'co', 'io'],
  'net': ['com', 'org', 'io', 'dev'],
  'org': ['com', 'net', 'ngo', 'foundation'],
  'io': ['dev', 'app', 'tech', 'ai'],
  'ai': ['io', 'tech', 'dev', 'ml'],
  'dev': ['io', 'app', 'tech', 'code'],
  'app': ['dev', 'io', 'mobile', 'software'],
  'co': ['com', 'io', 'biz', 'inc'],
  'de': ['at', 'ch', 'eu', 'com'],
  'ch': ['de', 'at', 'li', 'eu'],
}

type ChartPeriod = '1M' | '3M' | '1Y' | 'ALL'

// Shimmer component
function Shimmer({ className }: { className?: string }) {
  return (
    <div className={clsx(
      "relative overflow-hidden rounded bg-white/5",
      className
    )}>
      <div className="absolute inset-0 -translate-x-full animate-[shimmer_2s_infinite] bg-gradient-to-r from-transparent via-white/10 to-transparent" />
    </div>
  )
}

// Premium Chart Component with real data
function PriceChart({ 
  data, 
  isAuthenticated,
  chartStats,
}: { 
  data: Array<{ date: string; price: number }>
  isAuthenticated: boolean
  chartStats: { high: number; low: number; avg: number }
}) {
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
  const [tooltipPos, setTooltipPos] = useState({ x: 0, y: 0 })
  const containerRef = useRef<HTMLDivElement>(null)

  if (!isAuthenticated) {
    return (
      <div className="relative h-48 flex items-center justify-center">
        <div className="absolute inset-0 bg-gradient-to-t from-white/5 to-transparent rounded-xl" />
        <Shimmer className="absolute inset-4 h-40" />
        <div className="relative z-10 flex flex-col items-center gap-3">
          <Lock className="w-5 h-5 text-white/30" />
          <span className="text-xs text-white/50 uppercase tracking-wider">Sign in to view price history</span>
        </div>
      </div>
    )
  }

  if (data.length === 0) {
    return (
      <div className="h-48 flex items-center justify-center text-white/30">
        No price history available
      </div>
    )
  }

  const range = chartStats.high - chartStats.low || 1
  const padding = range * 0.1

  // Create smooth path
  const points = data.map((point, i) => {
    const x = (i / (data.length - 1)) * 100
    const y = 100 - ((point.price - chartStats.low + padding) / (range + padding * 2)) * 100
    return { x, y, ...point }
  })

  // Create SVG path for smooth curve
  const linePath = points.reduce((path, point, i) => {
    if (i === 0) return `M ${point.x} ${point.y}`
    
    // Use bezier curves for smoothness
    const prev = points[i - 1]
    const cpx = (prev.x + point.x) / 2
    return `${path} C ${cpx} ${prev.y}, ${cpx} ${point.y}, ${point.x} ${point.y}`
  }, '')

  // Area path
  const areaPath = `${linePath} L 100 100 L 0 100 Z`

  const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
    if (!containerRef.current) return
    const rect = containerRef.current.getBoundingClientRect()
    const x = e.clientX - rect.left
    const percentage = x / rect.width
    const index = Math.round(percentage * (data.length - 1))
    if (index >= 0 && index < data.length) {
      setHoveredIndex(index)
      setTooltipPos({ x: e.clientX - rect.left, y: points[index].y * rect.height / 100 })
    }
  }

  return (
    <div ref={containerRef} className="relative h-48">
      <svg
        className="w-full h-full"
        viewBox="0 0 100 100"
        preserveAspectRatio="none"
        onMouseMove={handleMouseMove}
        onMouseLeave={() => setHoveredIndex(null)}
      >
        <defs>
          <linearGradient id="chartGradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stopColor="rgb(0, 212, 170)" stopOpacity="0.15" />
            <stop offset="100%" stopColor="rgb(0, 212, 170)" stopOpacity="0" />
          </linearGradient>
          <filter id="glow">
            <feGaussianBlur stdDeviation="1" result="coloredBlur"/>
            <feMerge>
              <feMergeNode in="coloredBlur"/>
              <feMergeNode in="SourceGraphic"/>
            </feMerge>
          </filter>
        </defs>

        {/* Grid lines */}
        {[20, 40, 60, 80].map(y => (
          <line 
            key={y} 
            x1="0" y1={y} x2="100" y2={y} 
            stroke="currentColor" 
            strokeOpacity="0.05" 
            strokeWidth="0.2"
            vectorEffect="non-scaling-stroke"
            className="text-white/20"
          />
        ))}

        {/* Area fill */}
        <path
          d={areaPath}
          fill="url(#chartGradient)"
        />

        {/* Main line */}
        <path
          d={linePath}
          fill="none"
          stroke="rgb(0, 212, 170)"
          strokeWidth="0.4"
          strokeLinecap="round"
          strokeLinejoin="round"
          vectorEffect="non-scaling-stroke"
          filter="url(#glow)"
        />

        {/* Hover indicator */}
        {hoveredIndex !== null && (
          <g>
            <line
              x1={points[hoveredIndex].x}
              y1="0"
              x2={points[hoveredIndex].x}
              y2="100"
              stroke="rgb(0, 212, 170)"
              strokeWidth="1"
              strokeDasharray="4 4"
              vectorEffect="non-scaling-stroke"
              opacity="0.3"
            />
          </g>
        )}
      </svg>

      {/* Hover dot */}
      {hoveredIndex !== null && containerRef.current && (
        <div
          className="absolute w-3 h-3 bg-accent rounded-full border-2 border-black shadow-lg pointer-events-none transform -translate-x-1/2 -translate-y-1/2 transition-all duration-75"
          style={{ 
            left: `${(points[hoveredIndex].x / 100) * containerRef.current.offsetWidth}px`, 
            top: `${(points[hoveredIndex].y / 100) * containerRef.current.offsetHeight}px` 
          }}
        />
      )}

      {/* Tooltip */}
      {hoveredIndex !== null && (
        <div
          className="absolute z-20 px-3 py-2 bg-black/90 border border-white/10 rounded-lg shadow-xl pointer-events-none transform -translate-x-1/2 backdrop-blur-md"
          style={{ left: tooltipPos.x, top: Math.max(tooltipPos.y - 60, 10) }}
        >
          <p className="text-sm font-medium text-white tabular-nums">
            ${data[hoveredIndex].price.toFixed(2)}
          </p>
          <p className="text-xs text-white/50">
            {new Date(data[hoveredIndex].date).toLocaleDateString('en-US', { 
              month: 'short', 
              day: 'numeric',
              year: 'numeric'
            })}
          </p>
        </div>
      )}
    </div>
  )
}

// Domain Check Result Card
function DomainResultCard({ 
  result, 
  tld,
  cheapestPrice,
  cheapestRegistrar,
  onClose 
}: { 
  result: DomainCheckResult
  tld: string
  cheapestPrice: number
  cheapestRegistrar: string
  onClose: () => void
}) {
  const registrarUrl = REGISTRAR_URLS[cheapestRegistrar] || '#'

  return (
    <div className={clsx(
      "mt-6 p-6 rounded-2xl border transition-all duration-500 animate-fade-in backdrop-blur-md",
      result.is_available 
        ? "bg-gradient-to-br from-accent/10 via-accent/5 to-transparent border-accent/30" 
        : "bg-gradient-to-br from-orange-500/10 via-orange-500/5 to-transparent border-orange-500/30"
    )}>
      <div className="flex items-start justify-between gap-4">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-3">
            <div className={clsx(
              "w-10 h-10 rounded-xl flex items-center justify-center border",
              result.is_available ? "bg-accent/20 border-accent/20" : "bg-orange-500/20 border-orange-500/20"
            )}>
              {result.is_available ? (
                <Check className="w-5 h-5 text-accent" />
              ) : (
                <X className="w-5 h-5 text-orange-400" />
              )}
            </div>
            <div>
              <h3 className="font-mono text-lg text-white">{result.domain}</h3>
              <p className={clsx(
                "text-sm font-medium",
                result.is_available ? "text-accent" : "text-orange-400"
              )}>
                {result.is_available ? 'Available for registration' : 'Already registered'}
              </p>
            </div>
          </div>

          {result.is_available ? (
            <div className="flex flex-wrap items-center gap-4 mt-4">
              <div className="flex items-center gap-2">
                <Zap className="w-4 h-4 text-accent" />
                <span className="text-sm text-white/80">
                  Register from <span className="font-medium text-accent">${cheapestPrice.toFixed(2)}</span>/yr
                </span>
              </div>
              <a
                href={`${registrarUrl}${result.domain}`}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-2 px-5 py-2.5 bg-accent text-[#020202] text-sm font-bold rounded-lg hover:bg-accent-hover transition-all uppercase tracking-wide"
              >
                Register at {cheapestRegistrar}
                <ExternalLink className="w-4 h-4" />
              </a>
            </div>
          ) : (
            <div className="flex flex-wrap items-center gap-4 mt-4 text-sm text-white/50">
              {result.registrar && (
                <div className="flex items-center gap-2">
                  <Shield className="w-4 h-4 text-white/30" />
                  <span>Registrar: {result.registrar}</span>
                </div>
              )}
              {result.expiration_date && (
                <div className="flex items-center gap-2">
                  <Clock className="w-4 h-4 text-white/30" />
                  <span>Expires: {new Date(result.expiration_date).toLocaleDateString()}</span>
                </div>
              )}
            </div>
          )}
        </div>

        <button
          onClick={onClose}
          className="p-2 text-white/30 hover:text-white hover:bg-white/10 rounded-lg transition-colors"
        >
          <X className="w-4 h-4" />
        </button>
      </div>
    </div>
  )
}

export default function TldDetailPage() {
  const params = useParams()
  const { isAuthenticated, checkAuth, isLoading: authLoading, subscription, fetchSubscription } = useStore()
  const tld = params.tld as string
  
  // Feature flags based on subscription
  const hasPriceHistory = (subscription?.history_days ?? 0) !== 0
  
  const [details, setDetails] = useState<TldDetails | null>(null)
  const [history, setHistory] = useState<TldHistory | null>(null)
  const [relatedTlds, setRelatedTlds] = useState<Array<{ tld: string; price: number }>>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [chartPeriod, setChartPeriod] = useState<ChartPeriod>('1Y')
  const [domainSearch, setDomainSearch] = useState('')
  const [checkingDomain, setCheckingDomain] = useState(false)
  const [domainResult, setDomainResult] = useState<DomainCheckResult | null>(null)

  useEffect(() => {
    checkAuth()
    fetchSubscription()
  }, [checkAuth, fetchSubscription])

  useEffect(() => {
    if (tld) {
      loadData()
      loadRelatedTlds()
    }
  }, [tld])

  const loadData = async () => {
    try {
      const [historyData, compareData, overviewData] = await Promise.all([
        api.getTldHistory(tld, 365),
        api.getTldCompare(tld),
        api.getTldOverview(1, 0, 'popularity', tld),
      ])
      
      if (historyData && compareData) {
        const sortedRegistrars = [...(compareData.registrars || [])].sort((a, b) => 
          a.registration_price - b.registration_price
        )
        
        // Get additional data from overview API
        const tldFromOverview = overviewData?.tlds?.[0]
        
        setDetails({
          tld: compareData.tld || tld,
          type: compareData.type || 'generic',
          description: compareData.description || `Domain extension .${tld}`,
          registry: compareData.registry || 'Various',
          introduced: compareData.introduced || 0,
          trend: historyData.trend || 'stable',
          trend_reason: historyData.trend_reason || 'Price tracking available',
          pricing: {
            avg: compareData.price_range?.avg || historyData.current_price || 0,
            min: compareData.price_range?.min || historyData.current_price || 0,
            max: compareData.price_range?.max || historyData.current_price || 0,
          },
          registrars: sortedRegistrars,
          cheapest_registrar: compareData.cheapest_registrar || sortedRegistrars[0]?.name || 'N/A',
          // New fields from overview
          min_renewal_price: tldFromOverview?.min_renewal_price || sortedRegistrars[0]?.renewal_price || 0,
          price_change_1y: tldFromOverview?.price_change_1y || 0,
          price_change_3y: tldFromOverview?.price_change_3y || 0,
          risk_level: tldFromOverview?.risk_level || 'low',
          risk_reason: tldFromOverview?.risk_reason || 'Stable',
        })
        setHistory(historyData)
      } else {
        setError('Failed to load TLD data')
      }
    } catch (err) {
      console.error('Error loading TLD data:', err)
      setError('Failed to load TLD data')
    } finally {
      setLoading(false)
    }
  }

  const loadRelatedTlds = async () => {
    const related = RELATED_TLDS[tld.toLowerCase()] || ['com', 'net', 'org', 'io']
    const relatedData: Array<{ tld: string; price: number }> = []
    
    for (const relatedTld of related.slice(0, 4)) {
      try {
        const data = await api.getTldHistory(relatedTld, 30)
        if (data) {
          relatedData.push({ tld: relatedTld, price: data.current_price })
        }
      } catch {
        // Skip failed
      }
    }
    setRelatedTlds(relatedData)
  }

  const filteredHistory = useMemo(() => {
    if (!history?.history) return []
    
    const now = new Date()
    let cutoffDays = 365
    
    switch (chartPeriod) {
      case '1M': cutoffDays = 30; break
      case '3M': cutoffDays = 90; break
      case '1Y': cutoffDays = 365; break
      case 'ALL': cutoffDays = 9999; break
    }
    
    const cutoff = new Date(now.getTime() - cutoffDays * 24 * 60 * 60 * 1000)
    return history.history.filter(h => new Date(h.date) >= cutoff)
  }, [history, chartPeriod])

  const chartStats = useMemo(() => {
    if (filteredHistory.length === 0) return { high: 0, low: 0, avg: 0 }
    const prices = filteredHistory.map(h => h.price)
    return {
      high: Math.max(...prices),
      low: Math.min(...prices),
      avg: prices.reduce((a, b) => a + b, 0) / prices.length,
    }
  }, [filteredHistory])

  const handleDomainCheck = async () => {
    if (!domainSearch.trim()) return
    
    setCheckingDomain(true)
    setDomainResult(null)
    
    try {
      const domain = domainSearch.includes('.') ? domainSearch : `${domainSearch}.${tld}`
      const result = await api.checkDomain(domain, false)
      setDomainResult({
        domain,
        is_available: result.is_available,
        status: result.status,
        registrar: result.registrar,
        creation_date: result.creation_date,
        expiration_date: result.expiration_date,
      })
    } catch (err) {
      console.error('Domain check failed:', err)
    } finally {
      setCheckingDomain(false)
    }
  }

  const getRegistrarUrl = (registrarName: string, domain?: string) => {
    const baseUrl = REGISTRAR_URLS[registrarName]
    if (!baseUrl) return '#'
    if (domain) return `${baseUrl}${domain}`
    return baseUrl
  }

  const savings = useMemo(() => {
    if (!details || details.registrars.length < 2) return null
    const cheapest = details.registrars[0].registration_price
    const mostExpensive = details.registrars[details.registrars.length - 1].registration_price
    return {
      amount: mostExpensive - cheapest,
      cheapestName: details.registrars[0].name,
      expensiveName: details.registrars[details.registrars.length - 1].name,
    }
  }, [details])

  // Renewal trap info
  const renewalInfo = useMemo(() => {
    if (!details?.registrars?.length) return null
    const cheapest = details.registrars[0]
    const ratio = cheapest.renewal_price / cheapest.registration_price
    return {
      registration: cheapest.registration_price,
      renewal: cheapest.renewal_price,
      ratio,
      isTrap: ratio > 2,
    }
  }, [details])

  // Risk badge component
  const getRiskBadge = () => {
    if (!details) return null
    const level = details.risk_level
    const reason = details.risk_reason
    return (
      <span className={clsx(
        "inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium",
        level === 'high' && "bg-red-500/10 text-red-400",
        level === 'medium' && "bg-amber-500/10 text-amber-400",
        level === 'low' && "bg-accent/10 text-accent"
      )}>
        <span className={clsx(
          "w-2.5 h-2.5 rounded-full",
          level === 'high' && "bg-red-400",
          level === 'medium' && "bg-amber-400",
          level === 'low' && "bg-accent"
        )} />
        {reason}
      </span>
    )
  }

  const getTrendIcon = (trend: string) => {
    switch (trend) {
      case 'up': return <TrendingUp className="w-4 h-4" />
      case 'down': return <TrendingDown className="w-4 h-4" />
      default: return <Minus className="w-4 h-4" />
    }
  }

  if (loading || authLoading) {
    return (
      <div className="min-h-screen bg-[#020202]">
        <Header />
        <main className="pt-28 pb-16 px-4 sm:px-6">
          <div className="max-w-5xl mx-auto space-y-8">
            <Shimmer className="h-8 w-32" />
            <Shimmer className="h-20 w-48" />
            <div className="grid sm:grid-cols-4 gap-4">
              {[1, 2, 3, 4].map(i => <Shimmer key={i} className="h-24" />)}
            </div>
            <Shimmer className="h-64" />
          </div>
        </main>
      </div>
    )
  }

  if (error || !details) {
    return (
      <div className="min-h-screen bg-[#020202] flex flex-col">
        <Header />
        <main className="flex-1 flex items-center justify-center px-4">
          <div className="text-center">
            <div className="w-16 h-16 bg-white/5 rounded-full flex items-center justify-center mx-auto mb-6">
              <X className="w-8 h-8 text-white/30" />
            </div>
            <h1 className="text-3xl font-bold text-white mb-2">TLD Not Found</h1>
            <p className="text-white/50 mb-8">{error || `The TLD .${tld} could not be found.`}</p>
            <Link
              href="/discover"
              className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-[#020202] rounded-xl font-bold hover:bg-accent-hover transition-all uppercase tracking-wide text-sm"
            >
              <ArrowLeft className="w-4 h-4" />
              Back to Discover
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-[#020202] text-white relative flex flex-col overflow-x-hidden selection:bg-accent/30 selection:text-white">
      {/* Background Effects */}
      <div className="fixed inset-0 pointer-events-none z-0">
        <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.04] mix-blend-overlay" />
        <div 
          className="absolute inset-0 opacity-[0.03]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,0.3) 0.5px, transparent 0.5px), linear-gradient(90deg, rgba(255,255,255,0.3) 0.5px, transparent 0.5px)`,
            backgroundSize: '160px 160px',
          }}
        />
        <div className="absolute top-[-30%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[180px]" />
      </div>

      <Header />

      <main className="relative z-10 pt-24 sm:pt-28 pb-20 px-4 sm:px-6 flex-1">
        <div className="max-w-5xl mx-auto">
          
          {/* Breadcrumb */}
          <nav className="flex items-center gap-2 text-xs uppercase tracking-wider mb-8 font-medium">
            <Link href="/discover" className="text-white/40 hover:text-white transition-colors">
              Discover
            </Link>
            <ChevronRight className="w-3.5 h-3.5 text-white/30" />
            <span className="text-white">.{details.tld}</span>
          </nav>

          {/* Hero */}
          <div className="grid lg:grid-cols-[1fr,320px] gap-8 mb-12">
            {/* Left: TLD Info */}
            <div>
              <div className="flex items-start gap-4 mb-4">
                <h1 className="font-mono text-[4rem] sm:text-[5rem] lg:text-[6rem] leading-[0.85] tracking-tight text-white">
                  .{details.tld}
                </h1>
                <div className={clsx(
                  "mt-3 flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium uppercase tracking-wider",
                  details.trend === 'up' ? "bg-orange-500/10 text-orange-400 border border-orange-500/20" :
                  details.trend === 'down' ? "bg-accent/10 text-accent border border-accent/20" :
                  "bg-white/5 text-white/50 border border-white/10"
                )}>
                  {getTrendIcon(details.trend)}
                  <span>{details.trend === 'up' ? 'Rising' : details.trend === 'down' ? 'Falling' : 'Stable'}</span>
                </div>
              </div>
              
              <p className="text-lg text-white/60 mb-2">{details.description}</p>
              <p className="text-sm text-white/40">{details.trend_reason}</p>

              {/* Quick Stats - All data from table */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-8">
                <div 
                  className="p-4 bg-white/[0.02] border border-white/[0.08] rounded-xl cursor-help backdrop-blur-sm"
                  title="Lowest first-year registration price across all tracked registrars"
                >
                  <p className="text-[10px] text-white/40 uppercase tracking-wider mb-1">Buy (1y)</p>
                  {isAuthenticated ? (
                    <p className="text-xl font-medium text-white tabular-nums">${details.pricing.min.toFixed(2)}</p>
                  ) : (
                    <Shimmer className="h-6 w-16 mt-1" />
                  )}
                </div>
                <div 
                  className="p-4 bg-white/[0.02] border border-white/[0.08] rounded-xl cursor-help backdrop-blur-sm"
                  title={renewalInfo?.isTrap 
                    ? `Warning: Renewal is ${renewalInfo.ratio.toFixed(1)}x the registration price` 
                    : 'Annual renewal price after first year'}
                >
                  <p className="text-[10px] text-white/40 uppercase tracking-wider mb-1">Renew (1y)</p>
                  {isAuthenticated ? (
                    <div className="flex items-center gap-1">
                      <p className="text-xl font-medium text-white tabular-nums">
                        ${details.min_renewal_price.toFixed(2)}
                      </p>
                      {renewalInfo?.isTrap && (
                        <span title={`Renewal trap: ${renewalInfo.ratio.toFixed(1)}x registration`}>
                          <AlertTriangle className="w-4 h-4 text-amber-400" />
                        </span>
                      )}
                    </div>
                  ) : (
                    <Shimmer className="h-6 w-20 mt-1" />
                  )}
                </div>
                <div 
                  className="p-4 bg-white/[0.02] border border-white/[0.08] rounded-xl cursor-help backdrop-blur-sm"
                  title="Price change over the last 12 months"
                >
                  <p className="text-[10px] text-white/40 uppercase tracking-wider mb-1">1y Change</p>
                  {isAuthenticated ? (
                    <p className={clsx(
                      "text-xl font-medium tabular-nums",
                      details.price_change_1y > 0 ? "text-orange-400" :
                      details.price_change_1y < 0 ? "text-accent" :
                      "text-white"
                    )}>
                      {details.price_change_1y > 0 ? '+' : ''}{details.price_change_1y.toFixed(0)}%
                    </p>
                  ) : (
                    <Shimmer className="h-6 w-14 mt-1" />
                  )}
                </div>
                <div 
                  className="p-4 bg-white/[0.02] border border-white/[0.08] rounded-xl cursor-help backdrop-blur-sm"
                  title="Price change over the last 3 years"
                >
                  <p className="text-[10px] text-white/40 uppercase tracking-wider mb-1">3y Change</p>
                  {isAuthenticated ? (
                    <p className={clsx(
                      "text-xl font-medium tabular-nums",
                      details.price_change_3y > 0 ? "text-orange-400" :
                      details.price_change_3y < 0 ? "text-accent" :
                      "text-white"
                    )}>
                      {details.price_change_3y > 0 ? '+' : ''}{details.price_change_3y.toFixed(0)}%
                    </p>
                  ) : (
                    <Shimmer className="h-6 w-14 mt-1" />
                  )}
                </div>
              </div>

              {/* Risk Assessment */}
              {isAuthenticated && (
                <div className="flex items-center gap-4 mt-4 p-4 bg-white/[0.02] border border-white/[0.08] rounded-xl backdrop-blur-sm">
                  <Shield className="w-5 h-5 text-white/30" />
                  <div className="flex-1">
                    <p className="text-sm font-medium text-white">Risk Assessment</p>
                  </div>
                  {getRiskBadge()}
                </div>
              )}
            </div>

            {/* Right: Price Card */}
            <div className="lg:sticky lg:top-28 h-fit">
              <div className="p-6 bg-[#0a0a0a]/80 backdrop-blur-md border border-white/[0.08] rounded-2xl shadow-2xl">
                {isAuthenticated ? (
                  <>
                    <div className="flex items-baseline gap-1 mb-1">
                      <span className="text-[2.75rem] font-bold text-white tracking-tight tabular-nums">
                        ${details.pricing.min.toFixed(2)}
                      </span>
                      <span className="text-lg text-white/40">/yr</span>
                    </div>
                    <p className="text-xs text-white/40 mb-6 uppercase tracking-wide">
                      Cheapest at {details.cheapest_registrar}
                    </p>
                    
                    <div className="space-y-3">
                      <a
                        href={getRegistrarUrl(details.cheapest_registrar, `example.${tld}`)}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center justify-center gap-2 w-full py-3.5 bg-accent text-[#020202] font-bold rounded-lg hover:bg-accent-hover transition-all uppercase tracking-wide text-sm"
                      >
                        Register Domain
                        <ExternalLink className="w-4 h-4" />
                      </a>
                    </div>
                    
                    {savings && savings.amount > 0.5 && (
                      <div className="mt-5 pt-5 border-t border-white/[0.08]">
                        <div className="flex items-start gap-2.5">
                          <Zap className="w-4 h-4 text-accent mt-0.5 shrink-0" />
                          <p className="text-sm text-white/60 leading-relaxed">
                            Save <span className="text-accent font-medium">${savings.amount.toFixed(2)}</span>/yr vs {savings.expensiveName}
                          </p>
                        </div>
                      </div>
                    )}
                  </>
                ) : (
                  <>
                    <Shimmer className="h-12 w-32 mb-2" />
                    <Shimmer className="h-4 w-28 mb-6" />
                    <Link
                      href="/register"
                      className="flex items-center justify-center gap-2 w-full py-3.5 bg-accent text-[#020202] font-bold rounded-lg hover:bg-accent-hover transition-all uppercase tracking-wide text-sm"
                    >
                      <Lock className="w-4 h-4" />
                      Sign in to View Prices
                    </Link>
                  </>
                )}
              </div>
            </div>
          </div>

          {/* Renewal Trap Warning */}
          {isAuthenticated && renewalInfo?.isTrap && (
            <div className="mb-8 p-4 bg-amber-500/10 border border-amber-500/20 rounded-xl flex items-start gap-3">
              <AlertTriangle className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" />
              <div>
                <p className="text-sm font-medium text-amber-400">Renewal Trap Detected</p>
                <p className="text-sm text-white/60 mt-1">
                  The renewal price (${renewalInfo.renewal.toFixed(2)}) is {renewalInfo.ratio.toFixed(1)}x higher than the registration price (${renewalInfo.registration.toFixed(2)}). 
                  Consider the total cost of ownership before registering.
                </p>
              </div>
            </div>
          )}

          {/* Price Chart */}
          <section className="mb-12">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <h2 className="text-lg font-medium text-white">Price History</h2>
                {isAuthenticated && !hasPriceHistory && (
                  <span className="text-[10px] uppercase font-bold tracking-wider px-2 py-0.5 rounded bg-accent/10 text-accent border border-accent/20">Pro</span>
                )}
              </div>
              {hasPriceHistory && (
                <div className="flex items-center gap-1 p-1 bg-white/[0.03] border border-white/[0.08] rounded-lg">
                  {(['1M', '3M', '1Y', 'ALL'] as ChartPeriod[]).map(period => (
                    <button
                      key={period}
                      onClick={() => setChartPeriod(period)}
                      className={clsx(
                        "px-3 py-1.5 text-xs font-medium rounded transition-all",
                        chartPeriod === period
                          ? "bg-white text-black"
                          : "text-white/40 hover:text-white"
                      )}
                    >
                      {period}
                    </button>
                  ))}
                </div>
              )}
            </div>
            
            <div className="p-6 bg-white/[0.02] border border-white/[0.08] rounded-2xl backdrop-blur-sm">
              {!isAuthenticated ? (
                <div className="relative h-48 flex items-center justify-center">
                  <div className="absolute inset-0 bg-gradient-to-t from-white/5 to-transparent rounded-xl" />
                  <div className="relative z-10 flex flex-col items-center gap-3">
                    <Lock className="w-5 h-5 text-white/30" />
                    <span className="text-xs text-white/50 uppercase tracking-wider">Sign in to view price history</span>
                    <Link href={`/login?redirect=/discover/${tld}`} className="text-xs font-bold text-accent hover:text-accent-hover transition-colors uppercase tracking-wider">
                      Sign in →
                    </Link>
                  </div>
                </div>
              ) : !hasPriceHistory ? (
                <div className="relative h-48 flex items-center justify-center">
                  <div className="absolute inset-0 bg-gradient-to-t from-white/5 to-transparent rounded-xl" />
                  <div className="relative z-10 flex flex-col items-center gap-3">
                    <Zap className="w-5 h-5 text-accent" />
                    <span className="text-xs text-white/50 uppercase tracking-wider">Price history requires Trader or Tycoon plan</span>
                    <Link href="/pricing" className="flex items-center gap-2 text-xs font-bold px-4 py-2 bg-accent text-[#020202] rounded hover:bg-accent-hover transition-all uppercase tracking-wider">
                      <Zap className="w-3 h-3" />
                      Upgrade to Unlock
                    </Link>
                  </div>
                </div>
              ) : (
                <>
                  <PriceChart 
                    data={filteredHistory} 
                    isAuthenticated={true}
                    chartStats={chartStats}
                  />
                  
                  {filteredHistory.length > 0 && (
                    <div className="flex items-center justify-between mt-4 pt-4 border-t border-white/[0.08] text-xs">
                      <span className="text-white/40 font-mono">
                        {new Date(filteredHistory[0]?.date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                      </span>
                      <div className="flex items-center gap-6 font-mono">
                        <div className="flex items-center gap-2">
                          <span className="text-white/40 uppercase tracking-wider">High</span>
                          <span className="text-white font-medium">${chartStats.high.toFixed(2)}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-white/40 uppercase tracking-wider">Low</span>
                          <span className="text-accent font-medium">${chartStats.low.toFixed(2)}</span>
                        </div>
                      </div>
                      <span className="text-white/40 uppercase tracking-wider">Today</span>
                    </div>
                  )}
                </>
              )}
            </div>
          </section>

          {/* Domain Search */}
          <section className="mb-12">
            <h2 className="text-lg font-medium text-white mb-4">
              Check .{details.tld} Availability
            </h2>
            <div className="p-6 bg-white/[0.02] border border-white/[0.08] rounded-2xl backdrop-blur-sm">
              <div className="flex gap-3">
                <div className="flex-1 relative">
                  <input
                    type="text"
                    value={domainSearch}
                    onChange={(e) => setDomainSearch(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && handleDomainCheck()}
                    placeholder="Enter domain name"
                    className="w-full px-4 py-3.5 pr-20 bg-[#0a0a0a] border border-white/10 rounded-xl text-white placeholder:text-white/30 focus:outline-none focus:ring-1 focus:ring-accent/50 focus:border-accent/50 transition-all"
                  />
                  <span className="absolute right-4 top-1/2 -translate-y-1/2 text-white/30 font-mono text-sm">
                    .{tld}
                  </span>
                </div>
                <button
                  onClick={handleDomainCheck}
                  disabled={checkingDomain || !domainSearch.trim()}
                  className="px-6 py-3.5 bg-white text-[#020202] font-bold rounded-xl hover:bg-white/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center gap-2 uppercase tracking-wide text-sm"
                >
                  {checkingDomain ? (
                    <RefreshCw className="w-4 h-4 animate-spin" />
                  ) : (
                    <Search className="w-4 h-4" />
                  )}
                  Check
                </button>
              </div>
              
              {domainResult && (
                <DomainResultCard
                  result={domainResult}
                  tld={tld}
                  cheapestPrice={details.pricing.min}
                  cheapestRegistrar={details.cheapest_registrar}
                  onClose={() => setDomainResult(null)}
                />
              )}
            </div>
          </section>

          {/* Registrar Comparison */}
          <section className="mb-12">
            <h2 className="text-lg font-medium text-white mb-4">Compare Registrars</h2>
            
            {isAuthenticated ? (
              <div className="bg-white/[0.02] border border-white/[0.08] rounded-2xl overflow-hidden backdrop-blur-sm">
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-white/[0.08]">
                        <th className="text-left text-[10px] text-white/40 font-bold uppercase tracking-widest px-6 py-4">
                          Registrar
                        </th>
                        <th className="text-right text-[10px] text-white/40 font-bold uppercase tracking-widest px-6 py-4 cursor-help" title="First year registration price">
                          Register
                        </th>
                        <th className="text-right text-[10px] text-white/40 font-bold uppercase tracking-widest px-6 py-4 hidden sm:table-cell cursor-help" title="Annual renewal price">
                          Renew
                        </th>
                        <th className="text-right text-[10px] text-white/40 font-bold uppercase tracking-widest px-6 py-4 hidden sm:table-cell cursor-help" title="Transfer from another registrar">
                          Transfer
                        </th>
                        <th className="px-6 py-4 w-24"></th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-white/[0.04]">
                      {details.registrars.map((registrar, i) => {
                        const hasRenewalTrap = registrar.renewal_price / registrar.registration_price > 1.5
                        const isBestValue = i === 0 && !hasRenewalTrap
                        
                        return (
                          <tr key={registrar.name} className={clsx(
                            "transition-colors group hover:bg-white/[0.02]",
                            isBestValue && "bg-accent/[0.03]"
                          )}>
                            <td className="px-6 py-4">
                              <div className="flex items-center gap-2.5">
                                <span className="text-sm font-medium text-white">{registrar.name}</span>
                                {isBestValue && (
                                  <span 
                                    className="text-[10px] text-accent bg-accent/10 px-2 py-0.5 rounded font-bold uppercase tracking-wider cursor-help border border-accent/20"
                                    title="Best overall value: lowest registration price without renewal trap"
                                  >
                                    Best Value
                                  </span>
                                )}
                                {i === 0 && hasRenewalTrap && (
                                  <span 
                                    className="text-[10px] text-amber-400 bg-amber-500/10 px-2 py-0.5 rounded font-bold uppercase tracking-wider cursor-help border border-amber-500/20"
                                    title="Cheapest registration but high renewal costs"
                                  >
                                    Promo
                                  </span>
                                )}
                              </div>
                            </td>
                            <td className="px-6 py-4 text-right">
                              <span 
                                className={clsx(
                                  "text-sm font-medium tabular-nums cursor-help font-mono",
                                  isBestValue ? "text-accent" : "text-white/90"
                                )}
                                title={`First year: $${registrar.registration_price.toFixed(2)}`}
                              >
                                ${registrar.registration_price.toFixed(2)}
                              </span>
                            </td>
                            <td className="px-6 py-4 text-right hidden sm:table-cell">
                              <span 
                                className={clsx(
                                  "text-sm tabular-nums cursor-help font-mono",
                                  hasRenewalTrap ? "text-amber-400" : "text-white/50"
                                )}
                                title={hasRenewalTrap 
                                  ? `Renewal is ${(registrar.renewal_price / registrar.registration_price).toFixed(1)}x the registration price` 
                                  : `Annual renewal: $${registrar.renewal_price.toFixed(2)}`}
                              >
                                ${registrar.renewal_price.toFixed(2)}
                              </span>
                              {hasRenewalTrap && (
                                <span title={`Renewal trap: ${(registrar.renewal_price / registrar.registration_price).toFixed(1)}x registration price`}>
                                  <AlertTriangle className="inline-block ml-1.5 w-3.5 h-3.5 text-amber-400 cursor-help" />
                                </span>
                              )}
                            </td>
                            <td className="px-6 py-4 text-right hidden sm:table-cell">
                              <span 
                                className="text-sm text-white/50 tabular-nums cursor-help font-mono"
                                title={`Transfer from another registrar: $${registrar.transfer_price.toFixed(2)}`}
                              >
                                ${registrar.transfer_price.toFixed(2)}
                              </span>
                            </td>
                            <td className="px-6 py-4">
                              <a
                                href={getRegistrarUrl(registrar.name, `example.${tld}`)}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex items-center gap-1.5 text-xs font-bold text-white/40 hover:text-accent transition-colors opacity-0 group-hover:opacity-100 uppercase tracking-wider"
                                title={`Register at ${registrar.name}`}
                              >
                                Visit
                                <ExternalLink className="w-3 h-3" />
                              </a>
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            ) : (
              <div className="relative p-8 bg-white/[0.02] border border-white/[0.08] rounded-2xl backdrop-blur-sm">
                <div className="space-y-3">
                  {[1, 2, 3, 4].map(i => (
                    <div key={i} className="flex items-center justify-between">
                      <Shimmer className="h-5 w-24" />
                      <Shimmer className="h-5 w-16" />
                      <Shimmer className="h-5 w-16 hidden sm:block" />
                      <Shimmer className="h-5 w-16 hidden sm:block" />
                    </div>
                  ))}
                </div>
                <div className="absolute inset-0 flex items-center justify-center bg-[#0a0a0a]/60 backdrop-blur-sm rounded-2xl">
                  <div className="text-center">
                    <Lock className="w-6 h-6 text-white/30 mx-auto mb-2" />
                    <p className="text-sm text-white/50 mb-4">Sign in to compare registrar prices</p>
                    <Link
                      href="/register"
                      className="inline-flex items-center gap-2 px-5 py-2.5 bg-accent text-[#020202] text-sm font-bold rounded-lg hover:bg-accent-hover transition-all uppercase tracking-wide"
                    >
                      Join the Hunt
                    </Link>
                  </div>
                </div>
              </div>
            )}
          </section>

          {/* TLD Info */}
          <section className="mb-12">
            <h2 className="text-lg font-medium text-white mb-4">About .{details.tld}</h2>
            <div className="grid sm:grid-cols-3 gap-4">
              <div className="p-5 bg-white/[0.02] border border-white/[0.08] rounded-xl backdrop-blur-sm">
                <Building className="w-5 h-5 text-white/30 mb-3" />
                <p className="text-[10px] text-white/40 uppercase tracking-wider mb-1">Registry</p>
                <p className="text-base font-medium text-white">{details.registry}</p>
              </div>
              <div className="p-5 bg-white/[0.02] border border-white/[0.08] rounded-xl backdrop-blur-sm">
                <Calendar className="w-5 h-5 text-white/30 mb-3" />
                <p className="text-[10px] text-white/40 uppercase tracking-wider mb-1">Introduced</p>
                <p className="text-base font-medium text-white">{details.introduced || 'Unknown'}</p>
              </div>
              <div className="p-5 bg-white/[0.02] border border-white/[0.08] rounded-xl backdrop-blur-sm">
                <Globe className="w-5 h-5 text-white/30 mb-3" />
                <p className="text-[10px] text-white/40 uppercase tracking-wider mb-1">Type</p>
                <p className="text-base font-medium text-white capitalize">{details.type}</p>
              </div>
            </div>
          </section>

          {/* Related TLDs */}
          {relatedTlds.length > 0 && (
            <section className="mb-12">
              <h2 className="text-lg font-medium text-white mb-4">Similar Extensions</h2>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                {relatedTlds.map(related => (
                  <Link
                    key={related.tld}
                    href={`/discover/${related.tld}`}
                    className="group p-5 bg-white/[0.02] border border-white/[0.08] rounded-xl hover:border-accent/30 hover:bg-white/[0.04] transition-all backdrop-blur-sm"
                  >
                    <p className="font-mono text-lg text-white group-hover:text-accent transition-colors mb-1">
                      .{related.tld}
                    </p>
                    {isAuthenticated ? (
                      <p className="text-xs text-white/50 tabular-nums">
                        from ${related.price.toFixed(2)}/yr
                      </p>
                    ) : (
                      <Shimmer className="h-4 w-20" />
                    )}
                  </Link>
                ))}
              </div>
            </section>
          )}

          {/* CTA */}
          <section className="p-8 sm:p-10 bg-gradient-to-br from-accent/10 via-accent/5 to-transparent border border-accent/20 rounded-2xl text-center backdrop-blur-sm">
            <h3 className="text-xl font-bold text-white mb-2">
              Track .{details.tld} Domains
            </h3>
            <p className="text-white/60 mb-8 max-w-lg mx-auto">
              Monitor specific domains and get instant notifications when they become available.
            </p>
            <Link
              href={isAuthenticated ? '/terminal' : '/register'}
              className="inline-flex items-center gap-2 px-8 py-4 bg-white text-[#020202] font-bold rounded-xl hover:bg-white/90 transition-all uppercase tracking-wide text-sm"
            >
              {isAuthenticated ? 'Go to Command Center' : 'Start Monitoring Free'}
              <ChevronRight className="w-4 h-4" />
            </Link>
          </section>

        </div>
      </main>
      
      <Footer />
    </div>
  )
}

