'use client'

import { useEffect, useState, useMemo, useCallback, memo } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { TerminalLayout } from '@/components/TerminalLayout'
import { 
  ExternalLink,
  Loader2,
  Diamond,
  Timer,
  Zap,
  Filter,
  ChevronDown,
  ChevronUp,
  Plus,
  Check,
  TrendingUp,
  RefreshCw,
  ArrowUpDown,
  Activity,
  Flame,
  Clock,
  Search,
  LayoutGrid,
  List,
  SlidersHorizontal,
  MoreHorizontal,
  Eye,
  Info,
  ShieldCheck,
  Sparkles,
  Store
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

// ============================================================================
// TYPES
// ============================================================================

interface MarketItem {
  id: string
  domain: string
  tld: string
  price: number
  currency: string
  price_type: 'bid' | 'fixed' | 'negotiable'
  status: 'auction' | 'instant'
  source: string
  is_pounce: boolean
  verified: boolean
  time_remaining?: string
  end_time?: string
  num_bids?: number
  slug?: string
  seller_verified: boolean
  url: string
  is_external: boolean
  pounce_score: number
}

type SortField = 'domain' | 'score' | 'price' | 'time' | 'source'
type SortDirection = 'asc' | 'desc'
type SourceFilter = 'all' | 'pounce' | 'external'
type PriceRange = 'all' | 'low' | 'mid' | 'high'

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

function parseTimeToSeconds(timeStr?: string): number {
  if (!timeStr) return Infinity
  let seconds = 0
  const days = timeStr.match(/(\d+)d/)
  const hours = timeStr.match(/(\d+)h/)
  const mins = timeStr.match(/(\d+)m/)
  if (days) seconds += parseInt(days[1]) * 86400
  if (hours) seconds += parseInt(hours[1]) * 3600
  if (mins) seconds += parseInt(mins[1]) * 60
  return seconds || Infinity
}

function formatPrice(price: number, currency = 'USD'): string {
  return new Intl.NumberFormat('en-US', { 
    style: 'currency', 
    currency, 
    maximumFractionDigits: 0 
  }).format(price)
}

// ============================================================================
// COMPONENTS
// ============================================================================

// Tooltip
const Tooltip = memo(({ children, content }: { children: React.ReactNode; content: string }) => (
  <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>
))
Tooltip.displayName = 'Tooltip'

// Stat Card
const StatCard = memo(({ 
  label, 
  value, 
  subValue, 
  icon: Icon, 
  highlight 
}: { 
  label: string
  value: string | number
  subValue?: string
  icon: React.ElementType
  highlight?: boolean
}) => (
  <div className={clsx(
    "bg-zinc-900/40 border rounded-xl p-4 flex items-start justify-between hover:bg-white/[0.02] transition-colors relative overflow-hidden group",
    highlight ? "border-emerald-500/30" : "border-white/5"
  )}>
    <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 transition-colors",
      highlight ? "text-emerald-400 bg-emerald-500/10" : "text-zinc-400 bg-zinc-800/50"
    )}>
      <Icon className="w-4 h-4" />
    </div>
  </div>
))
StatCard.displayName = 'StatCard'

// Score Ring
const ScoreDisplay = memo(({ score, mobile = false }: { score: number; mobile?: boolean }) => {
  const color = score >= 80 ? 'text-emerald-500' : score >= 50 ? 'text-amber-500' : 'text-zinc-600'
  
  if (mobile) {
    return (
      <div className={clsx(
        "px-2 py-0.5 rounded text-[10px] font-bold font-mono border",
        score >= 80 ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" :
        score >= 50 ? "bg-amber-500/10 text-amber-400 border-amber-500/20" :
        "bg-zinc-800 text-zinc-400 border-zinc-700"
      )}>
        {score}
      </div>
    )
  }

  const size = 36
  const strokeWidth = 3
  const radius = (size - strokeWidth) / 2
  const circumference = radius * 2 * Math.PI
  const offset = circumference - (score / 100) * circumference

  return (
    <Tooltip content={`Pounce Score: ${score}/100`}>
      <div className="relative flex items-center justify-center cursor-help" style={{ width: size, height: size }}>
        <svg className="absolute w-full h-full -rotate-90">
          <circle cx={size/2} cy={size/2} r={radius} className="stroke-zinc-800" strokeWidth={strokeWidth} fill="none" />
          <circle
            cx={size/2}
            cy={size/2}
            r={radius}
            className={clsx("transition-all duration-700 ease-out", color)}
            strokeWidth={strokeWidth}
            strokeDasharray={circumference}
            strokeDashoffset={offset}
            strokeLinecap="round"
            fill="none"
          />
        </svg>
        <span className={clsx("text-[11px] font-bold font-mono", score >= 80 ? 'text-emerald-400' : 'text-zinc-400')}>
          {score}
        </span>
      </div>
    </Tooltip>
  )
})
ScoreDisplay.displayName = 'ScoreDisplay'

