'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 { 
  Loader2,
  TrendingUp,
  TrendingDown,
  Globe,
  DollarSign,
  AlertTriangle,
  RefreshCw,
  Search,
  ChevronDown,
  ChevronUp,
  ArrowRight,
  Lock,
  Sparkles,
  BarChart3,
  Zap,
  Minus,
  Eye,
  Gavel,
  Target,
  X,
  Menu,
  Settings,
  Shield,
  LogOut,
  Crown,
  Coins,
  Tag,
  ChevronRight,
  Filter,
  Briefcase
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

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

type UserTier = 'scout' | 'trader' | 'tycoon'
type SortField = 'tld' | 'price' | 'renewal' | 'change' | 'change3y' | 'risk' | 'popularity'
type SortDirection = 'asc' | 'desc'

interface TLDData {
  tld: string
  min_price: number
  avg_price: number
  max_price: number
  min_renewal_price: number
  avg_renewal_price: number
  price_change_7d: number
  price_change_1y: number
  price_change_3y: number
  risk_level: 'low' | 'medium' | 'high'
  risk_reason: string
  popularity_rank?: number
  type?: string
}

function getTierLevel(tier: UserTier): number {
  switch (tier) {
    case 'tycoon': return 3
    case 'trader': return 2
    case 'scout': return 1
    default: return 1
  }
}

const formatPrice = (p: number) => {
  if (typeof p !== 'number' || isNaN(p)) return '$0'
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(p)
}

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

