'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import {
  Clock,
  ExternalLink,
  Search,
  Flame,
  Timer,
  Gavel,
  X,
  Lock,
  TrendingUp,
  ChevronUp,
  ChevronDown,
  Diamond,
  ShieldCheck,
  Filter,
  ArrowUpRight,
  ArrowRight,
  Loader2
} from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import clsx from 'clsx'

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
}

interface Auction {
  domain: string
  platform: string
  platform_url: string
  current_bid: number
  currency: string
  num_bids: number
  end_time: string
  time_remaining: string
  buy_now_price: number | null
  reserve_met: boolean | null
  traffic: number | null
  age_years: number | null
  tld: string
  affiliate_url: string
  is_pounce?: boolean
  slug?: string
}

type TabType = 'all' | 'ending' | 'hot'

const PLATFORMS = [
  { id: 'All', name: 'All' },
  { id: 'GoDaddy', name: 'GoDaddy' },
  { id: 'Sedo', name: 'Sedo' },
  { id: 'NameJet', name: 'NameJet' },
  { id: 'DropCatch', name: 'DropCatch' },
]

const PREMIUM_TLDS = ['com', 'io', 'ai', 'co', 'de', 'ch', 'net', 'org', 'app', 'dev', 'xyz']

// Live time calculation (same as Terminal)
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 isVanityDomain(auction: Auction): boolean {
  const parts = auction.domain.split('.')
  if (parts.length < 2) return false
  const name = parts[0]
  const tld = parts.slice(1).join('.').toLowerCase()
  if (!PREMIUM_TLDS.includes(tld)) return false
  if (name.length > 12) return false
  if (name.includes('-')) return false
  if (name.length > 4 && /\d/.test(name)) return false
  return true
}