// Filter Toggle
const FilterToggle = memo(({ active, onClick, label, icon: Icon }: { 
  active: boolean
  onClick: () => void
  label: string
  icon?: React.ElementType
}) => (
  <button
    onClick={onClick}
    className={clsx(
      "flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-medium transition-all border whitespace-nowrap",
      active
        ? "bg-white text-black border-white shadow-[0_0_10px_rgba(255,255,255,0.1)]"
        : "bg-transparent text-zinc-400 border-zinc-800 hover:border-zinc-700 hover:text-zinc-300"
    )}
  >
    {Icon && <Icon className="w-3 h-3" />}
    {label}
  </button>
))
FilterToggle.displayName = 'FilterToggle'

// Sort Header
const SortableHeader = memo(({
  label, field, currentSort, currentDirection, onSort, align = 'left', tooltip
}: {
  label: string
  field: SortField
  currentSort: SortField
  currentDirection: SortDirection
  onSort: (field: SortField) => void
  align?: 'left'|'center'|'right'
  tooltip?: string
}) => {
  const isActive = currentSort === field
  return (
    <div className={clsx(
      "flex items-center gap-1",
      align === 'right' && "justify-end ml-auto",
      align === 'center' && "justify-center mx-auto"
    )}>
      <button
        onClick={() => onSort(field)}
        className={clsx(
          "flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest transition-all group select-none py-2",
          isActive ? "text-white" : "text-zinc-500 hover:text-zinc-300"
        )}
      >
        {label}
        <div className={clsx("flex flex-col -space-y-1 transition-opacity", isActive ? "opacity-100" : "opacity-0 group-hover:opacity-30")}>
          <ChevronUp className={clsx("w-2 h-2", isActive && currentDirection === 'asc' ? "text-white" : "text-zinc-600")} />
          <ChevronDown className={clsx("w-2 h-2", isActive && currentDirection === 'desc' ? "text-white" : "text-zinc-600")} />
        </div>
      </button>
      {tooltip && (
        <Tooltip content={tooltip}>
          <Info className="w-3 h-3 text-zinc-700 hover:text-zinc-500 transition-colors cursor-help" />
        </Tooltip>
      )}
    </div>
  )
})
SortableHeader.displayName = 'SortableHeader'

// Pounce Direct Badge
const PounceBadge = memo(({ verified }: { verified: boolean }) => (
  <div className={clsx(
    "flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide",
    verified 
      ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"
      : "bg-amber-500/10 text-amber-400 border border-amber-500/20"
  )}>
    {verified ? (
      <>
        <ShieldCheck className="w-3 h-3" />
        Verified
      </>
    ) : (
      <>
        <Diamond className="w-3 h-3" />
        Pounce
      </>
    )}
  </div>
))
PounceBadge.displayName = 'PounceBadge'

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

