'use client'

import { useEffect, useState, useMemo, useRef, useCallback } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { Sidebar } from '@/components/Sidebar'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import {
  ArrowLeft,
  TrendingUp,
  TrendingDown,
  Minus,
  Globe,
  Building,
  ExternalLink,
  Search,
  ChevronRight,
  Check,
  X,
  RefreshCw,
  DollarSign,
  BarChart3,
  Loader2,
  Lock,
  Sparkles,
  Diamond,
  Eye,
  Gavel,
  Target,
  Menu,
  Settings,
  Shield,
  LogOut,
  Crown,
  Zap,
  Coins,
  Tag,
  Briefcase
} from 'lucide-react'
import Link from 'next/link'
import Image from 'next/image'
import clsx from 'clsx'

// ============================================================================
// TYPES & HELPERS
// ============================================================================

type UserTier = 'scout' | 'trader' | 'tycoon'
type ChartPeriod = '1M' | '3M' | '1Y' | 'ALL'

function getTierLevel(tier: UserTier): number {
  switch (tier) {
    case 'tycoon': return 3
    case 'trader': return 2
    case 'scout': return 1
    default: return 1
  }
}

interface MarketplaceLink {
  name: string
  description: string
  url: string
  type: string
}

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
  marketplace_links?: MarketplaceLink[]
}

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

// ============================================================================
// CHART COMPONENT
// ============================================================================

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 lg:h-64 flex flex-col items-center justify-center text-white/20 text-xs font-mono space-y-2">
        <BarChart3 className="w-8 h-8" />
        <span>No price history available</span>
      </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'

  return (
    <div 
      ref={containerRef}
      className="relative h-48 lg:h-64 w-full cursor-crosshair"
      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.1" />
            <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] && (
          <line 
            x1={points[hoveredIndex].x} 
            y1="0" 
            x2={points[hoveredIndex].x} 
            y2="100" 
            stroke="#52525b" 
            strokeWidth="1" 
            strokeDasharray="2"
            vectorEffect="non-scaling-stroke"
          />
        )}
      </svg>
      
      {hoveredIndex !== null && points[hoveredIndex] && (
        <div
          className="absolute w-3 h-3 bg-[#020202] border-2 transform -translate-x-1/2 -translate-y-1/2 pointer-events-none z-10"
          style={{ 
            left: `${points[hoveredIndex].x}%`, 
            top: `${points[hoveredIndex].y}%`,
            borderColor: strokeColor
          }}
        />
      )}
      
      {hoveredIndex !== null && points[hoveredIndex] && (
        <div 
          className="absolute -top-12 transform -translate-x-1/2 bg-[#0a0a0a] border border-white/10 px-3 py-2 z-20 pointer-events-none"
          style={{ left: `${points[hoveredIndex].x}%` }}
        >
          <div className="flex flex-col items-center">
            <span className="text-sm font-bold text-white font-mono">${points[hoveredIndex].price.toFixed(2)}</span>
            <span className="text-[10px] text-white/40 font-mono">{new Date(points[hoveredIndex].date).toLocaleDateString()}</span>
          </div>
        </div>
      )}
    </div>
  )
}

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

