'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { useStore } from '@/lib/store'
import {
  ExternalLink,
  Loader2,
  Diamond,
  Zap,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  ChevronDown,
  RefreshCw,
  Search,
  Eye,
  EyeOff,
  ShieldCheck,
  Ban,
  X,
  Filter,
  Shield,
  Gavel,
  Clock,
  DollarSign,
  Timer,
  CheckCircle2,
} from 'lucide-react'
import clsx from 'clsx'

// ============================================================================
// 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 SourceFilter = 'all' | 'pounce' | 'external'
type PriceRange = 'all' | 'low' | 'mid' | 'high'

// ============================================================================
// HELPERS
// ============================================================================

function calcTimeRemaining(endTimeIso?: string): string {
  if (!endTimeIso) return 'N/A'
  const end = new Date(endTimeIso).getTime()
  const now = Date.now()
  const diff = end - now

  if (diff <= 0) return 'Ended'

  const seconds = Math.floor(diff / 1000)
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const mins = Math.floor((seconds % 3600) / 60)

  if (days > 0) return `${days}d ${hours}h`
  if (hours > 0) return `${hours}h ${mins}m`
  if (mins > 0) return `${mins}m`
  return '< 1m'
}

function getSecondsUntilEnd(endTimeIso?: string): number {
  if (!endTimeIso) return Infinity
  const diff = new Date(endTimeIso).getTime() - Date.now()
  return diff > 0 ? diff / 1000 : -1
}

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

function isSpam(domain: string): boolean {
  const name = domain.split('.')[0]
  if (name.includes('-')) return true
  if (name.length > 4 && /\d/.test(name)) return true
  if (/^\d+$/.test(name)) return true
  return false
}

// ============================================================================
// COMPONENT
// ============================================================================

interface AuctionsTabProps {
  showToast: (message: string, type?: 'success' | 'error' | 'info') => void
}

