'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Sidebar } from '@/components/Sidebar'
import { Toast, useToast } from '@/components/Toast'
import { 
  ExternalLink,
  Loader2,
  Diamond,
  Zap,
  ChevronLeft,
  ChevronRight,
  TrendingUp,
  RefreshCw,
  Clock,
  Search,
  Eye,
  EyeOff,
  ShieldCheck,
  Gavel,
  Ban,
  Target,
  X,
  Menu,
  Settings,
  Shield,
  LogOut,
  Crown,
  Sparkles,
  Coins,
  Tag
} 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]
  return /[-\d]/.test(name)
}

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

export default function MarketPage() {
  const { subscription, user, logout } = useStore()
  const { toast, showToast, hideToast } = useToast()
  
  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
  const [menuOpen, setMenuOpen] = useState(false)

  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: 'newest',
        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))
    }
    
    return filtered
  }, [items, searchQuery, loading, hideSpam])

  // Mobile Nav
  const mobileNavItems = [
    { href: '/terminal/radar', 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/radar', 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/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]/80 backdrop-blur-xl border-b border-white/[0.06]" 
          style={{ paddingTop: 'env(safe-area-inset-top)' }}
        >
          <div className="px-4 py-3 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="relative">
                <div className="w-9 h-9 bg-blue-500/10 border border-blue-500/20 rounded-xl flex items-center justify-center">
                  <Gavel className="w-4 h-4 text-blue-400" />
                </div>
              </div>
              <div>
                <h1 className="text-base font-bold text-white tracking-tight leading-none">Market</h1>
                <p className="text-[10px] text-white/40 font-medium tracking-wide mt-0.5">Live Auctions</p>
              </div>
            </div>
            
            <div className="flex items-center gap-2">
              <div className="px-2.5 py-1 bg-white/[0.03] border border-white/[0.08] rounded-lg">
                <div className="text-xs font-bold text-white tabular-nums">{stats.total}</div>
              </div>
              <button
                onClick={handleRefresh}
                disabled={refreshing}
                className="w-9 h-9 flex items-center justify-center bg-white/[0.03] border border-white/[0.08] rounded-lg"
              >
                <RefreshCw className={clsx("w-4 h-4 text-white/50", refreshing && "animate-spin")} />
              </button>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* SEARCH - Mobile */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="lg:hidden px-4 pt-4 pb-2">
          <div className={clsx(
            "relative border transition-all duration-300 rounded-xl overflow-hidden",
            searchFocused 
              ? "border-blue-500/50 bg-blue-500/[0.03]" 
              : "border-white/[0.08] bg-white/[0.03]"
          )}>
            <div className="flex items-center">
              <Search className={clsx(
                "w-5 h-5 ml-4 transition-colors",
                searchFocused ? "text-blue-400" : "text-white/30"
              )} />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onFocus={() => setSearchFocused(true)}
                onBlur={() => setSearchFocused(false)}
                placeholder="Search auctions..."
                className="flex-1 bg-transparent px-3 py-3.5 text-base text-white placeholder:text-white/20 outline-none font-medium"
              />
              {searchQuery && (
                <button 
                  onClick={() => setSearchQuery('')}
                  className="p-3.5 text-white/30 active:text-white transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              )}
            </div>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* FILTERS - Mobile Horizontal Scroll */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="lg:hidden px-4 pb-4">
          <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide">
            <button
              onClick={() => setSourceFilter(s => s === 'pounce' ? 'all' : 'pounce')}
              className={clsx(
                "flex items-center gap-1.5 px-3 py-2 rounded-full text-xs font-medium whitespace-nowrap transition-all",
                sourceFilter === 'pounce' 
                  ? "bg-accent/20 text-accent border border-accent/30" 
                  : "bg-white/[0.03] text-white/50 border border-white/[0.08]"
              )}
            >
              <Diamond className="w-3 h-3" />
              Pounce
            </button>
            
            <button
              onClick={() => setHideSpam(!hideSpam)}
              className={clsx(
                "flex items-center gap-1.5 px-3 py-2 rounded-full text-xs font-medium whitespace-nowrap transition-all",
                hideSpam 
                  ? "bg-white/10 text-white border border-white/20" 
                  : "bg-white/[0.03] text-white/40 border border-white/[0.08]"
              )}
            >
              <Ban className="w-3 h-3" />
              Clean
            </button>
            
            {['com', 'ai', 'io', 'net'].map((tld) => (
              <button
                key={tld}
                onClick={() => setTldFilter(t => t === tld ? 'all' : tld)}
                className={clsx(
                  "px-3 py-2 rounded-full text-xs font-medium whitespace-nowrap transition-all",
                  tldFilter === tld 
                    ? "bg-blue-500/20 text-blue-400 border border-blue-500/30" 
                    : "bg-white/[0.03] text-white/40 border border-white/[0.08]"
                )}
              >
                .{tld}
              </button>
            ))}
            
            {[
              { value: 'low', label: '< $100' },
              { value: 'mid', label: '< $1k' },
              { value: 'high', label: '$1k+' },
            ].map((item) => (
              <button
                key={item.value}
                onClick={() => setPriceRange(p => p === item.value ? 'all' : item.value as PriceRange)}
                className={clsx(
                  "px-3 py-2 rounded-full text-xs font-medium whitespace-nowrap transition-all",
                  priceRange === item.value 
                    ? "bg-amber-500/20 text-amber-400 border border-amber-500/30" 
                    : "bg-white/[0.03] text-white/40 border border-white/[0.08]"
                )}
              >
                {item.label}
              </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="inline-flex items-center gap-2">
                <Gavel className="w-4 h-4 text-accent" />
                <span className="text-[10px] font-mono tracking-wide text-accent">Live Auctions</span>
              </div>
              
              <h1 className="font-display text-[2rem] lg:text-[2.5rem] leading-[1] tracking-[-0.02em]">
                <span className="text-white">Market</span>
                <span className="text-white/30 ml-3">{stats.total}</span>
              </h1>
            </div>
            
            <div className="flex gap-6 lg:gap-8">
              <div className="text-right">
                <div className="text-xl font-display text-accent">{stats.pounceCount}</div>
                <div className="text-[9px] tracking-wide text-white/30 font-mono">Pounce Direct</div>
              </div>
              <div className="text-right">
                <div className="text-xl font-display text-white">{stats.auctionCount}</div>
                <div className="text-[9px] tracking-wide text-white/30 font-mono">External</div>
              </div>
              <div className="text-right">
                <div className="text-xl font-display text-amber-400">{stats.highScore}</div>
                <div className="text-[9px] tracking-wide text-white/30 font-mono">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-medium transition-colors",
                sourceFilter === 'all' ? "bg-white/10 text-white" : "text-white/40 hover:text-white/60"
              )}
            >
              All
            </button>
            <button
              onClick={() => setSourceFilter('pounce')}
              className={clsx(
                "px-3 py-1.5 text-xs font-medium transition-colors flex items-center gap-1.5",
                sourceFilter === 'pounce' ? "bg-accent/20 text-accent" : "text-white/40 hover:text-white/60"
              )}
            >
              <Diamond className="w-3 h-3" />
              Pounce Only
            </button>
            
            <div className="w-px h-5 bg-white/10" />
            
            <select
              value={tldFilter}
              onChange={(e) => setTldFilter(e.target.value)}
              className="bg-transparent border border-white/10 text-white text-xs px-3 py-1.5 outline-none hover:border-white/20"
            >
              <option value="all" className="bg-black">All TLDs</option>
              <option value="com" className="bg-black">.com</option>
              <option value="ai" className="bg-black">.ai</option>
              <option value="io" className="bg-black">.io</option>
              <option value="net" className="bg-black">.net</option>
            </select>
            
            <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(p => p === item.value ? 'all' : item.value as PriceRange)}
                className={clsx(
                  "px-3 py-1.5 text-xs font-medium transition-colors",
                  priceRange === item.value ? "bg-white/10 text-white" : "text-white/40 hover:text-white/60"
                )}
              >
                {item.label}
              </button>
            ))}
            
            <div className="w-px h-5 bg-white/10" />
            
            <button
              onClick={() => setHideSpam(!hideSpam)}
              className={clsx(
                "px-3 py-1.5 text-xs font-medium transition-colors flex items-center gap-1.5",
                hideSpam ? "bg-white/10 text-white" : "text-white/40 hover:text-white/60"
              )}
            >
              <Ban className="w-3 h-3" />
              Hide spam
            </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 domains..."
                className="bg-[#050505] 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 lg:w-64"
              />
            </div>
            
            <button
              onClick={handleRefresh}
              disabled={refreshing}
              className="p-2 text-white/30 hover:text-white transition-colors"
            >
              <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
            </button>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* CONTENT */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-4 lg:py-6 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">
              <div className="w-14 h-14 mx-auto bg-white/[0.02] border border-white/10 rounded-lg flex items-center justify-center mb-4">
                <Search className="w-6 h-6 text-white/20" />
              </div>
              <p className="text-white/40 text-sm">No domains found</p>
              <p className="text-white/25 text-xs mt-1">Try adjusting your filters</p>
            </div>
          ) : (
            <>
              {/* Mobile Cards */}
              <div className="lg:hidden space-y-3">
                {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-[#0A0A0A] border rounded-xl overflow-hidden",
                        isPounce ? "border-accent/20" : "border-white/[0.06]"
                      )}
                    >
                      <div className="p-4">
                        <div className="flex items-start justify-between gap-3 mb-3">
                          <div className="flex items-center gap-3 min-w-0">
                            {isPounce ? (
                              <div className="w-10 h-10 bg-accent/10 border border-accent/20 rounded-lg flex items-center justify-center shrink-0">
                                <Diamond className="w-5 h-5 text-accent" />
                              </div>
                            ) : (
                              <div className="w-10 h-10 bg-white/[0.03] border border-white/[0.06] rounded-lg flex items-center justify-center text-[10px] font-mono text-white/40 shrink-0">
                                {item.source.substring(0, 2).toUpperCase()}
                              </div>
                            )}
                            <div className="min-w-0">
                              <div className="text-sm font-bold text-white truncate">{item.domain}</div>
                              <div className="text-[10px] text-white/40">{item.source}</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-[10px] font-medium",
                              isUrgent ? "text-orange-400" : "text-white/40"
                            )}>
                              {isPounce ? (
                                <span className="flex items-center justify-end gap-1">
                                  <Zap className="w-3 h-3" />
                                  Instant
                                </span>
                              ) : (
                                <span className="flex items-center justify-end gap-1">
                                  <Clock className="w-3 h-3" />
                                  {displayTime || 'N/A'}
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                        
                        {/* Score & Actions */}
                        <div className="flex items-center gap-3 pt-3 border-t border-white/[0.05]">
                          <span className={clsx(
                            "text-[10px] font-mono font-bold px-2 py-1 rounded-sm",
                            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"
                          )}>
                            Score {item.pounce_score}
                          </span>
                          
                          <div className="flex-1" />
                          
                          <button
                            onClick={() => handleTrack(item.domain)}
                            disabled={isTracking}
                            className={clsx(
                              "w-10 h-10 flex items-center justify-center rounded-lg border transition-all active:scale-95",
                              isTracked 
                                ? "bg-accent/10 text-accent border-accent/20" 
                                : "bg-white/[0.03] text-white/40 border-white/[0.08]"
                            )}
                          >
                            {isTracking ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : isTracked ? (
                              <Eye className="w-4 h-4" />
                            ) : (
                              <EyeOff 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 rounded-lg text-sm font-bold transition-all active:scale-95",
                              isPounce 
                                ? "bg-accent text-[#020202]" 
                                : "bg-white/10 text-white"
                            )}
                          >
                            {isPounce ? 'Buy' : 'Bid'}
                            {!isPounce && <ExternalLink className="w-4 h-4" />}
                          </a>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>

              {/* Desktop Table */}
              <div className="hidden lg:block space-y-px">
                <div className="grid grid-cols-[1fr_80px_100px_100px_120px] gap-4 px-4 py-2 text-xs text-white/40 border-b border-white/[0.06]">
                  <div>Domain</div>
                  <div className="text-center">Score</div>
                  <div className="text-right">Price</div>
                  <div className="text-center">Time</div>
                  <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(
                        "group border border-white/[0.05] hover:border-white/[0.08] transition-all",
                        isPounce ? "bg-accent/[0.02]" : "bg-white/[0.01]"
                      )}
                    >
                      <div className="grid grid-cols-[1fr_80px_100px_100px_120px] gap-4 items-center px-4 py-3">
                        <div className="flex items-center gap-3 min-w-0">
                          {isPounce ? (
                            <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center shrink-0">
                              <Diamond className="w-4 h-4 text-accent" />
                            </div>
                          ) : (
                            <div className="w-8 h-8 bg-white/5 border border-white/10 flex items-center justify-center text-[10px] font-mono text-white/40 shrink-0">
                              {item.source.substring(0, 2).toUpperCase()}
                            </div>
                          )}
                          <div className="min-w-0">
                            <div className="text-sm font-medium text-white truncate">{item.domain}</div>
                            <div className="text-[10px] text-white/30 flex items-center gap-1.5">
                              {item.source}
                              {isPounce && item.verified && (
                                <>
                                  <span className="text-white/20">·</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/20">·</span>{item.num_bids} bids</> : null}
                            </div>
                          </div>
                        </div>
                        
                        <div className="text-center">
                          <span className={clsx(
                            "text-xs font-mono font-medium 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>
                        
                        <div className="text-right">
                          <div className={clsx(
                            "font-mono text-sm font-medium",
                            isPounce ? "text-accent" : "text-white"
                          )}>
                            {formatPrice(item.price)}
                          </div>
                          <div className="text-[10px] text-white/30">
                            {item.price_type === 'bid' ? 'Bid' : 'Buy Now'}
                          </div>
                        </div>
                        
                        <div className="text-center">
                          {isPounce ? (
                            <span className="text-xs text-accent font-medium 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>
                        
                        <div className="flex items-center justify-end gap-2 opacity-50 group-hover:opacity-100 transition-opacity">
                          <button
                            onClick={() => handleTrack(item.domain)}
                            disabled={isTracking}
                            title={isTracked ? "Stop tracking" : "Start tracking"}
                            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>
                          
                          <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-semibold 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-6">
                  <div className="text-xs text-white/40 font-mono">
                    Page {page} of {totalPages}
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => handlePageChange(page - 1)}
                      disabled={page === 1}
                      className="w-10 h-10 lg:w-8 lg:h-8 flex items-center justify-center border border-white/10 rounded-lg lg:rounded-none 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-10 h-10 lg:w-8 lg:h-8 flex items-center justify-center border border-white/10 rounded-lg lg:rounded-none 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]/90 backdrop-blur-xl border-t border-white/[0.08]"
          style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
        >
          <div className="flex items-stretch h-[60px]">
            {mobileNavItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={clsx(
                  "flex-1 flex flex-col items-center justify-center gap-1 relative transition-colors active:scale-95",
                  item.active ? "text-blue-400" : "text-white/40 active:text-white/80"
                )}
              >
                {item.active && (
                  <div className="absolute top-0 left-1/2 -translate-x-1/2 w-8 h-0.5 bg-blue-400 shadow-[0_0_10px_rgba(59,130,246,0.8)]" />
                )}
                <item.icon className={clsx("w-5 h-5 transition-transform", item.active && "scale-110")} />
                <span className="text-[10px] font-medium">{item.label}</span>
              </Link>
            ))}
            
            <button
              onClick={() => setMenuOpen(true)}
              className="flex-1 flex flex-col items-center justify-center gap-1 text-white/40 active:text-white/80 active:scale-95 transition-all"
            >
              <Menu className="w-5 h-5" />
              <span className="text-[10px] font-medium">Menu</span>
            </button>
          </div>
        </nav>
        
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE DRAWER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {menuOpen && (
          <div className="lg:hidden fixed inset-0 z-[100]">
            <div 
              className="absolute inset-0 bg-black/60 backdrop-blur-sm animate-in fade-in duration-300"
              onClick={() => setMenuOpen(false)}
            />
            
            <div className="absolute top-0 right-0 bottom-0 w-[85%] max-w-[320px] bg-[#0A0A0A] border-l border-white/[0.08] shadow-2xl 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-5 border-b border-white/[0.08]">
                <div className="flex items-center gap-3">
                  <Image src="/pounce-puma.png" alt="Pounce" width={32} height={32} className="object-contain" />
                  <div>
                    <h2 className="text-sm font-bold text-white tracking-wide">POUNCE</h2>
                    <p className="text-[10px] text-white/40 font-mono tracking-widest uppercase">Terminal</p>
                  </div>
                </div>
                <button
                  onClick={() => setMenuOpen(false)}
                  className="w-10 h-10 flex items-center justify-center bg-white/5 rounded-full text-white/60 hover:text-white active:scale-95 transition-all"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
              
              <div className="flex-1 overflow-y-auto py-6 space-y-8">
                {drawerNavSections.map((section) => (
                  <div key={section.title}>
                    <div className="flex items-center gap-2 px-6 mb-3">
                      <div className="w-1 h-3 bg-accent rounded-full" />
                      <span className="text-[11px] font-bold text-white/40 uppercase tracking-[0.2em]">{section.title}</span>
                    </div>
                    <div className="space-y-1">
                      {section.items.map((item: any) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={() => setMenuOpen(false)}
                          className="flex items-center gap-4 px-6 py-3.5 text-white/70 active:text-white active:bg-white/[0.03] transition-colors border-l-2 border-transparent active:border-accent"
                        >
                          <item.icon className="w-5 h-5 text-white/40" />
                          <span className="text-sm font-medium flex-1">{item.label}</span>
                          {item.isNew && (
                            <span className="px-2 py-0.5 text-[9px] font-bold bg-accent text-[#020202] rounded-sm">
                              NEW
                            </span>
                          )}
                          <ChevronRight className="w-4 h-4 text-white/10" />
                        </Link>
                      ))}
                    </div>
                  </div>
                ))}
                
                <div className="pt-4 border-t border-white/[0.08] mx-6">
                  <Link
                    href="/terminal/settings"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center gap-3 py-3 text-white/60 active:text-white transition-colors"
                  >
                    <Settings className="w-5 h-5" />
                    <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-3 text-amber-500/80 active:text-amber-400 transition-colors"
                    >
                      <Shield className="w-5 h-5" />
                      <span className="text-sm font-medium">Admin Panel</span>
                    </Link>
                  )}
                </div>
              </div>
              
              <div className="p-5 bg-white/[0.02] border-t border-white/[0.08]">
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-10 h-10 bg-gradient-to-br from-accent/20 to-accent/5 rounded-full flex items-center justify-center border border-accent/20">
                    <TierIcon className="w-5 h-5 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={clsx(
                      "text-[10px] font-mono uppercase tracking-wider",
                      tierName === 'Tycoon' ? "text-amber-400" : 
                      tierName === 'Trader' ? "text-accent" : 
                      "text-white/40"
                    )}>
                      {tierName} Plan
                    </p>
                  </div>
                </div>
                
                {tierName === 'Scout' && (
                  <Link 
                    href="/pricing"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center justify-center gap-2 w-full py-3 bg-white text-black text-sm font-bold rounded-lg active:scale-[0.98] transition-all mb-3 shadow-lg"
                  >
                    <Sparkles className="w-4 h-4 text-accent" />
                    Upgrade Now
                  </Link>
                )}
                
                <button
                  onClick={() => { logout(); setMenuOpen(false) }}
                  className="flex items-center justify-center gap-2 w-full py-3 border border-white/10 rounded-lg text-white/50 text-xs font-bold uppercase tracking-wider hover:text-white active:bg-white/5 transition-all"
                >
                  <LogOut className="w-4 h-4" />
                  Sign out
                </button>
              </div>
            </div>
          </div>
        )}
      </main>
      
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
    </div>
  )
}