export default function AcquirePage() {
  const { isAuthenticated, checkAuth, isLoading: authLoading } = useStore()
  const router = useRouter()
  
  const [allAuctions, setAllAuctions] = useState<Auction[]>([])
  const [endingSoon, setEndingSoon] = useState<Auction[]>([])
  const [hotAuctions, setHotAuctions] = useState<Auction[]>([])
  const [pounceItems, setPounceItems] = useState<MarketItem[]>([])
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<TabType>('all')
  
  // Stats from API (real totals, not array lengths)
  const [stats, setStats] = useState({ total: 0, ending: 0, direct: 0 })
  
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedPlatform, setSelectedPlatform] = useState('All')
  const [searchFocused, setSearchFocused] = useState(false)
  const [showFilters, setShowFilters] = useState(false)

  const [directGate, setDirectGate] = useState<{ domain: string; slug: string } | null>(null)
  
  useEffect(() => {
    checkAuth()
    loadAuctions()
  }, [checkAuth])

  const loadAuctions = async () => {
    setLoading(true)
    try {
      const [allFeed, endingFeed, hotFeed, pounceFeed] = await Promise.all([
        api.getMarketFeed({ source: 'external', limit: 150, sortBy: 'time' }),
        api.getMarketFeed({ source: 'external', endingWithin: 24, limit: 100, sortBy: 'time' }),
        api.getMarketFeed({ source: 'external', limit: 50, sortBy: 'score' }),
        api.getMarketFeed({ source: 'pounce', limit: 20 }),
      ])
      
      const convertToAuction = (item: MarketItem): Auction => ({
        domain: item.domain,
        platform: item.source,
        platform_url: item.url,
        current_bid: item.price,
        currency: item.currency,
        num_bids: item.num_bids || 0,
        end_time: item.end_time || '',
        time_remaining: item.time_remaining || '',
        buy_now_price: item.price_type === 'fixed' ? item.price : null,
        reserve_met: null,
        traffic: null,
        age_years: null,
        tld: item.tld,
        affiliate_url: item.url,
        slug: item.slug,
      })
      
      const toAuctions = (items: MarketItem[]) => items.map(convertToAuction)
      
      setAllAuctions(toAuctions(allFeed.items || []))
      setEndingSoon(toAuctions(endingFeed.items || []))
      setHotAuctions(toAuctions(hotFeed.items || []))
      setPounceItems(pounceFeed.items || [])
      
      // Set real totals from API
      setStats({
        total: allFeed.total || allFeed.auction_count || 0,
        ending: endingFeed.total || 0,
        direct: pounceFeed.pounce_direct_count || pounceFeed.total || 0,
      })
    } catch (error) {
      console.error('Failed to load auctions:', error)
    } finally {
      setLoading(false)
    }
  }

  const getCurrentAuctions = (): Auction[] => {
    switch (activeTab) {
      case 'ending': return endingSoon
      case 'hot': return hotAuctions
      default: return allAuctions
    }
  }

  // Trigger re-render every 30s to update live times
  const [tick, setTick] = useState(0)
  useEffect(() => {
    const interval = setInterval(() => setTick(t => t + 1), 30000)
    return () => clearInterval(interval)
  }, [])

  const displayAuctions = useMemo(() => {
    const current = getCurrentAuctions()
    const nowMs = Date.now()
    
    // Filter out expired auctions
    const activeAuctions = current.filter(auction => {
      if (!auction.end_time) return true
      const endMs = Date.parse(auction.end_time)
      if (Number.isNaN(endMs)) return true
      return endMs > (nowMs - 2000) // 2s grace
    })
    
    // Convert Pounce Direct items to Auction format and mark them
    const pounceAuctions: Auction[] = pounceItems.map(item => ({
      domain: item.domain,
      platform: 'Pounce',
      platform_url: item.url,
      current_bid: item.price,
      currency: item.currency,
      num_bids: 0,
      end_time: '',
      time_remaining: '',
      buy_now_price: item.price,
      reserve_met: null,
      traffic: null,
      age_years: null,
      tld: item.tld,
      affiliate_url: item.url,
      is_pounce: true, // Special flag
      slug: item.slug,
    }))
    
    // Apply auth filter
    const filteredAuctions = isAuthenticated ? activeAuctions : activeAuctions.filter(isVanityDomain)
    
    // Pounce Direct always on top
    return [...pounceAuctions, ...filteredAuctions]
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab, allAuctions, endingSoon, hotAuctions, pounceItems, isAuthenticated, tick])

  const filteredAuctions = displayAuctions.filter(auction => {
    if (searchQuery && !auction.domain.toLowerCase().includes(searchQuery.toLowerCase())) return false
    if (selectedPlatform !== 'All' && auction.platform !== selectedPlatform) return false
    return true
  })

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(amount)
  }

  const getTimeColor = (endTime: string) => {
    if (!endTime) return 'text-white/40'
    const diff = new Date(endTime).getTime() - Date.now()
    if (diff <= 0) return 'text-white/20'
    const hours = diff / (1000 * 60 * 60)
    if (hours < 1) return 'text-red-400'
    if (hours < 12) return 'text-amber-400'
    return 'text-white/40'
  }

  const getPounceSlug = useCallback((auction: Auction): string | null => {
    if (!auction.is_pounce) return null
    if (auction.slug) return auction.slug
    const match = (auction.affiliate_url || '').match(/^\/buy\/(.+)$/)
    return match?.[1] || null
  }, [])

  const handlePounceDirectClick = useCallback((auction: Auction) => {
    const slug = getPounceSlug(auction)
    if (!slug) return
    if (isAuthenticated) {
      router.push(`/buy/${slug}`)
      return
    }
    setDirectGate({ domain: auction.domain, slug })
  }, [getPounceSlug, isAuthenticated, router])

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#020202]">
        <Loader2 className="w-8 h-8 text-accent animate-spin" />
      </div>
    )
  }
  
  return (
    <div className="min-h-screen bg-[#020202] text-white">
      {/* Background */}
      <div className="fixed inset-0 pointer-events-none z-0">
        <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.03] mix-blend-overlay" />
        <div 
          className="absolute inset-0 opacity-[0.02]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,0.3) 0.5px, transparent 0.5px), linear-gradient(90deg, rgba(255,255,255,0.3) 0.5px, transparent 0.5px)`,
            backgroundSize: '80px 80px',
          }}
        />
      </div>

      <Header />

      {/* Pounce Direct gate (public conversion modal) */}
      {directGate && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <button
            type="button"
            aria-label="Close"
            onClick={() => setDirectGate(null)}
            className="absolute inset-0 bg-black/70"
          />
          <div className="relative w-full max-w-md border border-white/[0.10] bg-[#020202] shadow-2xl">
            <div className="flex items-start justify-between gap-4 p-4 border-b border-white/[0.08]">
              <div>
                <div className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Pounce Direct</div>
                <h3 className="mt-1 text-lg font-display text-white">{directGate.domain}</h3>
                <p className="mt-1 text-xs font-mono text-white/40">
                  Verified owner. Contact requires login.
                </p>
              </div>
              <button
                type="button"
                onClick={() => setDirectGate(null)}
                className="p-1 text-white/40 hover:text-white"
                aria-label="Close"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-3">
              <div className="flex items-start gap-3 border border-accent/20 bg-accent/[0.04] p-3">
                <Lock className="w-4 h-4 text-accent shrink-0 mt-0.5" />
                <div>
                  <p className="text-xs font-bold text-white">Seller protection</p>
                  <p className="text-[10px] font-mono text-white/50 mt-1">
                    Log in to send an inquiry. This reduces spam and keeps buyer identity consistent.
                  </p>
                </div>
              </div>

              <Link
                href={`/buy/${directGate.slug}`}
                className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-white/[0.05] border border-white/[0.10] text-white text-xs font-bold uppercase tracking-wider hover:bg-white/[0.08] transition-colors"
              >
                View Details
                <ArrowUpRight className="w-4 h-4" />
              </Link>
              <div className="grid grid-cols-2 gap-3">
                <Link
                  href={`/login?redirect=${encodeURIComponent(`/buy/${directGate.slug}`)}`}
                  className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white transition-colors"
                >
                  Login
                  <ArrowRight className="w-4 h-4" />
                </Link>
                <Link
                  href={`/register?redirect=${encodeURIComponent(`/buy/${directGate.slug}`)}`}
                  className="w-full flex items-center justify-center gap-2 px-4 py-3 border border-white/[0.10] bg-white/[0.02] text-white text-xs font-bold uppercase tracking-wider hover:bg-white/[0.05] transition-colors"
                >
                  Register
                  <ArrowRight className="w-4 h-4" />
                </Link>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* MOBILE HEADER */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <header 
        className="lg:hidden sticky top-14 z-40 bg-[#020202]/95 backdrop-blur-md border-b border-white/[0.08]"
      >
        <div className="px-4 py-3">
          {/* Title Row */}
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
              <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Acquire</span>
            </div>
            <div className="flex items-center gap-2 text-[10px] font-mono text-white/40">
              <span>{filteredAuctions.length} assets</span>
            </div>
          </div>
          
          {/* Stats Grid */}
          <div className="grid grid-cols-3 gap-2">
            <div className="bg-white/[0.02] border border-white/[0.08] p-2">
              <div className="text-lg font-bold text-white tabular-nums">{stats.total || allAuctions.length}</div>
              <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Total</div>
            </div>
            <div className="bg-accent/[0.05] border border-accent/20 p-2">
              <div className="text-lg font-bold text-accent tabular-nums">{stats.ending || endingSoon.length}</div>
              <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Ending</div>
            </div>
            <div className="bg-orange-500/[0.05] border border-orange-500/20 p-2">
              <div className="text-lg font-bold text-orange-400 tabular-nums">{hotAuctions.length}</div>
              <div className="text-[9px] font-mono text-orange-400/60 uppercase tracking-wider">Hot</div>
            </div>
          </div>
        </div>
      </header>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* MOBILE SEARCH & FILTERS */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <section className="lg:hidden px-4 py-3 border-b border-white/[0.08]">
        {/* Search */}
        <div className={clsx(
          "relative border-2 transition-all duration-200 mb-3",
          searchFocused ? "border-accent/50 bg-accent/[0.02]" : "border-white/[0.08] bg-white/[0.02]"
        )}>
          <div className="flex items-center">
            <Search className="w-4 h-4 text-white/30 ml-3" />
            <input
              type="text"
              placeholder="search domains..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => setSearchFocused(true)}
              onBlur={() => setSearchFocused(false)}
              className="flex-1 bg-transparent px-3 py-2.5 text-sm font-mono text-white placeholder:text-white/20 outline-none"
            />
            {searchQuery && (
              <button onClick={() => setSearchQuery('')} className="p-2 text-white/30">
                <X className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>

        {/* Tab Filters */}
        <div className="flex gap-2 mb-3">
          {[
            { id: 'all' as const, label: 'All', icon: Gavel },
            { id: 'ending' as const, label: 'Ending', icon: Timer },
            { id: 'hot' as const, label: 'Hot', icon: Flame },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={clsx(
                "flex-1 py-2 text-[10px] font-mono uppercase tracking-wider border transition-all flex items-center justify-center gap-1.5",
                activeTab === tab.id
                  ? "bg-accent text-black border-accent"
                  : "bg-white/[0.02] border-white/[0.08] text-white/50"
              )}
            >
              <tab.icon className="w-3 h-3" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* Platform Filter Toggle */}
        <button
          onClick={() => setShowFilters(!showFilters)}
          className="w-full py-2 flex items-center justify-between text-[10px] font-mono text-white/40 border border-white/[0.08] bg-white/[0.02] px-3"
        >
          <span>Platform: {selectedPlatform}</span>
          <ChevronDown className={clsx("w-3 h-3 transition-transform", showFilters && "rotate-180")} />
        </button>

        {showFilters && (
          <div className="mt-2 grid grid-cols-3 gap-1">
            {PLATFORMS.map((p) => (
              <button
                key={p.id}
                onClick={() => { setSelectedPlatform(p.id); setShowFilters(false) }}
                className={clsx(
                  "py-2 text-[9px] font-mono uppercase tracking-wider border transition-all",
                  selectedPlatform === p.id
                    ? "bg-white text-black border-white"
                    : "bg-white/[0.02] border-white/[0.08] text-white/50"
                )}
              >
                {p.name}
              </button>
            ))}
          </div>
        )}
      </section>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* MOBILE AUCTION LIST */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <section className="lg:hidden px-4 py-4 pb-20">
        {/* Login Banner */}
        {!isAuthenticated && (
          <div className="mb-4 p-3 bg-accent/5 border border-accent/20">
            <div className="flex items-center gap-3">
              <Lock className="w-4 h-4 text-accent shrink-0" />
              <div className="flex-1">
                <p className="text-xs font-bold text-white">Unlock Full Access</p>
                <p className="text-[10px] text-white/50">Valuations & deal scores</p>
              </div>
              <Link href="/register" className="px-3 py-1.5 bg-accent text-black text-[10px] font-bold uppercase">
                Join
              </Link>
            </div>
          </div>
        )}

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-6 h-6 text-accent animate-spin" />
          </div>
        ) : filteredAuctions.length === 0 ? (
          <div className="text-center py-20 text-white/30 font-mono text-sm">
            No assets found
          </div>
        ) : (
          <div className="space-y-2">
            {filteredAuctions.slice(0, 50).map((auction, i) => (
              auction.is_pounce ? (
                <button
                  key={`${auction.domain}-${i}`}
                  type="button"
                  onClick={() => handlePounceDirectClick(auction)}
                  className={clsx(
                    "w-full text-left block p-3 border active:bg-white/[0.03] transition-all",
                    "bg-accent/[0.03] border-accent/20"
                  )}
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="flex items-center gap-0.5 px-1 py-0.5 bg-accent/10 border border-accent/20 text-[8px] font-bold text-accent uppercase shrink-0">
                          <Diamond className="w-2.5 h-2.5" /> Direct
                        </span>
                        <span className="text-sm font-bold text-white font-mono truncate">
                          {auction.domain}
                        </span>
                      </div>
                      <div className="flex items-center gap-2 mt-1 text-[10px] font-mono text-white/30">
                        <span className="flex items-center gap-1 text-accent">
                          <ShieldCheck className="w-3 h-3" /> Verified • Instant
                        </span>
                        <span>•</span>
                        <span className="text-white/40">view deal</span>
                      </div>
                    </div>
                    <div className="text-right shrink-0">
                      <div className="text-sm font-bold text-accent font-mono">
                        {formatCurrency(auction.current_bid)}
                      </div>
                      <div className="text-[10px] text-accent/60 font-mono">Buy Now</div>
                    </div>
                  </div>
                </button>
              ) : (
              <a
                key={`${auction.domain}-${i}`}
                href={auction.affiliate_url}
                target="_blank"
                rel="noopener noreferrer"
                  className={clsx(
                    "block p-3 border active:bg-white/[0.03] transition-all",
                    "bg-[#0A0A0A] border-white/[0.08]"
                  )}
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-bold text-white font-mono truncate">
                      {auction.domain}
                      </span>
                    </div>
                    <div className="flex items-center gap-2 mt-1 text-[10px] font-mono text-white/30">
                      <span className="uppercase">{auction.platform}</span>
                      <span>•</span>
                      <span className={getTimeColor(auction.end_time)}>
                        <Clock className="w-3 h-3 inline mr-1" />
                        {calcTimeRemaining(auction.end_time)}
                      </span>
                    </div>
                  </div>
                  <div className="text-right shrink-0">
                    <div className="text-sm font-bold text-accent font-mono">
                      {formatCurrency(auction.current_bid)}
                    </div>
                    {auction.num_bids > 0 && (
                      <div className="text-[10px] text-white/30 font-mono">
                        {auction.num_bids} bids
                      </div>
                    )}
                  </div>
                </div>
              </a>
              )
            ))}
          </div>
        )}
      </section>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* DESKTOP LAYOUT */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <main className="hidden lg:block relative pt-32 pb-24 px-6">
        <div className="max-w-[1400px] mx-auto">
          {/* Hero Header */}
          <div className="mb-12 animate-fade-in">
            <div className="flex justify-between items-end gap-8 border-b border-white/[0.08] pb-10">
              <div>
                <span className="text-accent font-mono text-xs uppercase tracking-[0.2em] mb-4 block flex items-center gap-2">
                  <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                  Live Liquidity Pool
                </span>
                <h1 className="font-display text-[5rem] leading-[0.9] tracking-[-0.03em] text-white">
                  Acquire Assets.
                </h1>
                <p className="mt-6 text-lg text-white/50 max-w-2xl font-light leading-relaxed">
                  External auctions + Pounce Direct listings.
                  <span className="block mt-2 text-white/80">Pounce Direct owners are DNS-verified. External auctions are sourced from GoDaddy, Sedo, and other partners.</span>
                </p>
              </div>
              <div className="grid grid-cols-3 gap-8 text-right">
                <div>
                  <div className="text-3xl font-display text-white mb-1">{(stats.total || allAuctions.length).toLocaleString()}</div>
                  <div className="text-[10px] uppercase tracking-widest text-white/30 font-mono">Live Auctions</div>
                </div>
                <div>
                  <div className="text-3xl font-display text-accent mb-1">{(stats.ending || endingSoon.length).toLocaleString()}</div>
                  <div className="text-[10px] uppercase tracking-widest text-accent/60 font-mono">Ending 24h</div>
                </div>
                <div>
                  <div className="text-3xl font-display text-white mb-1">{(stats.direct || pounceItems.length).toLocaleString()}</div>
                  <div className="text-[10px] uppercase tracking-widest text-white/30 font-mono">Direct</div>
                </div>
              </div>
            </div>
          </div>

          {/* Login Banner */}
          {!isAuthenticated && (
            <div className="mb-10 p-1 border border-accent/20 bg-accent/5 max-w-3xl">
              <div className="bg-[#050505] p-6 flex items-center justify-between gap-6">
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 bg-accent/10 border border-accent/20 flex items-center justify-center text-accent">
                    <Lock className="w-5 h-5" />
                  </div>
                  <div>
                    <p className="text-base font-bold text-white mb-0.5">Restricted Access</p>
                    <p className="text-sm font-mono text-white/50">Sign in to unlock valuations and deal scores.</p>
                  </div>
                </div>
                <Link
                  href="/register"
                  className="shrink-0 px-6 py-3 bg-accent text-black text-xs font-bold uppercase tracking-widest hover:bg-white transition-all"
                >
                  Authorize
                </Link>
              </div>
            </div>
          )}

          {/* Search & Filters Bar */}
          <div className="mb-6 sticky top-20 z-30 backdrop-blur-xl bg-[#020202]/90 border-y border-white/[0.08] py-4 -mx-6 px-6">
            <div className="flex gap-4 justify-between items-center">
              {/* Search */}
              <div className="relative w-[400px] group">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40 group-focus-within:text-accent transition-colors" />
                <input
                  type="text"
                  placeholder="Search assets..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-12 pr-4 py-3 bg-[#0A0A0A] border border-white/10 text-white placeholder:text-white/20 font-mono text-sm focus:outline-none focus:border-accent transition-all"
                />
              </div>
              
              {/* Filters */}
              <div className="flex gap-2">
                <select
                  value={selectedPlatform}
                  onChange={(e) => setSelectedPlatform(e.target.value)}
                  className="appearance-none px-4 py-3 bg-[#0A0A0A] border border-white/10 text-white font-mono text-sm focus:outline-none focus:border-accent cursor-pointer"
                >
                  {PLATFORMS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
                
                <div className="flex border border-white/10 bg-[#0A0A0A]">
                  {[
                    { id: 'all' as const, label: 'All', icon: Gavel },
                    { id: 'ending' as const, label: 'Ending', icon: Timer },
                    { id: 'hot' as const, label: 'Hot', icon: Flame },
                  ].map((tab) => (
                    <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id)}
                      className={clsx(
                        "px-5 py-3 flex items-center gap-2 text-xs font-bold uppercase tracking-widest transition-all border-r border-white/10 last:border-r-0",
                        activeTab === tab.id
                          ? "bg-white/10 text-white border-b-2 border-accent"
                          : "text-white/40 hover:text-white border-b-2 border-transparent"
                      )}
                    >
                      <tab.icon className={clsx("w-4 h-4", activeTab === tab.id ? "text-accent" : "")} />
                      {tab.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Desktop Table */}
          <div className="border border-white/[0.08] bg-[#050505]">
            {/* Table Header */}
            <div className="grid grid-cols-[1fr_100px_120px_100px_80px] gap-4 px-6 py-4 bg-[#0A0A0A] border-b border-white/[0.08] text-[10px] font-mono text-white/40 uppercase tracking-wider">
              <div>Domain</div>
              <div className="text-center">Platform</div>
              <div className="text-right">Price</div>
              <div className="text-center">Time</div>
              <div></div>
            </div>

            {/* Table Body */}
            {loading ? (
              <div className="flex items-center justify-center py-20">
                <Loader2 className="w-6 h-6 text-accent animate-spin" />
              </div>
            ) : filteredAuctions.length === 0 ? (
              <div className="text-center py-20 text-white/30 font-mono">No assets found</div>
            ) : (
              <div>
                {filteredAuctions.map((auction, i) => (
                  auction.is_pounce ? (
                    <button
                    key={`${auction.domain}-${i}`}
                      type="button"
                      onClick={() => handlePounceDirectClick(auction)}
                      className={clsx(
                        "w-full text-left grid grid-cols-[1fr_100px_120px_100px_80px] gap-4 items-center px-6 py-4 border-b transition-all group",
                        "border-accent/20 bg-accent/[0.03] hover:bg-accent/[0.06]"
                      )}
                    >
                    <div className="flex items-center gap-3">
                      <div className="flex items-center gap-1 px-1.5 py-0.5 bg-accent/10 border border-accent/20 shrink-0">
                        <Diamond className="w-3 h-3 text-accent" />
                        <span className="text-[8px] font-bold text-accent uppercase">Direct</span>
                      </div>
                      <span className="font-mono text-base text-white group-hover:text-accent transition-colors truncate">
                      {auction.domain}
                      </span>
                    </div>
                    <div className="text-center text-xs font-mono text-white/40 uppercase">
                      <span className="flex items-center justify-center gap-1 text-accent">
                        <ShieldCheck className="w-3 h-3" /> Verified
                      </span>
                    </div>
                    <div className="text-right font-mono text-base text-accent">
                      {formatCurrency(auction.current_bid)}
                      <div className="text-[9px] text-accent/60 font-mono">Buy Now</div>
                    </div>
                    <div className={clsx("text-center text-xs font-mono", auction.is_pounce ? "text-accent" : getTimeColor(auction.end_time))}>
                      {auction.is_pounce ? 'Instant' : calcTimeRemaining(auction.end_time)}
                    </div>
                    <div className="flex justify-end">
                      <div className={clsx(
                        "w-8 h-8 border flex items-center justify-center transition-all",
                        auction.is_pounce 
                          ? "border-accent/30 text-accent group-hover:bg-accent group-hover:text-black"
                          : "border-white/10 text-white/30 group-hover:bg-white group-hover:text-black"
                      )}>
                        <ArrowUpRight className="w-4 h-4" />
                      </div>
                    </div>
                    </button>
                  ) : (
                    <a 
                      key={`${auction.domain}-${i}`}
                      href={auction.affiliate_url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className={clsx(
                        "grid grid-cols-[1fr_100px_120px_100px_80px] gap-4 items-center px-6 py-4 border-b transition-all group",
                        "border-white/[0.03] hover:bg-white/[0.02]"
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <span className="font-mono text-base text-white group-hover:text-accent transition-colors truncate">
                          {auction.domain}
                        </span>
                      </div>
                      <div className="text-center text-xs font-mono text-white/40 uppercase">{auction.platform}</div>
                      <div className="text-right font-mono text-base text-accent">
                        {formatCurrency(auction.current_bid)}
                      </div>
                      <div className={clsx("text-center text-xs font-mono", getTimeColor(auction.end_time))}>
                        {calcTimeRemaining(auction.end_time)}
                      </div>
                      <div className="flex justify-end">
                        <div className={clsx(
                          "w-8 h-8 border flex items-center justify-center transition-all",
                          "border-white/10 text-white/30 group-hover:bg-white group-hover:text-black"
                        )}>
                        <ExternalLink className="w-4 h-4" />
                      </div>
                    </div>
                  </a>
                  )
                ))}
              </div>
            )}
          </div>

          {/* Stats Footer */}
          {!loading && (
            <div className="mt-4 flex justify-between text-[10px] font-mono text-white/30 uppercase tracking-widest">
              <span>System Status: Online</span>
              <span>Assets: {filteredAuctions.length}</span>
            </div>
          )}

          {/* Bottom CTA */}
          {!isAuthenticated && (
            <div className="mt-16 p-px bg-gradient-to-r from-accent/20 via-white/5 to-accent/20">
              <div className="bg-[#080808] p-10 text-left">
                <div className="inline-flex items-center justify-center w-10 h-10 border border-accent/20 bg-accent/5 text-accent mb-4">
                  <Filter className="w-5 h-5" />
                </div>
                <h3 className="text-xl font-display text-white mb-2">Eliminate Noise.</h3>
                <p className="text-white/50 mb-6 max-w-md text-sm">
                  Our Trader plan filters 99% of junk domains automatically.
                </p>
                <Link
                  href="/pricing"
                  className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-black text-xs font-bold uppercase tracking-widest hover:bg-white transition-all"
                >
                  Upgrade <TrendingUp className="w-4 h-4" />
                </Link>
              </div>
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  )
}
