'use client'

import { useEffect, useState, useMemo, useRef } from 'react'
import { useParams } from 'next/navigation'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { PageContainer, StatCard } from '@/components/PremiumTable'
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,
} 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
  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
}

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

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

// Premium Chart Component with real data
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-foreground-muted">
        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 ? '#f97316' : '#00d4aa'

  return (
    <div 
      ref={containerRef}
      className="relative h-48"
      onMouseLeave={() => setHoveredIndex(null)}
    >
      <svg 
        className="w-full h-full" 
        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.3" />
            <stop offset="100%" stopColor={strokeColor} stopOpacity="0.02" />
          </linearGradient>
        </defs>
        <path d={areaPath} fill="url(#chartGradient)" />
        <path d={linePath} fill="none" stroke={strokeColor} strokeWidth="2" />
        
        {hoveredIndex !== null && points[hoveredIndex] && (
          <circle 
            cx={points[hoveredIndex].x} 
            cy={points[hoveredIndex].y} 
            r="4" 
            fill={strokeColor}
            stroke="#0a0a0a"
            strokeWidth="2"
          />
        )}
      </svg>
      
      {/* Tooltip */}
      {hoveredIndex !== null && points[hoveredIndex] && (
        <div 
          className="absolute -top-2 transform -translate-x-1/2 bg-background border border-border rounded-lg px-3 py-2 shadow-lg z-10 pointer-events-none"
          style={{ left: `${points[hoveredIndex].x}%` }}
        >
          <p className="text-sm font-medium text-foreground">${points[hoveredIndex].price.toFixed(2)}</p>
          <p className="text-xs text-foreground-muted">{new Date(points[hoveredIndex].date).toLocaleDateString()}</p>
        </div>
      )}
      
      {/* Y-axis labels */}
      <div className="absolute left-0 top-0 bottom-0 flex flex-col justify-between text-xs text-foreground-subtle -ml-12 w-10 text-right">
        <span>${maxPrice.toFixed(2)}</span>
        <span>${((maxPrice + minPrice) / 2).toFixed(2)}</span>
        <span>${minPrice.toFixed(2)}</span>
      </div>
    </div>
  )
}

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), // Get the specific TLD data
      ])
      
      if (historyData && compareData) {
        const sortedRegistrars = [...(compareData.registrars || [])].sort((a, b) => 
          a.registration_price - b.registration_price
        )
        
        // Get additional data from overview API (1y, 3y change, risk)
        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 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
  }

  // Calculate renewal trap info
  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()

  // 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>
    )
  }

  if (loading) {
    return (
      <CommandCenterLayout title={`.${tld}`} subtitle="Loading...">
        <PageContainer>
          <div className="flex items-center justify-center py-20">
            <RefreshCw className="w-6 h-6 text-accent animate-spin" />
          </div>
        </PageContainer>
      </CommandCenterLayout>
    )
  }

  if (error || !details) {
    return (
      <CommandCenterLayout title="TLD Not Found" subtitle="Error loading data">
        <PageContainer>
          <div className="text-center py-20">
            <div className="w-16 h-16 bg-background-secondary rounded-full flex items-center justify-center mx-auto mb-6">
              <X className="w-8 h-8 text-foreground-subtle" />
            </div>
            <h1 className="text-xl font-medium text-foreground mb-2">TLD Not Found</h1>
            <p className="text-foreground-muted mb-8">{error || `The TLD .${tld} could not be found.`}</p>
            <Link
              href="/command/pricing"
              className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-background rounded-xl font-medium hover:bg-accent-hover transition-all"
            >
              <ArrowLeft className="w-4 h-4" />
              Back to TLD Pricing
            </Link>
          </div>
        </PageContainer>
      </CommandCenterLayout>
    )
  }

  return (
    <CommandCenterLayout 
      title={`.${details.tld}`}
      subtitle={details.description}
    >
      <PageContainer>
        {/* Breadcrumb */}
        <nav className="flex items-center gap-2 text-sm mb-6">
          <Link href="/command/pricing" className="text-foreground-subtle hover:text-foreground transition-colors">
            TLD Pricing
          </Link>
          <ChevronRight className="w-3.5 h-3.5 text-foreground-subtle" />
          <span className="text-foreground font-medium">.{details.tld}</span>
        </nav>

        {/* Stats Grid - All info from table */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <div title="Lowest first-year registration price across all tracked registrars">
            <StatCard 
              title="Buy Price (1y)" 
              value={`$${details.pricing.min.toFixed(2)}`}
              subtitle={`at ${details.cheapest_registrar}`}
              icon={DollarSign} 
            />
          </div>
          <div title={renewalInfo?.isTrap 
            ? `Warning: Renewal is ${renewalInfo.ratio.toFixed(1)}x the registration price` 
            : 'Annual renewal price after first year'}>
            <StatCard 
              title="Renewal (1y)" 
              value={details.min_renewal_price ? `$${details.min_renewal_price.toFixed(2)}` : '—'}
              subtitle={renewalInfo?.isTrap ? `${renewalInfo.ratio.toFixed(1)}x registration` : 'per year'}
              icon={RefreshCw} 
            />
          </div>
          <div title="Price change over the last 12 months">
            <StatCard 
              title="1y Change" 
              value={`${details.price_change_1y > 0 ? '+' : ''}${details.price_change_1y.toFixed(0)}%`}
              icon={details.price_change_1y > 0 ? TrendingUp : details.price_change_1y < 0 ? TrendingDown : Minus} 
            />
          </div>
          <div title="Price change over the last 3 years">
            <StatCard 
              title="3y Change" 
              value={`${details.price_change_3y > 0 ? '+' : ''}${details.price_change_3y.toFixed(0)}%`}
              icon={BarChart3} 
            />
          </div>
        </div>

        {/* Risk Level */}
        <div className="flex items-center gap-4 p-4 bg-background-secondary/30 border border-border/50 rounded-xl">
          <Shield className="w-5 h-5 text-foreground-muted" />
          <div className="flex-1">
            <p className="text-sm font-medium text-foreground">Risk Assessment</p>
            <p className="text-xs text-foreground-muted">Based on renewal ratio, price volatility, and market trends</p>
          </div>
          {getRiskBadge()}
        </div>

        {/* Renewal Trap Warning */}
        {renewalInfo?.isTrap && (
          <div className="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-foreground-muted 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 */}
        <div className="p-6 bg-background-secondary/30 border border-border/50 rounded-2xl">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-lg font-medium text-foreground">Price History</h2>
            <div className="flex items-center gap-1 bg-foreground/5 rounded-lg p-1">
              {(['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-md transition-all",
                    chartPeriod === period
                      ? "bg-accent text-background"
                      : "text-foreground-muted hover:text-foreground"
                  )}
                >
                  {period}
                </button>
              ))}
            </div>
          </div>
          
          <div className="pl-14">
            <PriceChart data={filteredHistory} chartStats={chartStats} />
          </div>
          
          {/* Chart Stats */}
          <div className="grid grid-cols-3 gap-4 mt-6 pt-6 border-t border-border/30">
            <div className="text-center">
              <p className="text-xs text-foreground-subtle uppercase mb-1">Period High</p>
              <p className="text-lg font-medium text-foreground tabular-nums">${chartStats.high.toFixed(2)}</p>
            </div>
            <div className="text-center">
              <p className="text-xs text-foreground-subtle uppercase mb-1">Average</p>
              <p className="text-lg font-medium text-foreground tabular-nums">${chartStats.avg.toFixed(2)}</p>
            </div>
            <div className="text-center">
              <p className="text-xs text-foreground-subtle uppercase mb-1">Period Low</p>
              <p className="text-lg font-medium text-foreground tabular-nums">${chartStats.low.toFixed(2)}</p>
            </div>
          </div>
        </div>

        {/* Registrar Comparison */}
        <div className="p-6 bg-background-secondary/30 border border-border/50 rounded-2xl">
          <h2 className="text-lg font-medium text-foreground mb-6">Registrar Comparison</h2>
          
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border/30">
                  <th className="text-left pb-3 text-sm font-medium text-foreground-muted">Registrar</th>
                  <th className="text-right pb-3 text-sm font-medium text-foreground-muted" title="First year registration price">Register</th>
                  <th className="text-right pb-3 text-sm font-medium text-foreground-muted" title="Annual renewal price">Renew</th>
                  <th className="text-right pb-3 text-sm font-medium text-foreground-muted" title="Transfer from another registrar">Transfer</th>
                  <th className="text-right pb-3"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border/20">
                {details.registrars.map((registrar, idx) => {
                  const hasRenewalTrap = registrar.renewal_price / registrar.registration_price > 1.5
                  const isBestValue = idx === 0 && !hasRenewalTrap
                  
                  return (
                    <tr key={registrar.name} className={clsx(isBestValue && "bg-accent/5")}>
                      <td className="py-4">
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-foreground">{registrar.name}</span>
                          {isBestValue && (
                            <span 
                              className="px-2 py-0.5 text-xs bg-accent/10 text-accent rounded-full cursor-help"
                              title="Best overall value: lowest registration price without renewal trap"
                            >
                              Best
                            </span>
                          )}
                          {idx === 0 && hasRenewalTrap && (
                            <span 
                              className="px-2 py-0.5 text-xs bg-amber-500/10 text-amber-400 rounded-full cursor-help"
                              title="Cheapest registration but high renewal costs"
                            >
                              Cheap Start
                            </span>
                          )}
                        </div>
                      </td>
                      <td className="py-4 text-right">
                        <span 
                          className={clsx(
                            "font-medium tabular-nums cursor-help",
                            isBestValue ? "text-accent" : "text-foreground"
                          )}
                          title={`First year: $${registrar.registration_price.toFixed(2)}`}
                        >
                          ${registrar.registration_price.toFixed(2)}
                        </span>
                      </td>
                      <td className="py-4 text-right">
                        <div className="flex items-center gap-1 justify-end">
                          <span 
                            className={clsx(
                              "tabular-nums cursor-help",
                              hasRenewalTrap ? "text-amber-400" : "text-foreground-muted"
                            )}
                            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="w-3.5 h-3.5 text-amber-400 cursor-help" />
                            </span>
                          )}
                        </div>
                      </td>
                      <td className="py-4 text-right">
                        <span 
                          className="text-foreground-muted tabular-nums cursor-help"
                          title={`Transfer from another registrar: $${registrar.transfer_price.toFixed(2)}`}
                        >
                          ${registrar.transfer_price.toFixed(2)}
                        </span>
                      </td>
                      <td className="py-4 text-right">
                        <a
                          href={getRegistrarUrl(registrar.name)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1 text-sm text-accent hover:text-accent/80 transition-colors"
                          title={`Register at ${registrar.name}`}
                        >
                          Visit
                          <ExternalLink className="w-3.5 h-3.5" />
                        </a>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* Quick Domain Check */}
        <div className="p-6 bg-background-secondary/30 border border-border/50 rounded-2xl">
          <h2 className="text-lg font-medium text-foreground mb-4">Quick Domain Check</h2>
          <p className="text-sm text-foreground-muted mb-4">
            Check if a domain is available with .{tld}
          </p>
          
          <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={`example or example.${tld}`}
                className="w-full h-11 px-4 bg-background border border-border/50 rounded-xl
                           text-sm text-foreground placeholder:text-foreground-subtle
                           focus:outline-none focus:border-accent/50 transition-all"
              />
            </div>
            <button
              onClick={handleDomainCheck}
              disabled={checkingDomain || !domainSearch.trim()}
              className="h-11 px-6 bg-accent text-background font-medium rounded-xl
                         hover:bg-accent-hover transition-all disabled:opacity-50"
            >
              {checkingDomain ? (
                <RefreshCw className="w-4 h-4 animate-spin" />
              ) : (
                'Check'
              )}
            </button>
          </div>
          
          {/* Result */}
          {domainResult && (
            <div className={clsx(
              "mt-4 p-4 rounded-xl border",
              domainResult.is_available 
                ? "bg-accent/10 border-accent/30" 
                : "bg-foreground/5 border-border/50"
            )}>
              <div className="flex items-center gap-3">
                {domainResult.is_available ? (
                  <Check className="w-5 h-5 text-accent" />
                ) : (
                  <X className="w-5 h-5 text-foreground-subtle" />
                )}
                <div>
                  <p className="font-medium text-foreground">{domainResult.domain}</p>
                  <p className="text-sm text-foreground-muted">
                    {domainResult.is_available ? 'Available for registration!' : 'Already registered'}
                  </p>
                </div>
              </div>
              
              {domainResult.is_available && (
                <a
                  href={getRegistrarUrl(details.cheapest_registrar, domainResult.domain)}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-3 inline-flex items-center gap-2 px-4 py-2 bg-accent text-background text-sm font-medium rounded-lg hover:bg-accent-hover transition-all"
                >
                  Register at {details.cheapest_registrar}
                  <ExternalLink className="w-3.5 h-3.5" />
                </a>
              )}
            </div>
          )}
        </div>

        {/* TLD Info */}
        <div className="p-6 bg-background-secondary/30 border border-border/50 rounded-2xl">
          <h2 className="text-lg font-medium text-foreground mb-4">TLD Information</h2>
          
          <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="p-4 bg-background/50 rounded-xl">
              <div className="flex items-center gap-2 text-foreground-muted mb-2">
                <Globe className="w-4 h-4" />
                <span className="text-xs uppercase">Type</span>
              </div>
              <p className="font-medium text-foreground capitalize">{details.type}</p>
            </div>
            <div className="p-4 bg-background/50 rounded-xl">
              <div className="flex items-center gap-2 text-foreground-muted mb-2">
                <Building className="w-4 h-4" />
                <span className="text-xs uppercase">Registry</span>
              </div>
              <p className="font-medium text-foreground">{details.registry}</p>
            </div>
            <div className="p-4 bg-background/50 rounded-xl">
              <div className="flex items-center gap-2 text-foreground-muted mb-2">
                <Calendar className="w-4 h-4" />
                <span className="text-xs uppercase">Introduced</span>
              </div>
              <p className="font-medium text-foreground">{details.introduced || 'Unknown'}</p>
            </div>
            <div className="p-4 bg-background/50 rounded-xl">
              <div className="flex items-center gap-2 text-foreground-muted mb-2">
                <BarChart3 className="w-4 h-4" />
                <span className="text-xs uppercase">Registrars</span>
              </div>
              <p className="font-medium text-foreground">{details.registrars.length} tracked</p>
            </div>
          </div>
        </div>
      </PageContainer>
    </CommandCenterLayout>
  )
}
