'use client'

import { useEffect, useState, useMemo, useRef } from 'react'
import { useParams } from 'next/navigation'
import { TerminalLayout } from '@/components/TerminalLayout'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import {
  ArrowLeft,
  TrendingUp,
  TrendingDown,
  Minus,
  Calendar,
  Globe,
  Building,
  ExternalLink,
  Search,
  ChevronRight,
  Check,
  X,
  RefreshCw,
  AlertTriangle,
  DollarSign,
  BarChart3,
  Shield,
  Loader2,
  Info,
  ChevronDown
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

// ============================================================================
// SHARED COMPONENTS
// ============================================================================

function Tooltip({ children, content }: { children: React.ReactNode; content: string }) {
  return (
    <div className="relative flex items-center group/tooltip w-fit">
      {children}
      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-zinc-900 border border-zinc-800 rounded text-[10px] text-zinc-300 whitespace-nowrap opacity-0 group-hover/tooltip:opacity-100 transition-opacity pointer-events-none z-50 shadow-xl">
        {content}
        <div className="absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-zinc-800" />
      </div>
    </div>
  )
}

function StatCard({ 
  label, 
  value, 
  subValue, 
  icon: Icon, 
  trend 
}: { 
  label: string
  value: string | number
  subValue?: string
  icon: any
  trend?: 'up' | 'down' | 'neutral' | 'active'
}) {
  return (
    <div className="bg-zinc-900/40 border border-white/5 rounded-xl p-4 flex items-start justify-between hover:bg-white/[0.02] transition-colors relative overflow-hidden group">
      <div className="absolute inset-0 bg-gradient-to-br from-white/[0.03] to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
      <div className="relative z-10">
        <p className="text-[11px] font-semibold text-zinc-500 uppercase tracking-wider mb-1">{label}</p>
        <div className="flex items-baseline gap-2">
          <span className="text-2xl font-bold text-white tracking-tight">{value}</span>
          {subValue && <span className="text-xs text-zinc-500 font-medium">{subValue}</span>}
        </div>
      </div>
      <div className={clsx(
        "relative z-10 p-2 rounded-lg bg-zinc-800/50 transition-colors",
        trend === 'up' && "text-emerald-400 bg-emerald-500/10",
        trend === 'down' && "text-rose-400 bg-rose-500/10",
        trend === 'active' && "text-blue-400 bg-blue-500/10 animate-pulse",
        trend === 'neutral' && "text-zinc-400"
      )}>
        <Icon className="w-4 h-4" />
      </div>
    </div>
  )
}

// ============================================================================
// TYPES & DATA
// ============================================================================

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
  min_renewal_price: number
  price_change_1y: number
  price_change_3y: number
  risk_level: 'low' | 'medium' | 'high'
  risk_reason: string
}

interface TldHistory {
  tld: 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
  }>
}

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

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=',
}

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

// ============================================================================
// SUB-COMPONENTS
// ============================================================================