export default function TldDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { fetchSubscription, subscription, user, logout, checkAuth } = useStore()
  const tld = params.tld as string
  
  const userTier: UserTier = (subscription?.tier as UserTier) || 'scout'
  const tierLevel = getTierLevel(userTier)
  
  const canAccessDetailPage = tierLevel >= 2
  const canSeeRenewal = tierLevel >= 2
  const canSeeFullHistory = tierLevel >= 3
  
  const availablePeriods: ChartPeriod[] = useMemo(() => {
    if (tierLevel >= 3) return ['1M', '3M', '1Y', 'ALL']
    if (tierLevel >= 2) return ['1Y']
    return []
  }, [tierLevel])
  
  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)
  
  // Mobile Menu
  const [menuOpen, setMenuOpen] = useState(false)

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

  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()
  
  // Mobile Nav
  const mobileNavItems = [
    { href: '/terminal/hunt', label: 'Radar', icon: Target, active: false },
    { href: '/terminal/market', label: 'Market', icon: Gavel, active: false },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: false },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: true },
  ]
  
  const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap
  
  const drawerNavSections = [
    {
      title: 'Discover',
      items: [
        { href: '/terminal/hunt', label: 'Radar', icon: Target },
        { href: '/terminal/market', label: 'Market', icon: Gavel },
        { href: '/terminal/intel', label: 'Intel', icon: TrendingUp },
      ]
    },
    {
      title: 'Manage',
      items: [
        { href: '/terminal/watchlist', label: 'Watchlist', icon: Eye },
        { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase },
        { href: '/terminal/sniper', label: 'Sniper', icon: Target },
      ]
    },
    {
      title: 'Monetize',
      items: [
        { href: '/terminal/yield', label: 'Yield', icon: Coins, isNew: true },
        { href: '/terminal/listing', label: 'For Sale', icon: Tag },
      ]
    }
  ]

  if (loading) {
    return (
      <div className="min-h-screen bg-[#020202] flex items-center justify-center">
        <Loader2 className="w-6 h-6 text-accent animate-spin" />
      </div>
    )
  }

  if (error || !details) {
    return (
      <div className="min-h-screen bg-[#020202] flex flex-col items-center justify-center text-white/40 px-4">
        <X className="w-12 h-12 text-white/10 mb-4" />
        <h1 className="text-xl font-display text-white mb-2">TLD Not Found</h1>
        <p className="mb-6 text-center">The extension .{tld} is not currently tracked.</p>
        <Link href="/terminal/intel" className="text-accent hover:text-white flex items-center gap-2 text-sm">
          <ArrowLeft className="w-4 h-4" /> Back to Intel
        </Link>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-[#020202]">
      {/* Desktop Sidebar */}
      <div className="hidden lg:block">
        <Sidebar />
      </div>
      
      {/* Main Content */}
      <main className="lg:pl-[240px]">
        
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <header 
          className="lg:hidden sticky top-0 z-40 bg-[#020202]/95 backdrop-blur-md border-b border-white/[0.08]" 
          style={{ paddingTop: 'env(safe-area-inset-top)' }}
        >
          <div className="px-4 py-3">
            {/* Back + Title */}
            <div className="flex items-center gap-3 mb-3">
              <Link href="/terminal/intel" className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40">
                <ArrowLeft className="w-4 h-4" />
              </Link>
              <div className="flex items-center gap-2">
                <div className="w-1 h-6 bg-accent" />
                <span className="text-lg font-bold text-white font-mono">.{details.tld}</span>
                <span className={clsx(
                  "px-1.5 py-0.5 text-[9px] font-mono border",
                  details.risk_level === 'high' ? "bg-red-500/10 text-red-400 border-red-500/20" :
                  details.risk_level === 'medium' ? "bg-amber-500/10 text-amber-400 border-amber-500/20" :
                  "bg-accent/10 text-accent border-accent/20"
                )}>
                  {details.risk_level}
                </span>
              </div>
            </div>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-4 gap-2">
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-sm font-bold text-accent tabular-nums font-mono">${details.pricing.min.toFixed(0)}</div>
                <div className="text-[8px] font-mono text-white/30 uppercase tracking-wider">Reg</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-sm font-bold text-white tabular-nums font-mono">
                  {canSeeRenewal ? `$${details.min_renewal_price.toFixed(0)}` : '—'}
                </div>
                <div className="text-[8px] font-mono text-white/30 uppercase tracking-wider">Renew</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className={clsx(
                  "text-sm font-bold tabular-nums font-mono",
                  details.price_change_1y > 5 ? "text-orange-400" : details.price_change_1y < -5 ? "text-accent" : "text-white/40"
                )}>
                  {details.price_change_1y > 0 ? '+' : ''}{details.price_change_1y.toFixed(0)}%
                </div>
                <div className="text-[8px] font-mono text-white/30 uppercase tracking-wider">1Y</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className={clsx(
                  "text-sm font-bold tabular-nums font-mono",
                  canSeeFullHistory
                    ? (details.price_change_3y > 10 ? "text-orange-400" : details.price_change_3y < -10 ? "text-accent" : "text-white/40")
                    : "text-white/20"
                )}>
                  {canSeeFullHistory ? `${details.price_change_3y > 0 ? '+' : ''}${details.price_change_3y.toFixed(0)}%` : '—'}
                </div>
                <div className="text-[8px] font-mono text-white/30 uppercase tracking-wider">3Y</div>
              </div>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DESKTOP HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="hidden lg:block px-10 pt-10 pb-6 border-b border-white/[0.08]">
          <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6">
            <div className="space-y-4">
              {/* Breadcrumb */}
              <nav className="flex items-center gap-2 text-[10px] font-mono text-white/40 tracking-wide">
                <Link href="/terminal/intel" className="hover:text-accent transition-colors">Intel</Link>
                <ChevronRight className="w-3 h-3" />
                <span className="text-white">.{details.tld}</span>
              </nav>
              
              <div className="flex items-center gap-4">
                <div className="w-1 h-12 bg-accent" />
                <div>
                  <div className="flex items-center gap-3">
                    <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em] text-white">
                      .{details.tld}
                    </h1>
                    <span className={clsx(
                      "px-2 py-1 text-[10px] font-mono border",
                      details.risk_level === 'high' ? "bg-red-500/10 text-red-400 border-red-500/20" :
                      details.risk_level === 'medium' ? "bg-amber-500/10 text-amber-400 border-amber-500/20" :
                      "bg-accent/10 text-accent border-accent/20"
                    )}>
                      {details.risk_level} risk
                    </span>
                  </div>
                  <p className="text-white/40 text-sm mt-1 max-w-lg">{details.description}</p>
                </div>
              </div>
            </div>
            
            <div className="flex gap-8">
              <div className="text-right">
                <div className="text-2xl font-bold text-accent font-mono">${details.pricing.min.toFixed(2)}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Registration</div>
              </div>
              {canSeeRenewal && (
                <div className="text-right">
                  <div className={clsx("text-2xl font-bold font-mono", renewalInfo?.isTrap ? "text-amber-400" : "text-white")}>
                    ${details.min_renewal_price.toFixed(2)}
                  </div>
                  <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Renewal</div>
                </div>
              )}
            </div>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* CONTENT */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-6 pb-28 lg:pb-10">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            {/* Left Column: Chart + Search */}
            <div className="lg:col-span-2 space-y-6">
              
              {/* Price Chart */}
              <div className="border border-white/[0.08] bg-white/[0.01] p-4 lg:p-6 relative">
                {/* Lock overlay for Scout */}
                {!canAccessDetailPage && (
                  <div className="absolute inset-0 bg-[#020202]/80 backdrop-blur-[2px] flex flex-col items-center justify-center z-20">
                    <div className="w-12 h-12 border border-white/10 bg-white/5 flex items-center justify-center mb-4">
                      <Lock className="w-5 h-5 text-white/30" />
                    </div>
                    <h3 className="text-sm font-bold text-white mb-2">Charts Locked</h3>
                    <p className="text-xs text-white/40 mb-4 text-center max-w-xs">
                      Upgrade for detailed price history.
                    </p>
                    <Link
                      href="/pricing"
                      className="px-4 py-2 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white transition-colors flex items-center gap-2"
                    >
                      <Sparkles className="w-3 h-3" />
                      Unlock
                    </Link>
                  </div>
                )}
                
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-xs font-mono text-white/40 uppercase tracking-wider">Price History</h3>
                  <div className="flex bg-white/5 border border-white/10">
                    {(['1M', '3M', '1Y', 'ALL'] as ChartPeriod[]).map((period) => {
                      const isAvailable = availablePeriods.includes(period)
                      const isActive = chartPeriod === period && isAvailable
                      return (
                        <button
                          key={period}
                          onClick={() => isAvailable && setChartPeriod(period)}
                          disabled={!isAvailable}
                          className={clsx(
                            "px-2 lg:px-3 py-1.5 text-[10px] font-mono transition-all",
                            isActive
                              ? "bg-white/10 text-white"
                              : isAvailable
                                ? "text-white/40 hover:text-white"
                                : "text-white/15 cursor-not-allowed"
                          )}
                        >
                          {period}
                        </button>
                      )
                    })}
                  </div>
                </div>
                
                <div className={clsx(!canAccessDetailPage && "blur-sm")}>
                  <PriceChart data={filteredHistory} chartStats={chartStats} />
                </div>
                
                <div className="grid grid-cols-3 gap-4 mt-4 pt-4 border-t border-white/[0.06]">
                  <div className="text-center">
                    <div className="text-[9px] text-white/30 font-mono uppercase mb-1">High</div>
                    <div className="text-sm font-mono text-white">${chartStats.high.toFixed(2)}</div>
                  </div>
                  <div className="text-center border-l border-r border-white/[0.06]">
                    <div className="text-[9px] text-white/30 font-mono uppercase mb-1">Average</div>
                    <div className="text-sm font-mono text-white">${chartStats.avg.toFixed(2)}</div>
                  </div>
                  <div className="text-center">
                    <div className="text-[9px] text-white/30 font-mono uppercase mb-1">Low</div>
                    <div className="text-sm font-mono text-accent">${chartStats.low.toFixed(2)}</div>
                  </div>
                </div>
              </div>

              {/* Domain Check */}
              <div className="border border-white/[0.08] bg-white/[0.01] p-4 lg:p-6">
                <div className="flex flex-col gap-4">
                  <div>
                    <h2 className="text-xs font-mono text-white/40 uppercase tracking-wider mb-1 flex items-center gap-2">
                      <Search className="w-3 h-3" />
                      Check Availability
                    </h2>
                    <p className="text-[10px] font-mono text-white/30">Check if your .{details.tld} domain is available</p>
                  </div>

                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={domainSearch}
                      onChange={(e) => setDomainSearch(e.target.value)}
                      onKeyDown={(e) => e.key === 'Enter' && handleDomainCheck()}
                      placeholder={`example.${details.tld}`}
                      className="flex-1 h-10 bg-white/5 border border-white/10 px-4 text-white placeholder:text-white/25 outline-none focus:border-accent/50 font-mono text-sm"
                    />
                    <button
                      onClick={handleDomainCheck}
                      disabled={checkingDomain || !domainSearch.trim()}
                      className="h-10 px-4 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white transition-colors disabled:opacity-50"
                    >
                      {checkingDomain ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Check'}
                    </button>
                  </div>
                </div>
                
                {domainResult && (
                  <div className="mt-4 pt-4 border-t border-white/[0.06]">
                    <div className={clsx(
                      "p-3 border flex items-center justify-between",
                      domainResult.is_available 
                        ? "bg-accent/5 border-accent/20" 
                        : "bg-red-500/5 border-red-500/20"
                    )}>
                      <div className="flex items-center gap-3">
                        {domainResult.is_available ? (
                          <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center">
                            <Check className="w-4 h-4 text-accent" />
                          </div>
                        ) : (
                          <div className="w-8 h-8 bg-red-500/10 border border-red-500/20 flex items-center justify-center">
                            <X className="w-4 h-4 text-red-400" />
                          </div>
                        )}
                        <div>
                          <div className="font-mono font-medium text-white text-sm">{domainResult.domain}</div>
                          <div className={clsx("text-[10px] font-mono", domainResult.is_available ? "text-accent" : "text-red-400")}>
                            {domainResult.is_available ? 'Available' : 'Registered'}
                          </div>
                        </div>
                      </div>
                      
                      {domainResult.is_available && (
                        <a
                          href={getRegistrarUrl(details.cheapest_registrar, domainResult.domain)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="px-3 py-2 bg-accent text-black text-[10px] font-bold uppercase tracking-wider hover:bg-white transition-colors flex items-center gap-1.5"
                        >
                          Register
                          <ExternalLink className="w-3 h-3" />
                        </a>
                      )}
                    </div>
                  </div>
                )}
              </div>

              {/* Info Cards */}
              <div className="grid grid-cols-2 gap-px bg-white/[0.05]">
                <div className="bg-[#020202] p-4">
                  <div className="flex items-center gap-2 text-white/40 mb-2">
                    <Globe className="w-4 h-4" />
                    <span className="text-[9px] font-mono uppercase tracking-wider">Type</span>
                  </div>
                  <div className="text-sm text-white capitalize font-mono">{details.type}</div>
                </div>
                <div className="bg-[#020202] p-4">
                  <div className="flex items-center gap-2 text-white/40 mb-2">
                    <Building className="w-4 h-4" />
                    <span className="text-[9px] font-mono uppercase tracking-wider">Registry</span>
                  </div>
                  <div className="text-sm text-white truncate font-mono">{details.registry}</div>
                </div>
              </div>
            </div>

            {/* Right Column: Registrars */}
            <div className="border border-white/[0.08] bg-white/[0.01] h-fit">
              <div className="p-4 border-b border-white/[0.06]">
                <h3 className="text-xs font-mono text-white/40 uppercase tracking-wider">Registrar Prices</h3>
              </div>
              
              <div className="divide-y divide-white/[0.05]">
                {details.registrars.slice(0, 5).map((registrar, idx) => {
                  const hasRenewalTrap = registrar.renewal_price / registrar.registration_price > 1.5
                  const isBest = idx === 0 && !hasRenewalTrap

                  return (
                    <div key={registrar.name} className="p-4 hover:bg-white/[0.02] transition-colors">
                      <div className="flex items-center justify-between mb-2">
                        <div>
                          <div className="text-sm text-white font-mono">{registrar.name}</div>
                          {isBest && <span className="text-[9px] text-accent font-mono uppercase">Best Value</span>}
                          {idx === 0 && hasRenewalTrap && canSeeRenewal && (
                            <span className="text-[9px] text-amber-400 font-mono uppercase">Renewal Trap</span>
                          )}
                        </div>
                        <div className="text-right">
                          <div className={clsx("font-mono text-sm font-bold", isBest ? "text-accent" : "text-white")}>
                            ${registrar.registration_price.toFixed(2)}
                          </div>
                          {canSeeRenewal && (
                            <div className={clsx("text-[10px] font-mono", hasRenewalTrap ? "text-amber-400" : "text-white/30")}>
                              ${registrar.renewal_price.toFixed(2)}/yr
                            </div>
                          )}
                        </div>
                      </div>
                      <a 
                        href={getRegistrarUrl(registrar.name)}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="w-full h-8 bg-white/5 border border-white/10 text-white/50 hover:text-white text-[10px] font-mono uppercase tracking-wider flex items-center justify-center gap-2 transition-colors"
                      >
                        Visit
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    </div>
                  )
                })}
              </div>
              
              {userTier === 'scout' && (
                <div className="p-4 border-t border-white/[0.06]">
                  <Link 
                    href="/pricing" 
                    className="flex items-center justify-center gap-2 text-[10px] font-mono text-accent hover:text-white transition-colors uppercase tracking-wider"
                  >
                    <Sparkles className="w-3 h-3" />
                    Upgrade for renewal prices
                  </Link>
                </div>
              )}
            </div>

            {/* Marketplace Links */}
            {details.marketplace_links && details.marketplace_links.length > 0 && (
              <div className="border border-white/[0.08] bg-white/[0.01] h-fit mt-4">
                <div className="p-4 border-b border-white/[0.06]">
                  <h3 className="text-xs font-mono text-white/40 uppercase tracking-wider">Buy Existing Domains</h3>
                </div>
                
                <div className="divide-y divide-white/[0.05]">
                  {details.marketplace_links.map((marketplace) => (
                    <a
                      key={marketplace.name}
                      href={marketplace.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="p-4 hover:bg-white/[0.02] transition-colors flex items-center justify-between group"
                    >
                      <div>
                        <div className="text-sm text-white font-mono group-hover:text-accent transition-colors">
                          {marketplace.name}
                        </div>
                        <div className="text-[10px] text-white/40 font-mono">
                          {marketplace.description}
                        </div>
                      </div>
                      <ExternalLink className="w-4 h-4 text-white/20 group-hover:text-accent transition-colors" />
                    </a>
                  ))}
                </div>
              </div>
            )}
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE BOTTOM NAV */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <nav 
          className="lg:hidden fixed bottom-0 left-0 right-0 z-50 bg-[#020202] border-t border-white/[0.08]"
          style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
        >
          <div className="flex items-stretch h-14">
            {mobileNavItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={clsx(
                  "flex-1 flex flex-col items-center justify-center gap-0.5 relative transition-colors",
                  item.active ? "text-accent" : "text-white/40 active:text-white/80"
                )}
              >
                {item.active && (
                  <div className="absolute top-0 left-1/2 -translate-x-1/2 w-10 h-0.5 bg-accent" />
                )}
                <item.icon className="w-5 h-5" />
                <span className="text-[9px] font-mono uppercase tracking-wider">{item.label}</span>
              </Link>
            ))}
            
            <button
              onClick={() => setMenuOpen(true)}
              className="flex-1 flex flex-col items-center justify-center gap-0.5 text-white/40 active:text-white/80 transition-all"
            >
              <Menu className="w-5 h-5" />
              <span className="text-[9px] font-mono uppercase tracking-wider">Menu</span>
            </button>
          </div>
        </nav>
        
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE DRAWER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {menuOpen && (
          <div className="lg:hidden fixed inset-0 z-[100]">
            <div 
              className="absolute inset-0 bg-black/80 animate-in fade-in duration-200"
              onClick={() => setMenuOpen(false)}
            />
            
            <div className="absolute top-0 right-0 bottom-0 w-[80%] max-w-[300px] bg-[#0A0A0A] border-l border-white/[0.08] animate-in slide-in-from-right duration-300 flex flex-col" style={{ paddingTop: 'env(safe-area-inset-top)', paddingBottom: 'env(safe-area-inset-bottom)' }}>
              
              <div className="flex items-center justify-between p-4 border-b border-white/[0.08]">
                <div className="flex items-center gap-3">
                  <Image src="/pounce-puma.png" alt="Pounce" width={28} height={28} className="object-contain" />
                  <div>
                    <h2 className="text-sm font-bold text-white tracking-wider">POUNCE</h2>
                    <p className="text-[9px] text-white/40 font-mono uppercase tracking-widest">Terminal v1.0</p>
                  </div>
                </div>
                <button
                  onClick={() => setMenuOpen(false)}
                  className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/60 hover:text-white active:bg-white/5 transition-all"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>
              
              <div className="flex-1 overflow-y-auto py-4">
                {drawerNavSections.map((section) => (
                  <div key={section.title} className="mb-4">
                    <div className="flex items-center gap-2 px-4 mb-2">
                      <div className="w-1 h-3 bg-accent" />
                      <span className="text-[9px] font-bold text-white/30 uppercase tracking-[0.2em]">{section.title}</span>
                    </div>
                    <div>
                      {section.items.map((item: any) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={() => setMenuOpen(false)}
                          className="flex items-center gap-3 px-4 py-2.5 text-white/60 active:text-white active:bg-white/[0.03] transition-colors border-l-2 border-transparent active:border-accent"
                        >
                          <item.icon className="w-4 h-4 text-white/30" />
                          <span className="text-sm font-medium flex-1">{item.label}</span>
                          {item.isNew && (
                            <span className="px-1.5 py-0.5 text-[8px] font-bold bg-accent text-black">NEW</span>
                          )}
                        </Link>
                      ))}
                    </div>
                  </div>
                ))}
                
                <div className="pt-3 border-t border-white/[0.08] mx-4">
                  <Link
                    href="/terminal/settings"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center gap-3 py-2.5 text-white/50 active:text-white transition-colors"
                  >
                    <Settings className="w-4 h-4" />
                    <span className="text-sm font-medium">Settings</span>
                  </Link>
                  
                  {user?.is_admin && (
                    <Link
                      href="/admin"
                      onClick={() => setMenuOpen(false)}
                      className="flex items-center gap-3 py-2.5 text-amber-500/70 active:text-amber-400 transition-colors"
                    >
                      <Shield className="w-4 h-4" />
                      <span className="text-sm font-medium">Admin</span>
                    </Link>
                  )}
                </div>
              </div>
              
              <div className="p-4 bg-white/[0.02] border-t border-white/[0.08]">
                <div className="flex items-center gap-3 mb-3">
                  <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center">
                    <TierIcon className="w-4 h-4 text-accent" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-bold text-white truncate">
                      {user?.name || user?.email?.split('@')[0] || 'User'}
                    </p>
                    <p className="text-[9px] font-mono text-white/40 uppercase tracking-wider">{tierName}</p>
                  </div>
                </div>
                
                {tierName === 'Scout' && (
                  <Link 
                    href="/pricing"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center justify-center gap-2 w-full py-2.5 bg-accent text-black text-xs font-bold uppercase tracking-wider active:scale-[0.98] transition-all mb-2"
                  >
                    <Sparkles className="w-3 h-3" />
                    Upgrade
                  </Link>
                )}
                
                <button
                  onClick={() => { logout(); setMenuOpen(false) }}
                  className="flex items-center justify-center gap-2 w-full py-2 border border-white/10 text-white/40 text-[10px] font-mono uppercase tracking-wider active:bg-white/5 transition-all"
                >
                  <LogOut className="w-3 h-3" />
                  Sign out
                </button>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  )
}