export default function MarketPage() {
  const { subscription } = useStore()
  
  // Data
  const [items, setItems] = useState<MarketItem[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [stats, setStats] = useState({ total: 0, pounceCount: 0, auctionCount: 0, highScore: 0 })
  
  // Filters
  const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all')
  const [searchQuery, setSearchQuery] = useState('')
  const [priceRange, setPriceRange] = useState<PriceRange>('all')
  const [verifiedOnly, setVerifiedOnly] = useState(false)
  
  // Sort
  const [sortField, setSortField] = useState<SortField>('score')
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc')
  
  // Watchlist
  const [trackedDomains, setTrackedDomains] = useState<Set<string>>(new Set())
  const [trackingInProgress, setTrackingInProgress] = useState<string | null>(null)

  // Load data
  const loadData = useCallback(async () => {
    setLoading(true)
    try {
      const result = await api.getMarketFeed({
        source: sourceFilter,
        keyword: searchQuery || undefined,
        minPrice: priceRange === 'low' ? undefined : priceRange === 'mid' ? 100 : priceRange === 'high' ? 1000 : undefined,
        maxPrice: priceRange === 'low' ? 100 : priceRange === 'mid' ? 1000 : undefined,
        verifiedOnly,
        sortBy: sortField === 'score' ? 'score' : 
                sortField === 'price' ? (sortDirection === 'asc' ? 'price_asc' : 'price_desc') :
                sortField === 'time' ? 'time' : 'newest',
        limit: 100
      })
      
      setItems(result.items || [])
      setStats({
        total: result.total,
        pounceCount: result.pounce_direct_count,
        auctionCount: result.auction_count,
        highScore: (result.items || []).filter(i => i.pounce_score >= 80).length
      })
    } catch (error) {
      console.error('Failed to load market data:', error)
      setItems([])
    } finally {
      setLoading(false)
    }
  }, [sourceFilter, searchQuery, priceRange, verifiedOnly, sortField, sortDirection])

  useEffect(() => { loadData() }, [loadData])

  const handleRefresh = useCallback(async () => {
    setRefreshing(true)
    await loadData()
    setRefreshing(false)
  }, [loadData])

  const handleSort = useCallback((field: SortField) => {
    if (sortField === field) {
      setSortDirection(d => d === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDirection(field === 'score' || field === 'price' ? 'desc' : 'asc')
    }
  }, [sortField])

  const handleTrack = useCallback(async (domain: string) => {
    if (trackedDomains.has(domain) || trackingInProgress) return
    setTrackingInProgress(domain)
    try {
      await api.addDomain(domain)
      setTrackedDomains(prev => new Set([...Array.from(prev), domain]))
    } catch (error) { 
      console.error(error) 
    } finally { 
      setTrackingInProgress(null) 
    }
  }, [trackedDomains, trackingInProgress])

  // Client-side filtering for immediate UI feedback
  const filteredItems = useMemo(() => {
    let filtered = items

    // Additional client-side search (API already filters, but this is for instant feedback)
    if (searchQuery && !loading) {
      const query = searchQuery.toLowerCase()
      filtered = filtered.filter(item => item.domain.toLowerCase().includes(query))
    }

    // Sort
    const mult = sortDirection === 'asc' ? 1 : -1
    filtered = [...filtered].sort((a, b) => {
      // Pounce Direct always appears first within same score tier
      if (a.is_pounce !== b.is_pounce && sortField === 'score') {
        return a.is_pounce ? -1 : 1
      }
      
      switch (sortField) {
        case 'domain': return mult * a.domain.localeCompare(b.domain)
        case 'score': return mult * (a.pounce_score - b.pounce_score)
        case 'price': return mult * (a.price - b.price)
        case 'time': return mult * (parseTimeToSeconds(a.time_remaining) - parseTimeToSeconds(b.time_remaining))
        case 'source': return mult * a.source.localeCompare(b.source)
        default: return 0
      }
    })
    
    return filtered
  }, [items, searchQuery, sortField, sortDirection, loading])

  // Separate Pounce Direct from external
  const pounceItems = useMemo(() => filteredItems.filter(i => i.is_pounce), [filteredItems])
  const externalItems = useMemo(() => filteredItems.filter(i => !i.is_pounce), [filteredItems])

  return (
    <TerminalLayout 
      title="Market" 
      subtitle="Pounce Direct + Global Auctions"
      hideHeaderSearch={true}
    >
      <div className="relative">
        {/* Ambient glow */}
        <div className="pointer-events-none absolute inset-0 -z-10">
          <div className="absolute -top-72 left-1/2 -translate-x-1/2 w-[1200px] h-[900px] bg-emerald-500/8 blur-[160px]" />
        </div>

        <div className="space-y-6 pb-20 md:pb-0 relative">
          
          {/* METRICS */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
            <StatCard label="Total" value={stats.total} icon={Activity} />
            <StatCard label="Pounce Direct" value={stats.pounceCount} subValue="💎 Exclusive" icon={Diamond} highlight={stats.pounceCount > 0} />
            <StatCard label="External" value={stats.auctionCount} icon={Store} />
            <StatCard label="Top Tier" value={stats.highScore} subValue="80+ Score" icon={TrendingUp} />
          </div>

          {/* CONTROLS */}
          <div className="sticky top-0 z-30 bg-zinc-950/80 backdrop-blur-md py-4 border-b border-white/5 -mx-4 px-4 md:mx-0 md:px-0 md:border-none md:bg-transparent md:static">
            <div className="flex flex-col md:flex-row gap-4">
              {/* Search */}
              <div className="relative w-full md:w-80 group">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500 group-focus-within:text-white transition-colors" />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search domains..."
                  className="w-full pl-10 pr-4 py-2.5 bg-zinc-900 border border-white/10 rounded-xl
                             text-sm text-white placeholder:text-zinc-600
                             focus:outline-none focus:border-white/20 focus:ring-1 focus:ring-white/20 transition-all"
                />
              </div>
              
              {/* Filters */}
              <div className="flex items-center gap-2 overflow-x-auto w-full pb-1 md:pb-0 scrollbar-hide">
                <FilterToggle 
                  active={sourceFilter === 'pounce'} 
                  onClick={() => setSourceFilter(f => f === 'pounce' ? 'all' : 'pounce')} 
                  label="Pounce Only"
                  icon={Diamond}
                />
                <FilterToggle 
                  active={verifiedOnly} 
                  onClick={() => setVerifiedOnly(!verifiedOnly)} 
                  label="Verified"
                  icon={ShieldCheck}
                />
                <div className="w-px h-5 bg-white/10 mx-2 flex-shrink-0" />
                <FilterToggle 
                  active={priceRange === 'low'} 
                  onClick={() => setPriceRange(p => p === 'low' ? 'all' : 'low')} 
                  label="< $100"
                />
                <FilterToggle 
                  active={priceRange === 'high'} 
                  onClick={() => setPriceRange(p => p === 'high' ? 'all' : 'high')} 
                  label="$1k+"
                />
              </div>

              <div className="hidden md:block flex-1" />
              
              <button 
                onClick={handleRefresh} 
                className="hidden md:flex items-center gap-2 text-xs font-medium text-zinc-500 hover:text-white transition-colors"
              >
                <RefreshCw className={clsx("w-3.5 h-3.5", refreshing && "animate-spin")} />
                Refresh
              </button>
            </div>
          </div>

          {/* DATA GRID */}
          <div className="min-h-[400px]">
            {loading ? (
              <div className="flex flex-col items-center justify-center py-32 space-y-4">
                <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
                <p className="text-zinc-500 text-sm animate-pulse">Scanning markets...</p>
              </div>
            ) : filteredItems.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-32 text-center">
                <div className="w-16 h-16 bg-zinc-900 rounded-full flex items-center justify-center mb-4 border border-zinc-800">
                  <Search className="w-6 h-6 text-zinc-600" />
                </div>
                <h3 className="text-white font-medium mb-1">No matches found</h3>
                <p className="text-zinc-500 text-sm">Try adjusting your filters</p>
              </div>
            ) : (
              <div className="space-y-8">
                
                {/* POUNCE DIRECT SECTION (if any) */}
                {pounceItems.length > 0 && (
                  <div className="space-y-3">
                    <div className="flex items-center gap-3 px-2">
                      <div className="flex items-center gap-2 text-emerald-400">
                        <Diamond className="w-4 h-4 fill-emerald-400/20" />
                        <span className="text-xs font-bold uppercase tracking-widest">Pounce Direct</span>
                      </div>
                      <span className="text-[10px] text-zinc-500">Verified • Instant Buy • 0% Commission</span>
                      <div className="flex-1 h-px bg-gradient-to-r from-emerald-500/20 to-transparent" />
                    </div>
                    
                    <div className="border border-emerald-500/20 rounded-xl overflow-hidden bg-gradient-to-br from-emerald-500/5 to-transparent">
                      {pounceItems.map((item) => (
                        <div 
                          key={item.id} 
                          className="grid grid-cols-12 gap-4 px-6 py-4 items-center border-b border-emerald-500/10 last:border-b-0 hover:bg-emerald-500/5 transition-all group"
                        >
                          {/* Domain */}
                          <div className="col-span-5">
                            <div className="flex items-center gap-3">
                              <Diamond className="w-4 h-4 text-emerald-400 fill-emerald-400/20 flex-shrink-0" />
                              <div>
                                <div className="font-medium text-white text-[15px] tracking-tight">{item.domain}</div>
                                <div className="flex items-center gap-2 mt-0.5">
                                  <PounceBadge verified={item.verified} />
                                </div>
                              </div>
                            </div>
                          </div>
                          
                          {/* Score */}
                          <div className="col-span-2 flex justify-center">
                            <ScoreDisplay score={item.pounce_score} />
                          </div>
                          
                          {/* Price */}
                          <div className="col-span-2 text-right">
                            <div className="font-mono text-white font-medium">{formatPrice(item.price, item.currency)}</div>
                            <div className="text-[10px] text-emerald-400 mt-0.5">Instant Buy</div>
                          </div>
                          
                          {/* Action */}
                          <div className="col-span-3 flex items-center justify-end gap-3 opacity-0 group-hover:opacity-100 transition-opacity">
                            <Tooltip content="Add to Watchlist">
                              <button 
                                onClick={() => handleTrack(item.domain)}
                                disabled={trackedDomains.has(item.domain)}
                                className={clsx(
                                  "w-8 h-8 flex items-center justify-center rounded-full border transition-all",
                                  trackedDomains.has(item.domain) 
                                    ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20 cursor-default" 
                                    : "border-zinc-700 bg-zinc-900 text-zinc-400 hover:text-white hover:border-zinc-500 hover:scale-105"
                                )}
                              >
                                {trackedDomains.has(item.domain) ? <Check className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                              </button>
                            </Tooltip>
                            
                            <Link 
                              href={item.url}
                              className="h-9 px-5 flex items-center gap-2 bg-emerald-500 text-white rounded-lg text-xs font-bold hover:bg-emerald-400 transition-all hover:scale-105 shadow-lg shadow-emerald-500/20"
                            >
                              Buy Now
                              <Zap className="w-3 h-3" />
                            </Link>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                
                {/* EXTERNAL AUCTIONS */}
                {externalItems.length > 0 && (
                  <div className="space-y-3">
                    <div className="flex items-center gap-3 px-2">
                      <div className="flex items-center gap-2 text-zinc-400">
                        <Store className="w-4 h-4" />
                        <span className="text-xs font-bold uppercase tracking-widest">External Auctions</span>
                      </div>
                      <span className="text-[10px] text-zinc-500">{externalItems.length} from global platforms</span>
                      <div className="flex-1 h-px bg-gradient-to-r from-zinc-700/50 to-transparent" />
                    </div>
                    
                    {/* Desktop Table */}
                    <div className="hidden md:block border border-white/5 rounded-xl overflow-hidden bg-zinc-900/40 backdrop-blur-sm">
                      <div className="grid grid-cols-12 gap-4 px-6 py-3 border-b border-white/5 bg-white/[0.02]">
                        <div className="col-span-4">
                          <SortableHeader label="Domain" field="domain" currentSort={sortField} currentDirection={sortDirection} onSort={handleSort} />
                        </div>
                        <div className="col-span-2 text-center">
                          <SortableHeader label="Score" field="score" currentSort={sortField} currentDirection={sortDirection} onSort={handleSort} align="center" tooltip="Pounce Score based on length, TLD, and demand" />
                        </div>
                        <div className="col-span-2 text-right">
                          <SortableHeader label="Price" field="price" currentSort={sortField} currentDirection={sortDirection} onSort={handleSort} align="right" />
                        </div>
                        <div className="col-span-2 text-center">
                          <SortableHeader label="Time" field="time" currentSort={sortField} currentDirection={sortDirection} onSort={handleSort} align="center" />
                        </div>
                        <div className="col-span-2 text-right">
                          <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-600 py-2 block">Action</span>
                        </div>
                      </div>
                      
                      <div className="divide-y divide-white/5">
                        {externalItems.map((item) => {
                          const timeLeftSec = parseTimeToSeconds(item.time_remaining)
                          const isUrgent = timeLeftSec < 3600
                          return (
                            <div key={item.id} className="grid grid-cols-12 gap-4 px-6 py-4 items-center hover:bg-white/[0.04] transition-all group">
                              {/* Domain */}
                              <div className="col-span-4">
                                <div className="font-medium text-white text-[15px] tracking-tight">{item.domain}</div>
                                <div className="text-[11px] text-zinc-500 mt-0.5">{item.source}</div>
                              </div>
                              
                              {/* Score */}
                              <div className="col-span-2 flex justify-center">
                                <ScoreDisplay score={item.pounce_score} />
                              </div>
                              
                              {/* Price */}
                              <div className="col-span-2 text-right">
                                <div className="font-mono text-white font-medium">{formatPrice(item.price, item.currency)}</div>
                                {item.num_bids !== undefined && item.num_bids > 0 && (
                                  <div className="text-[10px] text-zinc-500 mt-0.5">{item.num_bids} bids</div>
                                )}
                              </div>
                              
                              {/* Time */}
                              <div className="col-span-2 flex justify-center">
                                <div className={clsx(
                                  "flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium",
                                  isUrgent ? "text-red-400 bg-red-500/10" : "text-zinc-400 bg-zinc-800/50"
                                )}>
                                  <Clock className="w-3 h-3" />
                                  {item.time_remaining || 'N/A'}
                                </div>
                              </div>
                              
                              {/* Actions */}
                              <div className="col-span-2 flex items-center justify-end gap-3 opacity-0 group-hover:opacity-100 transition-opacity">
                                <Tooltip content="Add to Watchlist">
                                  <button 
                                    onClick={() => handleTrack(item.domain)}
                                    disabled={trackedDomains.has(item.domain)}
                                    className={clsx(
                                      "w-8 h-8 flex items-center justify-center rounded-full border transition-all",
                                      trackedDomains.has(item.domain) 
                                        ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20 cursor-default" 
                                        : "border-zinc-700 bg-zinc-900 text-zinc-400 hover:text-white hover:border-zinc-500 hover:scale-105"
                                    )}
                                  >
                                    {trackedDomains.has(item.domain) ? <Check className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                                  </button>
                                </Tooltip>
                                
                                <a 
                                  href={item.url}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="h-9 px-4 flex items-center gap-2 bg-white text-zinc-950 rounded-lg text-xs font-bold hover:bg-zinc-200 transition-all hover:scale-105"
                                >
                                  Place Bid
                                  <ExternalLink className="w-3 h-3" />
                                </a>
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>
                    
                    {/* Mobile Cards */}
                    <div className="md:hidden space-y-3">
                      {externalItems.map((item) => {
                        const timeLeftSec = parseTimeToSeconds(item.time_remaining)
                        const isUrgent = timeLeftSec < 3600
                        return (
                          <div key={item.id} className="bg-zinc-900/40 border border-white/5 rounded-xl p-4">
                            <div className="flex justify-between items-start mb-3">
                              <span className="font-medium text-white text-base">{item.domain}</span>
                              <ScoreDisplay score={item.pounce_score} mobile />
                            </div>
                            
                            <div className="flex items-center justify-between mb-4">
                              <div>
                                <div className="text-[10px] text-zinc-500 uppercase tracking-wider mb-0.5">Current Bid</div>
                                <div className="font-mono text-lg font-medium text-white">{formatPrice(item.price, item.currency)}</div>
                              </div>
                              <div className="text-right">
                                <div className="text-[10px] text-zinc-500 uppercase tracking-wider mb-0.5">Ends In</div>
                                <div className={clsx("flex items-center gap-1.5 justify-end font-medium", isUrgent ? "text-red-400" : "text-zinc-400")}>
                                  <Clock className="w-3 h-3" />
                                  {item.time_remaining || 'N/A'}
                                </div>
                              </div>
                            </div>
                            
                            <div className="grid grid-cols-2 gap-3">
                              <button 
                                onClick={() => handleTrack(item.domain)}
                                disabled={trackedDomains.has(item.domain)}
                                className={clsx(
                                  "flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-medium border transition-all",
                                  trackedDomains.has(item.domain) 
                                    ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" 
                                    : "bg-zinc-800/30 text-zinc-400 border-zinc-700/50 active:scale-95"
                                )}
                              >
                                {trackedDomains.has(item.domain) ? (
                                  <><Check className="w-4 h-4" /> Tracked</>
                                ) : (
                                  <><Eye className="w-4 h-4" /> Watch</>
                                )}
                              </button>
                              <a 
                                href={item.url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-bold bg-white text-black active:scale-95 transition-all"
                              >
                                Place Bid
                                <ExternalLink className="w-3 h-3 opacity-50" />
                              </a>
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </TerminalLayout>
  )
}
