'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { Sidebar } from '@/components/Sidebar'
import { Toast, useToast } from '@/components/Toast'
import { 
  ExternalLink,
  Loader2,
  Diamond,
  Zap,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  ChevronDown,
  TrendingUp,
  RefreshCw,
  Clock,
  Search,
  Eye,
  EyeOff,
  ShieldCheck,
  Gavel,
  Ban,
  Target,
  X,
  Menu,
  Settings,
  Shield,
  LogOut,
  Crown,
  Sparkles,
  Coins,
  Tag,
  Filter,
  Briefcase
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

// ============================================================================
// 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]
  // Spam = contains hyphens OR is mostly numbers OR very long with numbers
  if (name.includes('-')) return true
  if (name.length > 4 && /\d/.test(name)) return true  // Short names with numbers are OK (e.g., "4chan")
  if (/^\d+$/.test(name)) return true  // Pure number domains
  return false
}

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

export default function MarketPage() {
  const { subscription, user, logout, checkAuth } = useStore()
  const { toast, showToast, hideToast } = useToast()
  const openAnalyze = useAnalyzePanelStore((s) => s.open)
  
  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)
  
  // Pagination
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const ITEMS_PER_PAGE = 50
  
  // Mobile Menu & Filters
  const [menuOpen, setMenuOpen] = useState(false)
  const [filtersOpen, setFiltersOpen] = useState(false)
  
  // Sorting
  const [sortField, setSortField] = useState<'domain' | 'score' | 'price' | 'time'>('time')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')

  // Check auth on mount
  useEffect(() => {
    checkAuth()
  }, [checkAuth])

  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',  // Sort by end time (ending soonest first) - same as Acquire page
        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 => 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])

  // Load user's tracked domains on mount
  useEffect(() => {
    const loadTrackedDomains = async () => {
      try {
        const result = await api.getDomains(1, 100)
        const domainSet = new Set(result.domains.map(d => 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 => d.name === domain)
        if (domainToDelete) {
          await api.deleteDomain(domainToDelete.id)
          setTrackedDomains(prev => {
            const next = new Set(Array.from(prev))
            next.delete(domain)
            return next
          })
          showToast(`Removed: ${domain}`, 'success')
        }
      } else {
        await api.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])

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

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

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

  return (
    <div className="min-h-screen bg-[#020202]">
      {/* Desktop Sidebar */}
      <div className="hidden lg:block">
        <Sidebar />
      </div>
      
      {/* Main Content */}
      <main className="lg:pl-[240px]">
        
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <header 
          className="lg:hidden sticky top-0 z-40 bg-[#020202]/95 backdrop-blur-md border-b border-white/[0.08]" 
          style={{ paddingTop: 'env(safe-area-inset-top)' }}
        >
          <div className="px-4 py-3">
            {/* Top 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">Live Market</span>
                {hideSpam && <span className="text-[9px] font-mono text-accent/60 bg-accent/10 px-1 py-0.5">CLEAN</span>}
              </div>
              <div className="flex items-center gap-2 text-[10px] font-mono text-white/40">
                <span>{filteredItems.length} shown</span>
                {hideSpam && filteredItems.length !== stats.total && <span className="text-white/20">/ {stats.total}</span>}
              </div>
            </div>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-4 gap-2">
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{filteredItems.length}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Shown</div>
              </div>
              <div className="bg-accent/[0.05] border border-accent/20 p-2">
                <div className="text-lg font-bold text-accent tabular-nums">{filteredItems.filter(i => i.is_pounce).length}</div>
                <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Pounce</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{filteredItems.filter(i => !i.is_pounce).length}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">External</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">{filteredItems.filter(i => i.pounce_score >= 80).length}</div>
                <div className="text-[9px] font-mono text-orange-400/60 uppercase tracking-wider">Score 80+</div>
              </div>
            </div>
          </div>
        </header>
        
        {/* Pull to Refresh Indicator */}
        {refreshing && (
          <div className="lg:hidden flex items-center justify-center py-3 bg-accent/5 border-b border-accent/10">
            <Loader2 className="w-4 h-4 text-accent animate-spin mr-2" />
            <span className="text-[10px] font-mono text-accent uppercase tracking-wider">Refreshing...</span>
          </div>
        )}

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* 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={clsx(
                "w-4 h-4 ml-3 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 domains..."
                className="flex-1 bg-transparent px-3 py-3 text-sm text-white placeholder:text-white/20 outline-none font-mono"
              />
              {searchQuery && (
                <button 
                  onClick={() => setSearchQuery('')}
                  className="p-3 text-white/30 active:text-white transition-colors"
                >
                  <X className="w-4 h-4" />
                </button>
              )}
            </div>
          </div>
          
          {/* Filter Toggle */}
          <button
            onClick={() => setFiltersOpen(!filtersOpen)}
            className={clsx(
              "flex items-center justify-between w-full py-2 px-3 border transition-colors",
              filtersOpen ? "border-accent/30 bg-accent/[0.05]" : "border-white/[0.08] bg-white/[0.02]"
            )}
          >
            <div className="flex items-center gap-2">
              <Filter className="w-4 h-4 text-white/40" />
              <span className="text-xs font-mono text-white/60">Filters</span>
              {activeFiltersCount > 0 && (
                <span className="px-1.5 py-0.5 text-[9px] font-bold bg-accent text-black">{activeFiltersCount}</span>
              )}
            </div>
            <ChevronRight className={clsx("w-4 h-4 text-white/30 transition-transform", filtersOpen && "rotate-90")} />
          </button>
          
          {/* Filters Panel */}
          {filtersOpen && (
            <div className="mt-3 p-3 border border-white/[0.08] bg-white/[0.02] space-y-3 animate-in fade-in slide-in-from-top-2 duration-200">
              {/* Source */}
              <div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">Source</div>
                <div className="flex gap-2">
                  {[
                    { value: 'all', label: 'All' },
                    { value: 'pounce', label: 'Pounce', icon: Diamond },
                    { value: 'external', label: 'External' },
                  ].map((item) => (
                    <button
                      key={item.value}
                      onClick={() => setSourceFilter(item.value as SourceFilter)}
                      className={clsx(
                        "flex-1 py-2 text-[10px] font-bold uppercase tracking-wider border transition-colors flex items-center justify-center gap-1",
                        sourceFilter === item.value 
                          ? "border-accent bg-accent/10 text-accent" 
                          : "border-white/[0.08] text-white/40"
                      )}
                    >
                      {item.icon && <item.icon className="w-3 h-3" />}
                      {item.label}
                    </button>
                  ))}
                </div>
              </div>
              
              {/* TLD */}
              <div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">TLD</div>
                <div className="flex gap-2 flex-wrap">
                  {['all', 'com', 'ai', 'io', 'net'].map((tld) => (
                    <button
                      key={tld}
                      onClick={() => setTldFilter(tld)}
                      className={clsx(
                        "px-3 py-1.5 text-[10px] font-mono uppercase border transition-colors",
                        tldFilter === tld 
                          ? "border-accent bg-accent/10 text-accent" 
                          : "border-white/[0.08] text-white/40"
                      )}
                    >
                      {tld === 'all' ? 'All' : `.${tld}`}
                    </button>
                  ))}
                </div>
              </div>
              
              {/* Price */}
              <div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">Price</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-1.5 text-[10px] font-mono border transition-colors",
                        priceRange === item.value 
                          ? "border-amber-400 bg-amber-400/10 text-amber-400" 
                          : "border-white/[0.08] text-white/40"
                      )}
                    >
                      {item.label}
                    </button>
                  ))}
                </div>
              </div>
              
              {/* Spam Filter */}
              <button
                onClick={() => setHideSpam(!hideSpam)}
                className={clsx(
                  "flex items-center justify-between w-full py-2 px-3 border transition-colors",
                  hideSpam ? "border-white/20 bg-white/[0.05]" : "border-white/[0.08]"
                )}
              >
                <div className="flex items-center gap-2">
                  <Ban className="w-4 h-4 text-white/40" />
                  <span className="text-xs font-mono text-white/60">Hide spam domains</span>
                </div>
                <div className={clsx(
                  "w-4 h-4 border flex items-center justify-center",
                  hideSpam ? "border-accent bg-accent" : "border-white/30"
                )}>
                  {hideSpam && <span className="text-black text-[10px] font-bold">✓</span>}
                </div>
              </button>
            </div>
          )}
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DESKTOP HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="hidden lg:block px-10 pt-10 pb-6">
          <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6">
            <div className="space-y-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">Market Feed</span>
                {hideSpam && <span className="text-[9px] font-mono text-accent/60 bg-accent/10 px-1.5 py-0.5">CLEAN</span>}
              </div>
              
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em]">
                <span className="text-white">Market</span>
                <span className="text-white/30 ml-3 font-mono text-[2rem]">
                  {filteredItems.length}
                  {hideSpam && filteredItems.length !== stats.total && (
                    <span className="text-white/15 text-lg">/{stats.total}</span>
                  )}
                </span>
              </h1>
              <p className="text-sm text-white/40 font-mono mt-2 max-w-lg">
                Browse live auctions from all major platforms. Filter, sort, and track opportunities.
              </p>
            </div>
            
            <div className="flex gap-8">
              <div className="text-right">
                <div className="text-2xl font-bold text-accent font-mono">{filteredItems.filter(i => i.is_pounce).length}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Pounce Direct</div>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold text-white font-mono">{filteredItems.filter(i => !i.is_pounce).length}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">External</div>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold text-amber-400 font-mono">{filteredItems.filter(i => i.pounce_score >= 80).length}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Score 80+</div>
              </div>
            </div>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DESKTOP FILTERS */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="hidden lg:block px-10 pb-6 border-b border-white/[0.08]">
          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={() => setSourceFilter('all')}
              className={clsx(
                "px-3 py-1.5 text-xs font-mono transition-colors border",
                sourceFilter === 'all' ? "bg-white/10 text-white border-white/20" : "text-white/40 border-transparent hover:text-white/60"
              )}
            >
              All
            </button>
            <button
              onClick={() => setSourceFilter('pounce')}
              className={clsx(
                "px-3 py-1.5 text-xs font-mono transition-colors flex items-center gap-1.5 border",
                sourceFilter === 'pounce' ? "bg-accent/20 text-accent border-accent/30" : "text-white/40 border-transparent hover:text-white/60"
              )}
            >
              <Diamond className="w-3 h-3" />
              Pounce
            </button>
            
            <div className="w-px h-5 bg-white/10" />
            
            {['com', 'ai', 'io', 'net'].map((tld) => (
              <button
                key={tld}
                onClick={() => setTldFilter(tldFilter === tld ? 'all' : tld)}
                className={clsx(
                  "px-3 py-1.5 text-xs font-mono transition-colors border",
                  tldFilter === tld 
                    ? "bg-accent/20 text-accent border-accent/30" 
                    : "text-white/40 border-transparent hover:text-white/60"
                )}
              >
                .{tld}
              </button>
            ))}
            
            <div className="w-px h-5 bg-white/10" />
            
            {[
              { value: 'low', label: '< $100' },
              { value: 'mid', label: '< $1k' },
              { value: 'high', label: '$1k+' },
            ].map((item) => (
              <button
                key={item.value}
                onClick={() => setPriceRange(priceRange === item.value ? 'all' : item.value as PriceRange)}
                className={clsx(
                  "px-3 py-1.5 text-xs font-mono transition-colors border",
                  priceRange === item.value ? "bg-amber-400/20 text-amber-400 border-amber-400/30" : "text-white/40 border-transparent hover:text-white/60"
                )}
              >
                {item.label}
              </button>
            ))}
            
            <div className="w-px h-5 bg-white/10" />
            
            <button
              onClick={() => setHideSpam(!hideSpam)}
              title={hideSpam ? "Showing clean domains only - click to show all" : "Showing all domains - click to hide spam"}
              className={clsx(
                "px-3 py-1.5 text-xs font-mono transition-colors flex items-center gap-1.5 border",
                hideSpam ? "bg-accent/20 text-accent border-accent/30" : "text-white/40 border-transparent hover:text-white/60"
              )}
            >
              <Ban className="w-3 h-3" />
              {hideSpam ? 'Clean' : 'All'}
            </button>
            
            <div className="flex-1" />
            
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search..."
                className="bg-white/[0.02] border border-white/10 pl-9 pr-4 py-2 text-sm text-white placeholder:text-white/25 outline-none focus:border-accent/40 w-48 font-mono"
              />
            </div>
            
            <button
              onClick={handleRefresh}
              disabled={refreshing}
              className="p-2 text-white/30 hover:text-white transition-colors border border-white/10"
            >
              <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
            </button>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* CONTENT */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-4 pb-28 lg:pb-10">
          {loading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="w-6 h-6 text-accent animate-spin" />
            </div>
          ) : filteredItems.length === 0 ? (
            <div className="text-center py-16 border border-dashed border-white/[0.08]">
              <Search className="w-8 h-8 text-white/10 mx-auto mb-3" />
              <p className="text-white/40 text-sm font-mono">No domains found</p>
              <p className="text-white/25 text-xs font-mono mt-1">Try adjusting filters</p>
            </div>
          ) : (
            <>
              {/* Results List */}
              <div className="space-y-px bg-white/[0.04] border border-white/[0.08]">
                {/* Desktop Table Header */}
                <div className="hidden lg:grid grid-cols-[1fr_80px_100px_80px_120px] gap-4 px-3 py-2 text-[10px] font-mono text-white/40 uppercase tracking-wider border-b border-white/[0.08]">
                  <button onClick={() => handleSort('domain')} className="flex items-center gap-1 hover:text-white/60 text-left">
                    Domain
                    {sortField === 'domain' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
                  </button>
                  <button onClick={() => handleSort('score')} className="flex items-center gap-1 justify-center hover:text-white/60">
                    Score
                    {sortField === 'score' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
                  </button>
                  <button onClick={() => handleSort('price')} className="flex items-center gap-1 justify-end hover:text-white/60">
                    Price
                    {sortField === 'price' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
                  </button>
                  <button onClick={() => handleSort('time')} className="flex items-center gap-1 justify-center hover:text-white/60">
                    Time
                    {sortField === 'time' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
                  </button>
                  <div className="text-right">Actions</div>
                </div>
                
                {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(
                        "bg-[#020202] hover:bg-white/[0.02] transition-all",
                        isPounce && "bg-accent/[0.02]"
                      )}
                    >
                      {/* Mobile Row */}
                      <div className="lg:hidden p-3">
                        <div className="flex items-start justify-between gap-3 mb-2">
                          <div className="flex items-center gap-3 min-w-0 flex-1">
                            <div className={clsx(
                              "w-8 h-8 flex items-center justify-center border shrink-0",
                              isPounce ? "bg-accent/10 border-accent/20" : "bg-white/[0.02] border-white/[0.06]"
                            )}>
                              {isPounce ? (
                                <Diamond className="w-4 h-4 text-accent" />
                              ) : (
                                <span className="text-[9px] font-mono text-white/40">{item.source.substring(0, 2).toUpperCase()}</span>
                              )}
                            </div>
                            <div className="min-w-0 flex-1">
                              <button
                                onClick={() => openAnalyze(item.domain)}
                                className="text-sm font-bold text-white font-mono truncate text-left"
                                title="Analyze"
                              >
                                {item.domain}
                              </button>
                              <div className="flex items-center gap-2 text-[10px] font-mono text-white/30">
                                <span className="uppercase">{item.source}</span>
                                <span className="text-white/10">|</span>
                                <span className={clsx(isUrgent && "text-orange-400")}>
                                  {isPounce ? 'Instant' : displayTime || 'N/A'}
                                </span>
                              </div>
                            </div>
                          </div>
                          
                          <div className="text-right shrink-0">
                            <div className={clsx(
                              "text-base font-bold font-mono",
                              isPounce ? "text-accent" : "text-white"
                            )}>
                              {formatPrice(item.price)}
                            </div>
                            <div className={clsx(
                              "text-[9px] font-mono px-1 py-0.5 inline-block",
                              item.pounce_score >= 80 ? "text-accent bg-accent/10" :
                              item.pounce_score >= 50 ? "text-amber-400 bg-amber-400/10" :
                              "text-white/30 bg-white/5"
                            )}>
                              Score {item.pounce_score}
                            </div>
                          </div>
                        </div>
                        
                        {/* Actions */}
                        <div className="flex gap-2">
                          <button
                            onClick={() => handleTrack(item.domain)}
                            disabled={isTracking}
                            className={clsx(
                              "flex-1 py-2 text-[10px] font-bold uppercase tracking-wider border flex items-center justify-center gap-1.5 transition-all",
                              isTracked 
                                ? "border-accent bg-accent/10 text-accent" 
                                : "border-white/[0.08] text-white/40"
                            )}
                          >
                            {isTracking ? (
                              <Loader2 className="w-3 h-3 animate-spin" />
                            ) : isTracked ? (
                              <Eye className="w-3 h-3" />
                            ) : (
                              <EyeOff className="w-3 h-3" />
                            )}
                            {isTracked ? 'Tracked' : 'Track'}
                          </button>
                          
                          <button
                            onClick={() => openAnalyze(item.domain)}
                            className="w-10 py-2 text-[10px] font-bold uppercase tracking-wider border border-white/[0.08] text-white/50 flex items-center justify-center transition-all hover:text-white hover:bg-white/5"
                            title="Analyze"
                          >
                            <Shield className="w-3.5 h-3.5" />
                          </button>

                          <a
                            href={item.url}
                            target={isPounce ? "_self" : "_blank"}
                            rel={isPounce ? undefined : "noopener noreferrer"}
                            className={clsx(
                              "flex-1 py-2 text-[10px] font-bold uppercase tracking-wider flex items-center justify-center gap-1.5 transition-all",
                              isPounce 
                                ? "bg-accent text-black" 
                                : "bg-white/10 text-white"
                            )}
                          >
                            {isPounce ? 'Buy' : 'Bid'}
                            {!isPounce && <ExternalLink className="w-3 h-3" />}
                          </a>
                        </div>
                      </div>
                      
                      {/* Desktop Row */}
                      <div className="hidden lg:grid grid-cols-[1fr_80px_100px_80px_120px] gap-4 items-center p-3 group">
                        <div className="flex items-center gap-3 min-w-0 flex-1">
                          <div className={clsx(
                            "w-8 h-8 flex items-center justify-center border shrink-0",
                            isPounce ? "bg-accent/10 border-accent/20" : "bg-white/[0.02] border-white/[0.06]"
                          )}>
                            {isPounce ? (
                              <Diamond className="w-4 h-4 text-accent" />
                            ) : (
                              <span className="text-[9px] font-mono text-white/40">{item.source.substring(0, 2).toUpperCase()}</span>
                            )}
                          </div>
                          <div className="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"
                              title="Analyze"
                            >
                              {item.domain}
                            </button>
                            <div className="flex items-center gap-2 text-[10px] font-mono text-white/30">
                              <span className="uppercase">{item.source}</span>
                              {isPounce && item.verified && (
                                <>
                                  <span className="text-white/10">|</span>
                                  <span className="text-accent flex items-center gap-0.5">
                                    <ShieldCheck className="w-3 h-3" />
                                    Verified
                                  </span>
                                </>
                              )}
                              {item.num_bids ? <><span className="text-white/10">|</span>{item.num_bids} bids</> : null}
                            </div>
                          </div>
                        </div>
                        
                        {/* Score */}
                        <div className="w-16 text-center shrink-0">
                          <span className={clsx(
                            "text-xs font-mono font-bold px-2 py-0.5",
                            item.pounce_score >= 80 ? "text-accent bg-accent/10" :
                            item.pounce_score >= 50 ? "text-amber-400 bg-amber-400/10" :
                            "text-white/40 bg-white/5"
                          )}>
                            {item.pounce_score}
                          </span>
                        </div>
                        
                        {/* Price */}
                        <div className="w-24 text-right shrink-0">
                          <div className={clsx(
                            "font-mono text-sm font-bold",
                            isPounce ? "text-accent" : "text-white"
                          )}>
                            {formatPrice(item.price)}
                          </div>
                          <div className="text-[9px] font-mono text-white/30 uppercase">
                            {item.price_type === 'bid' ? 'Bid' : 'Buy Now'}
                          </div>
                        </div>
                        
                        {/* Time */}
                        <div className="w-20 text-center shrink-0">
                          {isPounce ? (
                            <span className="text-xs text-accent font-mono flex items-center justify-center gap-1">
                              <Zap className="w-3 h-3" />
                              Instant
                            </span>
                          ) : (
                            <span className={clsx(
                              "text-xs font-mono",
                              isUrgent ? "text-orange-400" : "text-white/50"
                            )}>
                              {displayTime || 'N/A'}
                            </span>
                          )}
                        </div>
                        
                        {/* Actions */}
                        <div className="flex items-center gap-2 shrink-0 opacity-50 group-hover:opacity-100 transition-opacity">
                          <button
                            onClick={() => handleTrack(item.domain)}
                            disabled={isTracking}
                            className={clsx(
                              "w-7 h-7 flex items-center justify-center border transition-colors",
                              isTracked 
                                ? "bg-accent/10 text-accent border-accent/20 hover:bg-red-500/10 hover:text-red-400 hover:border-red-500/20" 
                                : "text-white/30 border-white/10 hover:text-accent hover:bg-accent/10 hover:border-accent/20"
                            )}
                          >
                            {isTracking ? (
                              <Loader2 className="w-3.5 h-3.5 animate-spin" />
                            ) : isTracked ? (
                              <Eye className="w-3.5 h-3.5" />
                            ) : (
                              <EyeOff className="w-3.5 h-3.5" />
                            )}
                          </button>

                          <button
                            onClick={() => openAnalyze(item.domain)}
                            className="w-7 h-7 flex items-center justify-center border transition-colors text-white/30 border-white/10 hover:text-accent hover:bg-accent/10 hover:border-accent/20"
                            title="Analyze"
                          >
                            <Shield className="w-3.5 h-3.5" />
                          </button>
                          
                          <a
                            href={item.url}
                            target={isPounce ? "_self" : "_blank"}
                            rel={isPounce ? undefined : "noopener noreferrer"}
                            className={clsx(
                              "h-7 px-3 flex items-center gap-1.5 text-xs font-bold transition-colors",
                              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 h-3" />}
                          </a>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-between pt-4">
                  <div className="text-[10px] text-white/40 font-mono uppercase tracking-wider">
                    Page {page}/{totalPages} · {filteredItems.length} domains{hideSpam && filteredItems.length !== items.length && ` (${items.length} before filter)`}
                  </div>
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => handlePageChange(page - 1)}
                      disabled={page === 1}
                      className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                    >
                      <ChevronLeft className="w-4 h-4" />
                    </button>
                    
                    <div className="hidden lg:flex items-center gap-1">
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum: number
                        if (totalPages <= 5) {
                          pageNum = i + 1
                        } else if (page <= 3) {
                          pageNum = i + 1
                        } else if (page >= totalPages - 2) {
                          pageNum = totalPages - 4 + i
                        } else {
                          pageNum = page - 2 + i
                        }
                        
                        return (
                          <button
                            key={pageNum}
                            onClick={() => handlePageChange(pageNum)}
                            className={clsx(
                              "w-8 h-8 flex items-center justify-center text-xs font-mono border transition-colors",
                              page === pageNum
                                ? "bg-accent text-black border-accent"
                                : "border-white/10 text-white/50 hover:text-white hover:bg-white/5"
                            )}
                          >
                            {pageNum}
                          </button>
                        )
                      })}
                    </div>
                    
                    <span className="lg:hidden text-xs text-white/50 font-mono px-2">
                      {page}/{totalPages}
                    </span>
                    
                    <button
                      onClick={() => handlePageChange(page + 1)}
                      disabled={page === totalPages}
                      className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                    >
                      <ChevronRight className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              )}
            </>
          )}
        </section>

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