export function AuctionsTab({ showToast }: AuctionsTabProps) {
  const openAnalyze = useAnalyzePanelStore((s) => s.open)
  const addDomain = useStore((s) => s.addDomain)
  const deleteDomain = useStore((s) => s.deleteDomain)

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

  const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all')
  const [searchQuery, setSearchQuery] = useState('')
  const [priceRange, setPriceRange] = useState<PriceRange>('all')
  const [hideSpam, setHideSpam] = useState(true)
  const [tldFilter, setTldFilter] = useState<string>('all')
  const [searchFocused, setSearchFocused] = useState(false)

  const [trackedDomains, setTrackedDomains] = useState<Set<string>>(new Set())
  const [trackingInProgress, setTrackingInProgress] = useState<string | null>(null)

  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const ITEMS_PER_PAGE = 50

  const [filtersOpen, setFiltersOpen] = useState(false)

  const [sortField, setSortField] = useState<'domain' | 'score' | 'price' | 'time'>('time')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')

  const loadData = useCallback(async (currentPage = 1) => {
    setLoading(true)
    try {
      const result = await api.getMarketFeed({
        source: sourceFilter,
        keyword: searchQuery || undefined,
        tld: tldFilter === 'all' ? undefined : tldFilter,
        minPrice: priceRange === 'low' ? undefined : priceRange === 'mid' ? 100 : priceRange === 'high' ? 1000 : undefined,
        maxPrice: priceRange === 'low' ? 100 : priceRange === 'mid' ? 1000 : undefined,
        sortBy: 'time',
        limit: ITEMS_PER_PAGE,
        offset: (currentPage - 1) * ITEMS_PER_PAGE,
      })

      setItems(result.items || [])
      setStats({
        total: result.total,
        pounceCount: result.pounce_direct_count,
        auctionCount: result.auction_count,
        highScore: (result.items || []).filter((i: MarketItem) => i.pounce_score >= 80).length,
      })
      setTotalPages(Math.ceil((result.total || 0) / ITEMS_PER_PAGE))
    } catch (error) {
      console.error('Failed to load market data:', error)
      setItems([])
    } finally {
      setLoading(false)
    }
  }, [sourceFilter, searchQuery, priceRange, tldFilter])

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

  const handlePageChange = useCallback((newPage: number) => {
    setPage(newPage)
    loadData(newPage)
  }, [loadData])

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

  useEffect(() => {
    const loadTrackedDomains = async () => {
      try {
        const result = await api.getDomains(1, 100)
        const domainSet = new Set(result.domains.map((d: any) => d.name))
        setTrackedDomains(domainSet)
      } catch (error) {
        console.error('Failed to load tracked domains:', error)
      }
    }
    loadTrackedDomains()
  }, [])

  const handleTrack = useCallback(async (domain: string) => {
    if (trackingInProgress) return
    setTrackingInProgress(domain)

    try {
      if (trackedDomains.has(domain)) {
        const result = await api.getDomains(1, 100)
        const domainToDelete = result.domains.find((d: any) => d.name === domain)
        if (domainToDelete) {
          await deleteDomain(domainToDelete.id)
          setTrackedDomains((prev) => {
            const next = new Set(Array.from(prev))
            next.delete(domain)
            return next
          })
          showToast(`Removed: ${domain}`, 'success')
        }
      } else {
        await addDomain(domain)
        setTrackedDomains((prev) => new Set([...Array.from(prev), domain]))
        showToast(`Tracking: ${domain}`, 'success')
      }
    } catch (error: any) {
      showToast(error.message || 'Failed', 'error')
    } finally {
      setTrackingInProgress(null)
    }
  }, [trackedDomains, trackingInProgress, showToast, addDomain, deleteDomain])

  const filteredItems = useMemo(() => {
    let filtered = items

    const nowMs = Date.now()
    filtered = filtered.filter((item) => {
      if (item.status !== 'auction') return true
      if (!item.end_time) return true
      const t = Date.parse(item.end_time)
      if (Number.isNaN(t)) return true
      return t > nowMs - 2000
    })

    if (searchQuery && !loading) {
      const query = searchQuery.toLowerCase()
      filtered = filtered.filter((item) => item.domain.toLowerCase().includes(query))
    }

    if (hideSpam) {
      filtered = filtered.filter((item) => !isSpam(item.domain))
    }

    const mult = sortDirection === 'asc' ? 1 : -1
    filtered.sort((a, b) => {
      switch (sortField) {
        case 'domain':
          return mult * a.domain.localeCompare(b.domain)
        case 'score':
          return mult * ((a.pounce_score || 0) - (b.pounce_score || 0))
        case 'price':
          return mult * (a.price - b.price)
        case 'time':
          const aTime = a.end_time ? new Date(a.end_time).getTime() : Infinity
          const bTime = b.end_time ? new Date(b.end_time).getTime() : Infinity
          return mult * (aTime - bTime)
        default:
          return 0
      }
    })

    return filtered
  }, [items, searchQuery, loading, hideSpam, sortField, sortDirection])

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

  const activeFiltersCount = [sourceFilter !== 'all', priceRange !== 'all', tldFilter !== 'all', hideSpam].filter(Boolean).length

  // Loading State
  if (loading && items.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-24">
        <Loader2 className="w-8 h-8 text-accent animate-spin mb-4" />
        <span className="text-xs font-mono text-white/30 uppercase tracking-widest">Loading marketplace...</span>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header Stats */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-gradient-to-br from-accent/20 to-accent/5 border border-accent/30 flex items-center justify-center">
            <Gavel className="w-6 h-6 text-accent" />
          </div>
          <div>
            <div className="text-2xl font-black text-white font-mono tracking-tight">
              {stats.total.toLocaleString()}
            </div>
            <div className="text-[10px] font-mono text-white/40 uppercase tracking-widest">Live auctions & listings</div>
          </div>
        </div>
        <button
          onClick={handleRefresh}
          disabled={refreshing}
          className="p-3 border border-white/10 text-white/40 hover:text-accent hover:border-accent/30 hover:bg-accent/5 transition-all"
          title="Refresh auctions"
        >
          <RefreshCw className={clsx("w-5 h-5", refreshing && "animate-spin")} />
        </button>
      </div>

      {/* Search */}
      <div className={clsx(
        "relative border-2 transition-all duration-200",
        searchFocused ? "border-accent/50 bg-accent/[0.02]" : "border-white/[0.08] bg-white/[0.02]"
      )}>
        <div className="flex items-center">
          <Search className={clsx("w-5 h-5 ml-4 transition-colors", searchFocused ? "text-accent" : "text-white/30")} />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onFocus={() => setSearchFocused(true)}
            onBlur={() => setSearchFocused(false)}
            placeholder="Search auctions and listings..."
            className="flex-1 bg-transparent px-4 py-4 text-sm text-white placeholder:text-white/20 outline-none font-mono"
          />
          {searchQuery && (
            <button onClick={() => setSearchQuery('')} className="p-4 text-white/30 hover:text-white transition-colors">
              <X className="w-5 h-5" />
            </button>
          )}
        </div>
      </div>

      {/* Advanced Filters */}
      <button
        onClick={() => setFiltersOpen(!filtersOpen)}
        className={clsx(
          "flex items-center justify-between w-full py-3 px-5 border transition-all",
          filtersOpen ? "border-accent/30 bg-accent/[0.03]" : "border-white/[0.08] bg-white/[0.02] hover:border-white/20"
        )}
      >
        <div className="flex items-center gap-3">
          <Filter className={clsx("w-4 h-4", filtersOpen ? "text-accent" : "text-white/40")} />
          <span className={clsx("text-xs font-mono uppercase tracking-widest", filtersOpen ? "text-accent" : "text-white/50")}>
            Market Filters
          </span>
          {activeFiltersCount > 0 && (
            <span className="px-2 py-0.5 text-[9px] font-black bg-accent text-black">{activeFiltersCount}</span>
          )}
        </div>
        <ChevronRight className={clsx("w-4 h-4 transition-transform", filtersOpen ? "rotate-90 text-accent" : "text-white/30")} />
      </button>

      {filtersOpen && (
        <div className="p-5 border border-white/[0.08] bg-white/[0.01] space-y-5 animate-in fade-in slide-in-from-top-2 duration-200">
          {/* Source Filter */}
          <div>
            <div className="text-[10px] font-mono text-white/40 uppercase tracking-widest mb-3">Source</div>
            <div className="flex gap-2">
              {[
                { value: 'all', label: 'All Sources' },
                { value: 'pounce', label: 'Pounce Direct', icon: Diamond },
                { value: 'external', label: 'External' },
              ].map((item) => (
                <button
                  key={item.value}
                  onClick={() => setSourceFilter(item.value as SourceFilter)}
                  className={clsx(
                    "flex-1 py-3 text-xs font-bold uppercase tracking-wider border transition-all flex items-center justify-center gap-2",
                    sourceFilter === item.value 
                      ? "border-accent bg-accent/10 text-accent" 
                      : "border-white/[0.08] text-white/40 hover:border-white/20"
                  )}
                >
                  {item.icon && <item.icon className="w-4 h-4" />}
                  {item.label}
                </button>
              ))}
            </div>
          </div>

          {/* Price & TLD */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
            <div>
              <div className="text-[10px] font-mono text-white/40 uppercase tracking-widest mb-3">Price Range</div>
              <div className="flex gap-2">
                {[
                  { value: 'all', label: 'All' },
                  { value: 'low', label: '< $100' },
                  { value: 'mid', label: '< $1k' },
                  { value: 'high', label: '$1k+' },
                ].map((item) => (
                  <button
                    key={item.value}
                    onClick={() => setPriceRange(item.value as PriceRange)}
                    className={clsx(
                      "flex-1 py-3 text-xs font-mono border transition-all",
                      priceRange === item.value 
                        ? "border-amber-400 bg-amber-400/10 text-amber-400 font-bold" 
                        : "border-white/[0.08] text-white/40 hover:border-white/20"
                    )}
                  >
                    {item.label}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <div className="text-[10px] font-mono text-white/40 uppercase tracking-widest mb-3">TLD Filter</div>
              <div className="flex gap-2 flex-wrap">
                {['all', 'com', 'ai', 'io', 'net', 'ch'].map((tld) => (
                  <button
                    key={tld}
                    onClick={() => setTldFilter(tld)}
                    className={clsx(
                      "px-4 py-3 text-xs font-mono uppercase border transition-all",
                      tldFilter === tld 
                        ? "border-accent bg-accent/10 text-accent font-bold" 
                        : "border-white/[0.08] text-white/40 hover:border-white/20"
                    )}
                  >
                    {tld === 'all' ? 'All' : `.${tld}`}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Hide Spam */}
          <button
            onClick={() => setHideSpam(!hideSpam)}
            className={clsx(
              "flex items-center justify-between w-full py-3 px-4 border transition-all",
              hideSpam ? "border-accent/30 bg-accent/5" : "border-white/[0.08] hover:border-white/20"
            )}
          >
            <div className="flex items-center gap-3">
              <Ban className={clsx("w-4 h-4", hideSpam ? "text-accent" : "text-white/30")} />
              <span className={clsx("text-xs font-mono uppercase tracking-wider", hideSpam ? "text-accent" : "text-white/50")}>
                Hide spam domains (numbers, hyphens)
              </span>
            </div>
            <div className={clsx(
              "w-5 h-5 border flex items-center justify-center transition-all",
              hideSpam ? "border-accent bg-accent" : "border-white/20"
            )}>
              {hideSpam && <CheckCircle2 className="w-3 h-3 text-black" />}
            </div>
          </button>
        </div>
      )}

      {/* Results Info */}
      <div className="flex items-center justify-between px-1">
        <div className="flex items-center gap-3 text-[11px] font-mono text-white/40 uppercase tracking-widest">
          <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse" />
          <span>{filteredItems.length} active listings</span>
          {stats.highScore > 0 && (
            <>
              <span className="text-white/20">•</span>
              <span className="text-accent">{stats.highScore} premium</span>
            </>
          )}
        </div>
        {totalPages > 1 && (
          <span className="text-[11px] font-mono text-white/30 uppercase tracking-widest">
            Page {page} of {totalPages}
          </span>
        )}
      </div>

      {/* Results Table */}
      {filteredItems.length === 0 ? (
        <div className="text-center py-24 border border-dashed border-white/[0.08] bg-white/[0.01]">
          <Search className="w-16 h-16 text-white/5 mx-auto mb-6" />
          <p className="text-white/50 text-sm font-mono uppercase tracking-widest font-bold">No auctions found</p>
          <p className="text-white/20 text-xs font-mono mt-3 uppercase tracking-wider max-w-sm mx-auto leading-relaxed">
            Try adjusting your search criteria or filters
          </p>
        </div>
      ) : (
        <>
          <div className="border border-white/[0.08] bg-[#020202] overflow-hidden">
            {/* Table Header */}
            <div className="hidden lg:grid grid-cols-[1fr_80px_120px_100px_180px] gap-6 px-6 py-4 text-[10px] font-mono text-white/40 uppercase tracking-[0.15em] border-b border-white/[0.08] bg-white/[0.02]">
              <button 
                onClick={() => handleSort('domain')} 
                className="flex items-center gap-2 hover:text-white transition-colors text-left"
              >
                <span className={clsx(sortField === 'domain' && "text-accent font-bold")}>Domain</span>
                {sortField === 'domain' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
              </button>
              <button 
                onClick={() => handleSort('score')} 
                className="flex items-center gap-2 justify-center hover:text-white transition-colors"
              >
                <span className={clsx(sortField === 'score' && "text-accent font-bold")}>Score</span>
                {sortField === 'score' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
              </button>
              <button 
                onClick={() => handleSort('price')} 
                className="flex items-center gap-2 justify-end hover:text-white transition-colors"
              >
                <span className={clsx(sortField === 'price' && "text-accent font-bold")}>Price</span>
                {sortField === 'price' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
              </button>
              <button 
                onClick={() => handleSort('time')} 
                className="flex items-center gap-2 justify-center hover:text-white transition-colors"
              >
                <span className={clsx(sortField === 'time' && "text-accent font-bold")}>Ends</span>
                {sortField === 'time' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
              </button>
              <div className="text-right">Actions</div>
            </div>

            {/* Table Body */}
            <div className="divide-y divide-white/[0.04]">
              {filteredItems.map((item) => {
                const timeLeftSec = getSecondsUntilEnd(item.end_time)
                const isUrgent = timeLeftSec > 0 && timeLeftSec < 3600
                const isPounce = item.is_pounce
                const displayTime = item.status === 'auction' ? calcTimeRemaining(item.end_time) : null
                const isTracked = trackedDomains.has(item.domain)
                const isTracking = trackingInProgress === item.domain

                return (
                  <div key={item.id} className={clsx("group hover:bg-white/[0.02] transition-all", isPounce && "bg-accent/[0.02]")}>
                    {/* Mobile Row */}
                    <div className="lg:hidden p-5">
                      <div className="flex items-start justify-between gap-4 mb-4">
                        <div className="min-w-0">
                          <button 
                            onClick={() => openAnalyze(item.domain)} 
                            className="text-lg font-bold text-white font-mono truncate block text-left hover:text-accent transition-colors"
                          >
                            {item.domain}
                          </button>
                          <div className="flex items-center gap-2 mt-2 text-[10px] font-mono text-white/30 uppercase tracking-wider">
                            <span className="bg-white/5 px-2 py-0.5 border border-white/5">{item.source}</span>
                            {isPounce && item.verified && <ShieldCheck className="w-3.5 h-3.5 text-accent" />}
                            <span className={clsx(isUrgent && "text-orange-400 font-bold")}>
                              {isPounce ? 'INSTANT' : displayTime || 'N/A'}
                            </span>
                          </div>
                        </div>

                        <div className="text-right shrink-0">
                          <div className={clsx(
                            "text-lg font-black font-mono tracking-tight",
                            isPounce ? "text-accent" : "text-white"
                          )}>
                            {formatPrice(item.price)}
                          </div>
                          <div className={clsx(
                            "text-[10px] font-mono px-2 py-0.5 mt-1 inline-block border",
                            item.pounce_score >= 80 ? "text-accent bg-accent/5 border-accent/20" : 
                            item.pounce_score >= 50 ? "text-amber-400 bg-amber-400/5 border-amber-400/20" : 
                            "text-white/30 bg-white/5 border-white/5"
                          )}>
                            SCORE {item.pounce_score}
                          </div>
                        </div>
                      </div>

                      <div className="flex gap-2">
                        <button
                          onClick={() => handleTrack(item.domain)}
                          disabled={isTracking}
                          className={clsx(
                            "flex-1 h-12 text-xs font-bold uppercase tracking-widest border flex items-center justify-center gap-2 transition-all",
                            isTracked 
                              ? "border-accent bg-accent/5 text-accent" 
                              : "border-white/10 text-white/50 hover:bg-white/5"
                          )}
                        >
                          {isTracking ? <Loader2 className="w-4 h-4 animate-spin" /> : isTracked ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
                          {isTracked ? 'Tracked' : 'Track'}
                        </button>

                        <button 
                          onClick={() => openAnalyze(item.domain)} 
                          className="w-14 h-12 border border-white/10 text-white/50 flex items-center justify-center hover:text-accent hover:border-accent/30 hover:bg-accent/5 transition-all"
                        >
                          <Shield className="w-5 h-5" />
                        </button>

                        <a
                          href={item.url}
                          target={isPounce ? '_self' : '_blank'}
                          rel={isPounce ? undefined : 'noopener noreferrer'}
                          className={clsx(
                            "flex-1 h-12 text-xs font-black uppercase tracking-widest flex items-center justify-center gap-2 transition-all",
                            isPounce ? "bg-accent text-black hover:bg-white" : "bg-white/10 text-white hover:bg-white/20"
                          )}
                        >
                          {isPounce ? 'Buy' : 'Bid'}
                          {!isPounce && <ExternalLink className="w-4 h-4" />}
                        </a>
                      </div>
                    </div>

                    {/* Desktop Row */}
                    <div className="hidden lg:grid grid-cols-[1fr_80px_120px_100px_180px] gap-6 items-center px-6 py-4">
                      {/* Domain */}
                      <div className="flex items-center gap-3 min-w-0">
                        <button 
                          onClick={() => openAnalyze(item.domain)} 
                          className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors text-left"
                        >
                          {item.domain}
                        </button>
                        <div className="flex items-center gap-2 text-[9px] font-mono text-white/20 uppercase tracking-wider opacity-0 group-hover:opacity-100 transition-opacity">
                          <span>{item.source}</span>
                          {isPounce && item.verified && <ShieldCheck className="w-3 h-3 text-accent" />}
                        </div>
                      </div>

                      {/* Score */}
                      <div className="text-center">
                        <span className={clsx(
                          "text-xs font-mono font-bold px-3 py-1 border inline-block",
                          item.pounce_score >= 80 ? "text-accent bg-accent/5 border-accent/20" : 
                          item.pounce_score >= 50 ? "text-amber-400 bg-amber-400/5 border-amber-400/20" : 
                          "text-white/30 bg-white/5 border-white/5"
                        )}>
                          {item.pounce_score}
                        </span>
                      </div>

                      {/* Price */}
                      <div className="text-right">
                        <div className={clsx(
                          "font-mono text-sm font-bold tracking-tight",
                          isPounce ? "text-accent" : "text-white"
                        )}>
                          {formatPrice(item.price)}
                        </div>
                        <div className="text-[9px] font-mono text-white/20 uppercase tracking-wider">
                          {item.price_type === 'bid' ? 'Current Bid' : 'Buy Now'}
                        </div>
                      </div>

                      {/* Time */}
                      <div className="text-center">
                        {isPounce ? (
                          <span className="text-xs text-accent font-mono font-bold flex items-center justify-center gap-1.5 uppercase tracking-wider">
                            <Zap className="w-3.5 h-3.5" />
                            Instant
                          </span>
                        ) : (
                          <span className={clsx(
                            "text-xs font-mono uppercase tracking-wider flex items-center justify-center gap-1.5",
                            isUrgent ? "text-orange-400 font-bold" : "text-white/40"
                          )}>
                            {isUrgent && <Timer className="w-3.5 h-3.5" />}
                            {displayTime || 'N/A'}
                          </span>
                        )}
                      </div>

                      {/* Actions */}
                      <div className="flex items-center justify-end gap-2 opacity-40 group-hover:opacity-100 transition-all">
                        <button
                          onClick={() => handleTrack(item.domain)}
                          disabled={isTracking}
                          className={clsx(
                            "w-10 h-10 flex items-center justify-center border transition-all",
                            isTracked 
                              ? "bg-accent/5 text-accent border-accent/20 hover:bg-red-500/5 hover:text-red-400 hover:border-red-500/20" 
                              : "text-white/50 border-white/10 hover:text-white hover:bg-white/5"
                          )}
                          title={isTracked ? "Untrack" : "Track Domain"}
                        >
                          {isTracking ? <Loader2 className="w-4 h-4 animate-spin" /> : isTracked ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
                        </button>

                        <button 
                          onClick={() => openAnalyze(item.domain)} 
                          className="w-10 h-10 flex items-center justify-center border border-white/10 text-white/50 hover:text-accent hover:border-accent/30 hover:bg-accent/5 transition-all" 
                          title="Analyze"
                        >
                          <Shield className="w-4 h-4" />
                        </button>

                        <a
                          href={item.url}
                          target={isPounce ? '_self' : '_blank'}
                          rel={isPounce ? undefined : 'noopener noreferrer'}
                          className={clsx(
                            "h-10 px-5 flex items-center gap-2 text-[10px] font-black uppercase tracking-widest transition-all",
                            isPounce 
                              ? "bg-accent text-black hover:bg-white" 
                              : "bg-white/10 text-white hover:bg-white/20"
                          )}
                        >
                          {isPounce ? 'Buy' : 'Bid'}
                          {!isPounce && <ExternalLink className="w-3.5 h-3.5" />}
                        </a>
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 pt-4">
              <button
                onClick={() => handlePageChange(page - 1)}
                disabled={page === 1}
                className="w-12 h-12 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-20 disabled:cursor-not-allowed transition-all"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>
              <div className="flex items-center bg-white/[0.02] border border-white/[0.08] px-6 h-12">
                <span className="text-xs text-white/50 font-mono uppercase tracking-widest">
                  Page <span className="text-white font-bold mx-1">{page}</span> / {totalPages}
                </span>
              </div>
              <button
                onClick={() => handlePageChange(page + 1)}
                disabled={page === totalPages}
                className="w-12 h-12 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-20 disabled:cursor-not-allowed transition-all"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>
          )}
        </>
      )}
    </div>
  )
}