function PriceChart({ 
  data, 
  chartStats,
}: { 
  data: Array<{ date: string; price: number }>
  chartStats: { high: number; low: number; avg: number }
}) {
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  if (data.length === 0) {
    return (
      <div className="h-48 flex items-center justify-center text-zinc-600 text-xs font-mono uppercase">
        No price history available
      </div>
    )
  }

  const minPrice = Math.min(...data.map(d => d.price))
  const maxPrice = Math.max(...data.map(d => d.price))
  const priceRange = maxPrice - minPrice || 1

  const points = data.map((d, i) => ({
    x: (i / (data.length - 1)) * 100,
    y: 100 - ((d.price - minPrice) / priceRange) * 80 - 10,
    ...d,
  }))

  const linePath = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x},${p.y}`).join(' ')
  const areaPath = linePath + ` L${points[points.length - 1].x},100 L${points[0].x},100 Z`

  const isRising = data[data.length - 1].price >= data[0].price
  const strokeColor = isRising ? '#10b981' : '#f43f5e' // emerald-500 : rose-500

  return (
    <div 
      ref={containerRef}
      className="relative h-48 w-full"
      onMouseLeave={() => setHoveredIndex(null)}
    >
      <svg 
        className="w-full h-full overflow-visible" 
        viewBox="0 0 100 100" 
        preserveAspectRatio="none"
        onMouseMove={(e) => {
          if (!containerRef.current) return
          const rect = containerRef.current.getBoundingClientRect()
          const x = ((e.clientX - rect.left) / rect.width) * 100
          const idx = Math.round((x / 100) * (points.length - 1))
          setHoveredIndex(Math.max(0, Math.min(idx, points.length - 1)))
        }}
      >
        <defs>
          <linearGradient id="chartGradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stopColor={strokeColor} stopOpacity="0.2" />
            <stop offset="100%" stopColor={strokeColor} stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d={areaPath} fill="url(#chartGradient)" />
        <path d={linePath} fill="none" stroke={strokeColor} strokeWidth="1.5" vectorEffect="non-scaling-stroke" />
        
        {hoveredIndex !== null && points[hoveredIndex] && (
          <g>
            <line 
              x1={points[hoveredIndex].x} 
              y1="0" 
              x2={points[hoveredIndex].x} 
              y2="100" 
              stroke="#52525b" 
              strokeWidth="1" 
              strokeDasharray="2"
              vectorEffect="non-scaling-stroke"
            />
            <circle 
              cx={points[hoveredIndex].x} 
              cy={points[hoveredIndex].y} 
              r="4" 
              fill="#09090b"
              stroke={strokeColor}
              strokeWidth="2"
              vectorEffect="non-scaling-stroke"
            />
          </g>
        )}
      </svg>
      
      {/* Tooltip */}
      {hoveredIndex !== null && points[hoveredIndex] && (
        <div 
          className="absolute -top-10 transform -translate-x-1/2 bg-zinc-900 border border-zinc-800 rounded px-3 py-1.5 shadow-xl z-20 pointer-events-none"
          style={{ left: `${points[hoveredIndex].x}%` }}
        >
          <div className="flex flex-col items-center">
             <span className="text-xs font-bold text-white font-mono">${points[hoveredIndex].price.toFixed(2)}</span>
             <span className="text-[10px] text-zinc-500 font-mono">{new Date(points[hoveredIndex].date).toLocaleDateString()}</span>
          </div>
          <div className="absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-zinc-900" />
        </div>
      )}
    </div>
  )
}

// ============================================================================
// MAIN PAGE
// ============================================================================

export default function CommandTldDetailPage() {
  const params = useParams()
  const { fetchSubscription } = useStore()
  const tld = params.tld as string
  
  const [details, setDetails] = useState<TldDetails | null>(null)
  const [history, setHistory] = useState<TldHistory | null>(null)
  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(() => {
    fetchSubscription()
    if (tld) {
      loadData()
    }
  }, [tld, fetchSubscription])

  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
        )
        
        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',
          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 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 getRenewalInfo = () => {
    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,
    }
  }

  const renewalInfo = getRenewalInfo()

  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-[10px] font-bold uppercase tracking-wider",
        level === 'high' && "bg-rose-500/10 text-rose-400 border border-rose-500/20",
        level === 'medium' && "bg-amber-500/10 text-amber-400 border border-amber-500/20",
        level === 'low' && "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"
      )}>
        <span className={clsx(
          "w-1.5 h-1.5 rounded-full",
          level === 'high' && "bg-rose-400 animate-pulse",
          level === 'medium' && "bg-amber-400",
          level === 'low' && "bg-emerald-400"
        )} />
        {reason}
      </span>
    )
  }

  if (loading) {
    return (
      <TerminalLayout hideHeaderSearch={true}>
        <div className="flex items-center justify-center min-h-[50vh]">
           <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
        </div>
      </TerminalLayout>
    )
  }

  if (error || !details) {
    return (
      <TerminalLayout hideHeaderSearch={true}>
        <div className="flex flex-col items-center justify-center min-h-[50vh] text-zinc-400">
           <X className="w-12 h-12 text-zinc-600 mb-4" />
           <h1 className="text-xl font-bold text-white mb-2">TLD Not Found</h1>
           <p className="mb-6">The extension .{tld} is not currently tracked.</p>
           <Link href="/terminal/intel" className="text-emerald-400 hover:text-emerald-300 flex items-center gap-2">
             <ArrowLeft className="w-4 h-4" /> Back to Intelligence
           </Link>
        </div>
      </TerminalLayout>
    )
  }

  return (
    <TerminalLayout hideHeaderSearch={true}>
      <div className="relative">
        
        {/* Ambient Background Glow */}
        <div className="pointer-events-none absolute inset-0 -z-10">
          <div className="absolute top-[-200px] right-[-100px] w-[800px] h-[600px] bg-emerald-500/5 rounded-full blur-[120px] mix-blend-screen" />
          <div className="absolute bottom-0 left-[-100px] w-[600px] h-[500px] bg-blue-500/5 rounded-full blur-[100px] mix-blend-screen" />
        </div>

        <div className="space-y-6 pb-20 md:pb-0 relative">
          
          {/* Header Section */}
          <div className="flex flex-col md:flex-row justify-between items-start md:items-end gap-6 border-b border-white/5 pb-8">
            <div className="space-y-4">
               {/* Breadcrumb */}
              <nav className="flex items-center gap-2 text-xs font-medium text-zinc-500 uppercase tracking-widest">
                <Link href="/terminal/intel" className="hover:text-emerald-400 transition-colors">
                  Intelligence
                </Link>
                <ChevronRight className="w-3 h-3" />
                <span className="text-white">.{details.tld}</span>
              </nav>

              <div className="flex items-center gap-4">
                <div className="h-12 w-1.5 bg-emerald-500 rounded-full shadow-[0_0_15px_rgba(16,185,129,0.5)]" />
                <div>
                   <h1 className="text-4xl font-bold tracking-tight text-white flex items-center gap-3">
                    .{details.tld}
                    {getRiskBadge()}
                   </h1>
                   <p className="text-zinc-400 text-sm mt-1 max-w-lg">
                    {details.description}
                   </p>
                </div>
              </div>
            </div>
            
            <div className="flex gap-2">
               <Link 
                  href="/terminal/intel"
                  className="px-4 py-2 rounded-lg bg-zinc-900 border border-white/10 hover:bg-white/5 text-sm font-medium text-zinc-300 transition-colors flex items-center gap-2"
                >
                  <ArrowLeft className="w-4 h-4" /> Back
               </Link>
            </div>
          </div>

          {/* Metric Grid */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <StatCard 
              label="Registration" 
              value={`$${details.pricing.min.toFixed(2)}`}
              subValue={`at ${details.cheapest_registrar}`}
              icon={DollarSign}
              trend="neutral"
            />
             <StatCard 
              label="Renewal" 
              value={details.min_renewal_price ? `$${details.min_renewal_price.toFixed(2)}` : '—'}
              subValue={renewalInfo?.isTrap ? `${renewalInfo.ratio.toFixed(1)}x Markup` : '/ year'}
              icon={RefreshCw}
              trend={renewalInfo?.isTrap ? 'down' : 'neutral'}
            />
            <StatCard 
              label="1y Trend" 
              value={`${details.price_change_1y > 0 ? '+' : ''}${details.price_change_1y.toFixed(0)}%`}
              subValue="Volatility"
              icon={details.price_change_1y > 0 ? TrendingUp : TrendingDown}
              trend={details.price_change_1y > 10 ? 'down' : details.price_change_1y < -10 ? 'up' : 'neutral'}
            />
             <StatCard 
              label="Tracked" 
              value={details.registrars.length}
              subValue="Registrars"
              icon={Building}
            />
          </div>

          {/* Quick Check Bar */}
          <div className="bg-zinc-900/40 border border-white/5 rounded-xl p-6 backdrop-blur-sm relative overflow-hidden group hover:border-white/10 transition-colors">
             <div className="absolute inset-0 bg-gradient-to-r from-emerald-500/5 to-transparent pointer-events-none opacity-50" />
             <div className="relative z-10 flex flex-col md:flex-row gap-6 items-center">
                <div className="flex-1">
                   <h2 className="text-lg font-bold text-white mb-1">Check Availability</h2>
                   <p className="text-sm text-zinc-400">Instantly check if your desired .{details.tld} domain is available across all registrars.</p>
                </div>
                
                <div className="flex-1 w-full max-w-xl flex gap-3">
                   <div className="relative flex-1 group/input">
                      <input
                        type="text"
                        value={domainSearch}
                        onChange={(e) => setDomainSearch(e.target.value)}
                        onKeyDown={(e) => e.key === 'Enter' && handleDomainCheck()}
                        placeholder={`example.${details.tld}`}
                        className="w-full h-12 bg-black/50 border border-white/10 rounded-lg pl-4 pr-4 text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 focus:ring-1 focus:ring-emerald-500/50 transition-all font-mono"
                      />
                   </div>
                   <button
                      onClick={handleDomainCheck}
                      disabled={checkingDomain || !domainSearch.trim()}
                      className="h-12 px-8 bg-emerald-500 text-white font-bold rounded-lg hover:bg-emerald-400 transition-all disabled:opacity-50 shadow-lg shadow-emerald-500/20"
                    >
                      {checkingDomain ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Check'}
                   </button>
                </div>
             </div>

             {/* Check Result */}
             {domainResult && (
                <div className="mt-6 pt-6 border-t border-white/5 animate-in fade-in slide-in-from-top-2">
                   <div className={clsx(
                      "p-4 rounded-lg border flex items-center justify-between",
                      domainResult.is_available 
                        ? "bg-emerald-500/10 border-emerald-500/20" 
                        : "bg-rose-500/10 border-rose-500/20"
                   )}>
                      <div className="flex items-center gap-3">
                         {domainResult.is_available ? (
                            <div className="p-2 rounded-full bg-emerald-500/20 text-emerald-400"><Check className="w-5 h-5" /></div>
                         ) : (
                            <div className="p-2 rounded-full bg-rose-500/20 text-rose-400"><X className="w-5 h-5" /></div>
                         )}
                         <div>
                            <div className="font-mono font-bold text-white text-lg">{domainResult.domain}</div>
                            <div className={clsx("text-xs font-medium uppercase tracking-wider", domainResult.is_available ? "text-emerald-400" : "text-rose-400")}>
                               {domainResult.is_available ? 'Available for registration' : 'Already Registered'}
                            </div>
                         </div>
                      </div>
                      
                      {domainResult.is_available && (
                         <a
                            href={getRegistrarUrl(details.cheapest_registrar, domainResult.domain)}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="px-4 py-2 bg-emerald-500 text-white text-sm font-bold rounded hover:bg-emerald-400 transition-colors flex items-center gap-2"
                         >
                            Buy at {details.cheapest_registrar} <ExternalLink className="w-4 h-4" />
                         </a>
                      )}
                   </div>
                </div>
             )}
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
             
             {/* Left Column: Chart & Info */}
             <div className="lg:col-span-2 space-y-8">
                
                {/* Price History Chart */}
                <div className="bg-zinc-900/40 border border-white/5 rounded-xl p-6 backdrop-blur-sm shadow-xl">
                   <div className="flex items-center justify-between mb-6">
                      <div>
                         <h3 className="text-lg font-bold text-white">Price History</h3>
                         <p className="text-xs text-zinc-500">Historical registration price trends</p>
                      </div>
                      <div className="flex bg-black/50 rounded-lg p-1 border border-white/5">
                        {(['1M', '3M', '1Y', 'ALL'] as ChartPeriod[]).map((period) => (
                          <button
                            key={period}
                            onClick={() => setChartPeriod(period)}
                            className={clsx(
                              "px-3 py-1 text-[10px] font-bold rounded transition-all",
                              chartPeriod === period
                                ? "bg-zinc-800 text-white shadow-sm"
                                : "text-zinc-500 hover:text-zinc-300"
                            )}
                          >
                            {period}
                          </button>
                        ))}
                      </div>
                   </div>
                   
                   <div className="h-64">
                      <PriceChart data={filteredHistory} chartStats={chartStats} />
                   </div>

                   <div className="grid grid-cols-3 gap-4 mt-6 pt-6 border-t border-white/5">
                      <div className="text-center">
                         <div className="text-[10px] text-zinc-500 uppercase tracking-widest mb-1">High</div>
                         <div className="text-lg font-mono font-bold text-white">${chartStats.high.toFixed(2)}</div>
                      </div>
                      <div className="text-center border-l border-r border-white/5">
                         <div className="text-[10px] text-zinc-500 uppercase tracking-widest mb-1">Average</div>
                         <div className="text-lg font-mono font-bold text-white">${chartStats.avg.toFixed(2)}</div>
                      </div>
                      <div className="text-center">
                         <div className="text-[10px] text-zinc-500 uppercase tracking-widest mb-1">Low</div>
                         <div className="text-lg font-mono font-bold text-emerald-400">${chartStats.low.toFixed(2)}</div>
                      </div>
                   </div>
                </div>

                {/* TLD Info Cards */}
                <div className="grid grid-cols-2 gap-4">
                   <div className="bg-zinc-900/40 border border-white/5 rounded-xl p-4 hover:border-white/10 transition-colors">
                      <div className="flex items-center gap-2 text-zinc-500 mb-2">
                         <Globe className="w-4 h-4" />
                         <span className="text-xs uppercase tracking-widest">Type</span>
                      </div>
                      <div className="text-lg font-medium text-white capitalize">{details.type}</div>
                   </div>
                   <div className="bg-zinc-900/40 border border-white/5 rounded-xl p-4 hover:border-white/10 transition-colors">
                      <div className="flex items-center gap-2 text-zinc-500 mb-2">
                         <Building className="w-4 h-4" />
                         <span className="text-xs uppercase tracking-widest">Registry</span>
                      </div>
                      <div className="text-lg font-medium text-white truncate" title={details.registry}>{details.registry}</div>
                   </div>
                </div>

             </div>

             {/* Right Column: Registrars Table */}
             <div className="bg-zinc-900/40 border border-white/5 rounded-xl overflow-hidden backdrop-blur-sm flex flex-col h-fit shadow-xl">
                <div className="p-4 border-b border-white/5 bg-white/[0.02]">
                   <h3 className="text-lg font-bold text-white">Registrar Prices</h3>
                   <p className="text-xs text-zinc-500">Live comparison sorted by price</p>
                </div>
                
                <div className="overflow-x-auto">
                   <table className="w-full text-left">
                      <thead>
                         <tr className="border-b border-white/5 text-[10px] font-bold text-zinc-500 uppercase tracking-wider">
                            <th className="px-4 py-3">Registrar</th>
                            <th className="px-4 py-3 text-right">Reg</th>
                            <th className="px-4 py-3 text-right">Renew</th>
                            <th className="px-4 py-3 text-right"></th>
                         </tr>
                      </thead>
                      <tbody className="divide-y divide-white/5">
                         {details.registrars.map((registrar, idx) => {
                            const hasRenewalTrap = registrar.renewal_price / registrar.registration_price > 1.5
                            const isBest = idx === 0 && !hasRenewalTrap

                            return (
                               <tr key={registrar.name} className="group hover:bg-white/[0.02] transition-colors">
                                  <td className="px-4 py-3">
                                     <div className="font-medium text-white text-sm">{registrar.name}</div>
                                     {isBest && <span className="text-[10px] text-emerald-400 font-bold uppercase">Best Value</span>}
                                     {idx === 0 && hasRenewalTrap && <span className="text-[10px] text-amber-400 font-bold uppercase">Renewal Trap</span>}
                                  </td>
                                  <td className="px-4 py-3 text-right">
                                     <div className={clsx("font-mono text-sm", isBest ? "text-emerald-400 font-bold" : "text-white")}>
                                        ${registrar.registration_price.toFixed(2)}
                                     </div>
                                  </td>
                                  <td className="px-4 py-3 text-right">
                                     <div className={clsx("font-mono text-sm", hasRenewalTrap ? "text-amber-400" : "text-zinc-500")}>
                                        ${registrar.renewal_price.toFixed(2)}
                                     </div>
                                  </td>
                                  <td className="px-4 py-3 text-right">
                                     <a 
                                        href={getRegistrarUrl(registrar.name)}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="p-1.5 rounded bg-white/5 text-zinc-400 hover:text-white hover:bg-white/10 transition-colors inline-block"
                                     >
                                        <ExternalLink className="w-3.5 h-3.5" />
                                     </a>
                                  </td>
                               </tr>
                            )
                         })}
                      </tbody>
                   </table>
                </div>
             </div>

          </div>

        </div>
      </div>
    </TerminalLayout>
  )
}