export default function IntelPage() {
  const { subscription, user, logout, checkAuth } = useStore()
  const { toast, showToast, hideToast } = useToast()
  
  const userTier: UserTier = (subscription?.tier as UserTier) || 'scout'
  const tierLevel = getTierLevel(userTier)
  
  const canSeeRenewal = tierLevel >= 2
  const canSee3yTrend = tierLevel >= 3
  
  const [tldData, setTldData] = useState<TLDData[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [refreshing, setRefreshing] = useState(false)
  const [total, setTotal] = useState(0)
  
  const [searchQuery, setSearchQuery] = useState('')
  const [searchFocused, setSearchFocused] = useState(false)
  const [filterType, setFilterType] = useState<'all' | 'tech' | 'geo' | 'budget'>('all')
  const [filtersOpen, setFiltersOpen] = useState(false)
  
  const [sortField, setSortField] = useState<SortField>('popularity')
  const [sortDirection, setSortDirection] = useState<SortDirection>('asc')
  
  // Mobile Menu
  const [menuOpen, setMenuOpen] = useState(false)

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

  const loadData = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const allTlds: TLDData[] = []
      let totalRecords = 0
      
      for (let offset = 0; offset < 500; offset += 100) {
        const response = await api.getTldOverview(100, offset, 'popularity')
        
        if (!response || !response.tlds || response.tlds.length === 0) {
          break
        }
        
        totalRecords = response.total || 0
        
        const mapped: TLDData[] = response.tlds.map((tld: any) => ({
          tld: tld.tld || '',
          min_price: tld.min_registration_price || 0,
          avg_price: tld.avg_registration_price || 0,
          max_price: tld.max_registration_price || 0,
          min_renewal_price: tld.min_renewal_price || 0,
          avg_renewal_price: tld.avg_renewal_price || 0,
          price_change_7d: tld.price_change_7d || 0,
          price_change_1y: tld.price_change_1y || 0,
          price_change_3y: tld.price_change_3y || 0,
          risk_level: tld.risk_level || 'low',
          risk_reason: tld.risk_reason || '',
          popularity_rank: tld.popularity_rank,
          type: tld.type,
        }))
        
        allTlds.push(...mapped)
        
        if (response.tlds.length < 100) break
      }
      
      if (allTlds.length === 0) {
        setError('No TLD data available')
        setTldData([])
        setTotal(0)
        return
      }
      
      setTldData(allTlds)
      setTotal(totalRecords || allTlds.length)
    } catch (err: any) {
      console.error('Failed to load TLD data:', err)
      setError(err.message || 'Failed to load TLD data')
      setTldData([])
    } finally {
      setLoading(false)
    }
  }, [])

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

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

  const handleSort = useCallback((field: SortField) => {
    if (field === 'renewal' && !canSeeRenewal) return
    if (field === 'change3y' && !canSee3yTrend) return
    
    if (sortField === field) setSortDirection(d => d === 'asc' ? 'desc' : 'asc')
    else {
      setSortField(field)
      setSortDirection(field === 'price' || field === 'renewal' || field === 'risk' ? 'asc' : 'desc')
    }
  }, [sortField, canSeeRenewal, canSee3yTrend])

  const filteredData = useMemo(() => {
    let data = [...tldData]

    const techTlds = ['ai', 'io', 'app', 'dev', 'tech', 'cloud', 'digital', 'software', 'code', 'systems', 'network', 'data', 'cyber', 'online', 'web', 'api', 'hosting']
    if (filterType === 'tech') data = data.filter(t => techTlds.includes(t.tld) || t.tld === 'io' || t.tld === 'ai')
    if (filterType === 'geo') data = data.filter(t => t.type === 'ccTLD')
    if (filterType === 'budget') data = data.filter(t => t.min_price < 10)

    if (searchQuery) {
      data = data.filter(t => t.tld.toLowerCase().includes(searchQuery.toLowerCase()))
    }

    const mult = sortDirection === 'asc' ? 1 : -1
    data.sort((a, b) => {
      switch (sortField) {
        case 'tld': return mult * a.tld.localeCompare(b.tld)
        case 'price': return mult * ((a.min_price || 0) - (b.min_price || 0))
        case 'renewal': return mult * ((a.min_renewal_price || 0) - (b.min_renewal_price || 0))
        case 'change': return mult * ((a.price_change_1y || 0) - (b.price_change_1y || 0))
        case 'change3y': return mult * ((a.price_change_3y || 0) - (b.price_change_3y || 0))
        case 'risk': 
          const riskMap: Record<string, number> = { low: 1, medium: 2, high: 3 }
          return mult * ((riskMap[a.risk_level] || 1) - (riskMap[b.risk_level] || 1))
        case 'popularity': return mult * ((a.popularity_rank || 999) - (b.popularity_rank || 999))
        default: return 0
      }
    })

    return data
  }, [tldData, filterType, searchQuery, sortField, sortDirection])

  const stats = useMemo(() => {
    if (!tldData.length) return { lowest: 0, traps: 0, avgRenewal: 0 }
    const prices = tldData.map(t => t.min_price).filter(p => p > 0)
    const lowest = prices.length > 0 ? Math.min(...prices) : 0
    const traps = tldData.filter(t => t.risk_level === 'high').length
    const avgRenewal = tldData.length > 0 ? tldData.reduce((sum, t) => sum + (t.min_renewal_price || 0), 0) / tldData.length : 0
    return { lowest, traps, avgRenewal }
  }, [tldData])

  // Active filters count
  const activeFiltersCount = filterType !== 'all' ? 1 : 0

  // Mobile Nav
  const mobileNavItems = [
    { href: '/terminal/hunt', label: 'Radar', icon: Target, active: false },
    { href: '/terminal/market', label: 'Market', icon: Gavel, active: false },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: false },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: true },
  ]
  
  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">TLD Intel</span>
              </div>
              <div className="flex items-center gap-2 text-[10px] font-mono text-white/40">
                <span>{total} extensions</span>
                <span className="text-accent">{stats.traps} risky</span>
              </div>
            </div>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-3 gap-2">
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{total}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">TLDs</div>
              </div>
              <div className="bg-accent/[0.05] border border-accent/20 p-2">
                <div className="text-lg font-bold text-accent tabular-nums font-mono">{formatPrice(stats.lowest)}</div>
                <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Lowest</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">{stats.traps}</div>
                <div className="text-[9px] font-mono text-orange-400/60 uppercase tracking-wider">High Risk</div>
              </div>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE SEARCH & FILTERS */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="lg:hidden px-4 py-3 border-b border-white/[0.08]">
          {/* Search */}
          <div className={clsx(
            "relative border-2 transition-all duration-200 mb-3",
            searchFocused 
              ? "border-accent/50 bg-accent/[0.02]" 
              : "border-white/[0.08] bg-white/[0.02]"
          )}>
            <div className="flex items-center">
              <Search className={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 TLDs..."
                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] animate-in fade-in slide-in-from-top-2 duration-200">
              <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">Category</div>
              <div className="grid grid-cols-2 gap-2">
                {[
                  { value: 'all', label: 'All TLDs', icon: null },
                  { value: 'tech', label: 'Tech', icon: Zap },
                  { value: 'geo', label: 'National', icon: Globe },
                  { value: 'budget', label: '<$10', icon: DollarSign },
                ].map((item) => (
                  <button
                    key={item.value}
                    onClick={() => setFilterType(item.value as typeof filterType)}
                    className={clsx(
                      "py-2 text-[10px] font-bold uppercase tracking-wider border flex items-center justify-center gap-1.5 transition-all",
                      filterType === 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>
          )}
        </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">TLD Intel</span>
              </div>
              
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em]">
                <span className="text-white">TLD Intel</span>
                <span className="text-white/30 ml-3 font-mono text-[2rem]">{total}</span>
              </h1>
              <p className="text-sm text-white/40 font-mono mt-2 max-w-lg">
                Compare TLD prices, spot renewal traps, and find the best registrars.
              </p>
            </div>
            
            <div className="flex gap-8">
              <div className="text-right">
                <div className="text-2xl font-bold text-accent font-mono">{formatPrice(stats.lowest)}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Lowest Entry</div>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold text-orange-400 font-mono">{stats.traps}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">High Risk</div>
              </div>
              {canSeeRenewal && (
                <div className="text-right">
                  <div className="text-2xl font-bold text-white font-mono">{formatPrice(stats.avgRenewal)}</div>
                  <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Avg Renewal</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={() => setFilterType('all')}
              className={clsx(
                "px-3 py-1.5 text-xs font-mono transition-colors border",
                filterType === 'all' ? "bg-white/10 text-white border-white/20" : "text-white/40 border-transparent hover:text-white/60"
              )}
            >
              All TLDs
            </button>
            <button
              onClick={() => setFilterType('tech')}
              className={clsx(
                "px-3 py-1.5 text-xs font-mono transition-colors flex items-center gap-1.5 border",
                filterType === 'tech' ? "bg-accent/20 text-accent border-accent/30" : "text-white/40 border-transparent hover:text-white/60"
              )}
            >
              <Zap className="w-3 h-3" />
              Tech
            </button>
            <button
              onClick={() => setFilterType('geo')}
              className={clsx(
                "px-3 py-1.5 text-xs font-mono transition-colors flex items-center gap-1.5 border",
                filterType === 'geo' ? "bg-white/10 text-white border-white/20" : "text-white/40 border-transparent hover:text-white/60"
              )}
            >
              <Globe className="w-3 h-3" />
              National
            </button>
            <button
              onClick={() => setFilterType('budget')}
              className={clsx(
                "px-3 py-1.5 text-xs font-mono transition-colors flex items-center gap-1.5 border",
                filterType === 'budget' ? "bg-white/10 text-white border-white/20" : "text-white/40 border-transparent hover:text-white/60"
              )}
            >
              <DollarSign className="w-3 h-3" />
              {'<'}$10
            </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>
          ) : error ? (
            <div className="text-center py-16 border border-dashed border-white/[0.08]">
              <AlertTriangle className="w-8 h-8 text-rose-400 mx-auto mb-3" />
              <p className="text-rose-400 text-sm font-mono mb-2">{error}</p>
              <button onClick={handleRefresh} className="text-white/40 text-xs font-mono hover:text-white">Try again</button>
            </div>
          ) : filteredData.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 TLDs found</p>
            </div>
          ) : (
            <>
              {/* TLD List */}
              <div className="space-y-px bg-white/[0.04] border border-white/[0.08]">
                {/* Desktop Header */}
                <div className="hidden lg:grid grid-cols-[1fr_100px_100px_80px_80px_60px_40px] 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('tld')} className="flex items-center gap-1 hover:text-white/60">
                    Extension
                    {sortField === 'tld' && (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">
                    Reg
                    {sortField === 'price' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
                  </button>
                  <button 
                    onClick={() => canSeeRenewal && handleSort('renewal')} 
                    className={clsx("flex items-center gap-1 justify-end", canSeeRenewal ? "hover:text-white/60" : "opacity-50")}
                  >
                    Renewal
                    {!canSeeRenewal && <Lock className="w-3 h-3" />}
                  </button>
                  <button onClick={() => handleSort('change')} className="flex items-center gap-1 justify-center hover:text-white/60">
                    1y
                    {sortField === 'change' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
                  </button>
                  <button 
                    onClick={() => canSee3yTrend && handleSort('change3y')} 
                    className={clsx("flex items-center gap-1 justify-center", canSee3yTrend ? "hover:text-white/60" : "opacity-50")}
                  >
                    3y
                    {!canSee3yTrend && <Lock className="w-3 h-3" />}
                  </button>
                  <div className="text-center">Risk</div>
                  <div></div>
                </div>
                
                {filteredData.map((tld) => {
                  const isTrap = (tld.min_renewal_price || 0) > (tld.min_price || 1) * 1.5
                  const trend = tld.price_change_1y || 0
                  const trend3y = tld.price_change_3y || 0
                  
                  return (
                    <div key={tld.tld} className="bg-[#020202] hover:bg-white/[0.02] transition-all group">
                      {/* Mobile Row */}
                      <Link
                        href={`/terminal/intel/${tld.tld}`}
                        className="lg:hidden block p-3"
                      >
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-3">
                            <div className="w-8 h-8 bg-white/[0.02] border border-white/[0.06] flex items-center justify-center">
                              <Globe className="w-4 h-4 text-white/40" />
                            </div>
                            <span className="text-sm font-bold text-white font-mono">.{tld.tld}</span>
                          </div>
                          <div className="text-right">
                            <div className="text-sm font-bold text-accent font-mono">{formatPrice(tld.min_price)}</div>
                            <div className="text-[9px] font-mono text-white/30">register</div>
                          </div>
                        </div>
                        <div className="flex items-center justify-between text-[10px] font-mono">
                          <div className="flex items-center gap-3">
                            <span className={clsx(
                              "px-1.5 py-0.5 flex items-center gap-1",
                              trend > 5 ? "text-orange-400 bg-orange-400/10" :
                              trend < -5 ? "text-accent bg-accent/10" :
                              "text-white/40 bg-white/5"
                            )}>
                              {trend > 0 ? <TrendingUp className="w-3 h-3" /> : trend < 0 ? <TrendingDown className="w-3 h-3" /> : <Minus className="w-3 h-3" />}
                              {Math.abs(trend)}%
                            </span>
                            <div className="w-12 h-1 bg-white/10">
                              <div className={clsx(
                                "h-full",
                                tld.risk_level === 'low' ? "w-1/3 bg-accent" :
                                tld.risk_level === 'medium' ? "w-2/3 bg-amber-400" :
                                "w-full bg-red-400"
                              )} />
                            </div>
                          </div>
                          <ChevronRight className="w-4 h-4 text-white/20" />
                        </div>
                      </Link>
                      
                      {/* Desktop Row */}
                      <div className="hidden lg:grid grid-cols-[1fr_100px_100px_80px_80px_60px_40px] gap-4 items-center px-3 py-3">
                        <Link href={`/terminal/intel/${tld.tld}`} className="font-mono font-bold text-white hover:text-accent transition-colors">
                          .{tld.tld}
                        </Link>
                        <div className="text-right font-mono text-white">{formatPrice(tld.min_price)}</div>
                        <div className="text-right">
                          {canSeeRenewal ? (
                            <div className="flex items-center justify-end gap-1">
                              <span className={clsx("font-mono", isTrap ? "text-amber-400" : "text-white/50")}>
                                {formatPrice(tld.min_renewal_price)}
                              </span>
                              {isTrap && <AlertTriangle className="w-3 h-3 text-amber-400" />}
                            </div>
                          ) : (
                            <span className="text-white/20 flex items-center gap-1 justify-end text-[10px]">
                              <Lock className="w-3 h-3" />
                            </span>
                          )}
                        </div>
                        <div className="text-center">
                          <span className={clsx(
                            "inline-flex items-center gap-0.5 text-xs font-mono px-1.5 py-0.5",
                            trend > 5 ? "text-orange-400 bg-orange-400/10" :
                            trend < -5 ? "text-accent bg-accent/10" :
                            "text-white/40 bg-white/5"
                          )}>
                            {trend > 0 ? <TrendingUp className="w-3 h-3" /> : trend < 0 ? <TrendingDown className="w-3 h-3" /> : <Minus className="w-3 h-3" />}
                            {Math.abs(trend)}%
                          </span>
                        </div>
                        <div className="text-center">
                          {canSee3yTrend ? (
                            <span className={clsx(
                              "inline-flex items-center gap-0.5 text-xs font-mono px-1.5 py-0.5",
                              trend3y > 10 ? "text-orange-400 bg-orange-400/10" :
                              trend3y < -10 ? "text-accent bg-accent/10" :
                              "text-white/40 bg-white/5"
                            )}>
                              {trend3y > 0 ? <TrendingUp className="w-3 h-3" /> : trend3y < 0 ? <TrendingDown className="w-3 h-3" /> : <Minus className="w-3 h-3" />}
                              {Math.abs(trend3y)}%
                            </span>
                          ) : (
                            <span className="text-white/20">—</span>
                          )}
                        </div>
                        <div className="flex justify-center">
                          <div className="w-10 h-1 bg-white/10">
                            <div className={clsx(
                              "h-full",
                              tld.risk_level === 'low' ? "w-1/3 bg-accent" :
                              tld.risk_level === 'medium' ? "w-2/3 bg-amber-400" :
                              "w-full bg-red-400"
                            )} />
                          </div>
                        </div>
                        <Link 
                          href={`/terminal/intel/${tld.tld}`}
                          className="opacity-0 group-hover:opacity-100 flex justify-end"
                        >
                          <ArrowRight className="w-4 h-4 text-white/30 hover:text-accent" />
                        </Link>
                      </div>
                    </div>
                  )
                })}
              </div>
              
              {/* Upgrade CTA */}
              {userTier === 'scout' && (
                <div className="mt-6 p-6 border border-white/[0.08] bg-white/[0.02] text-center">
                  <Sparkles className="w-6 h-6 text-accent mx-auto mb-3" />
                  <h3 className="text-sm font-bold text-white mb-1">Unlock Full Intel</h3>
                  <p className="text-xs font-mono text-white/40 mb-4">
                    See renewal prices, traps & 3-year trends
                  </p>
                  <Link
                    href="/pricing"
                    className="inline-flex items-center gap-2 px-4 py-2 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white transition-colors"
                  >
                    <Sparkles className="w-3 h-3" />
                    Upgrade
                  </Link>
                </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>
  )
}
