'use client'

import { useEffect, useState, useCallback, useRef } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Sidebar } from '@/components/Sidebar'
import { Toast, useToast } from '@/components/Toast'
import {
  Eye,
  Gavel,
  ArrowRight,
  CheckCircle2,
  XCircle,
  Loader2,
  Crosshair,
  Zap,
  Globe,
  Target,
  Search,
  X,
  TrendingUp,
  Settings,
  Clock,
  Wifi,
  ChevronRight,
  Sparkles,
  Radio,
  Activity,
  Menu,
  Tag,
  Coins,
  Shield,
  LogOut,
  Crown,
  ChevronDown
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

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

interface HotAuction {
  domain: string
  current_bid: number
  time_remaining: string
  platform: string
  affiliate_url?: string
}

interface SearchResult {
  domain: string
  status: string
  is_available: boolean | null
  registrar: string | null
  expiration_date: string | null
  loading: boolean
  inAuction: boolean
  auctionData?: HotAuction
}

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

export default function RadarPage() {
  const { isAuthenticated, domains, addDomain, user, subscription, logout } = useStore()
  const { toast, showToast, hideToast } = useToast()
  
  const [hotAuctions, setHotAuctions] = useState<HotAuction[]>([])
  const [marketStats, setMarketStats] = useState({ totalAuctions: 0, endingSoon: 0 })
  const [loadingData, setLoadingData] = useState(true)
  
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResult, setSearchResult] = useState<SearchResult | null>(null)
  const [addingToWatchlist, setAddingToWatchlist] = useState(false)
  const [searchFocused, setSearchFocused] = useState(false)
  const searchInputRef = useRef<HTMLInputElement>(null)
  
  // Mobile Menu State
  const [menuOpen, setMenuOpen] = useState(false)

  // Load Data
  const loadDashboardData = useCallback(async () => {
    try {
      const summary = await api.getDashboardSummary()
      setHotAuctions((summary.market.ending_soon_preview || []).slice(0, 6))
      setMarketStats({
        totalAuctions: summary.market.total_auctions || 0,
        endingSoon: summary.market.ending_soon || 0,
      })
    } catch (error) {
      console.error('Failed to load data:', error)
    } finally {
      setLoadingData(false)
    }
  }, [])

  useEffect(() => {
    if (isAuthenticated) loadDashboardData()
    else setLoadingData(false)
  }, [isAuthenticated, loadDashboardData])

  // Search
  const handleSearch = useCallback(async (domainInput: string) => {
    if (!domainInput.trim()) { setSearchResult(null); return }
    const cleanDomain = domainInput.trim().toLowerCase()
    setSearchResult({ domain: cleanDomain, status: 'checking', is_available: null, registrar: null, expiration_date: null, loading: true, inAuction: false })
    
    try {
      const [whoisResult, auctionsResult] = await Promise.all([
        api.checkDomain(cleanDomain).catch(() => null),
        api.getAuctions(cleanDomain).catch(() => ({ auctions: [] })),
      ])
      const auctionMatch = (auctionsResult as any).auctions?.find((a: any) => a.domain.toLowerCase() === cleanDomain)
      setSearchResult({
        domain: whoisResult?.domain || cleanDomain,
        status: whoisResult?.status || 'unknown',
        is_available: whoisResult?.is_available ?? null,
        registrar: whoisResult?.registrar || null,
        expiration_date: whoisResult?.expiration_date || null,
        loading: false,
        inAuction: !!auctionMatch,
        auctionData: auctionMatch,
      })
    } catch {
      setSearchResult({ domain: cleanDomain, status: 'error', is_available: null, registrar: null, expiration_date: null, loading: false, inAuction: false })
    }
  }, [])

  const handleAddToWatchlist = useCallback(async () => {
    if (!searchQuery.trim()) return
    setAddingToWatchlist(true)
    try {
      await addDomain(searchQuery.trim())
      showToast(`Added: ${searchQuery.trim()}`, 'success')
      setSearchQuery('')
      setSearchResult(null)
    } catch (err: any) {
      showToast(err.message || 'Failed', 'error')
    } finally {
      setAddingToWatchlist(false)
    }
  }, [searchQuery, addDomain, showToast])

  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchQuery.length > 3) handleSearch(searchQuery)
      else setSearchResult(null)
    }, 500)
    return () => clearTimeout(timer)
  }, [searchQuery, handleSearch])

  // Computed
  const availableDomains = domains?.filter(d => d.is_available) || []
  const totalDomains = domains?.length || 0

  // Nav Items for Mobile Bottom Bar
  const mobileNavItems = [
    { href: '/terminal/radar', label: 'Radar', icon: Target, active: true },
    { 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: false },
  ]
  
  // Full Navigation for Drawer
  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 - Premium App Style */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <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">
            {/* Brand */}
            <div className="flex items-center gap-3">
              <div className="relative">
                <div className="w-9 h-9 bg-accent/10 border border-accent/20 rounded-xl flex items-center justify-center shadow-[0_0_15px_-3px_rgba(16,185,129,0.3)]">
                  <Radio className="w-4 h-4 text-accent" />
                </div>
                <div className="absolute -top-0.5 -right-0.5 w-2 h-2 bg-accent rounded-full animate-pulse shadow-[0_0_8px_rgba(16,185,129,0.8)]" />
              </div>
              <div>
                <h1 className="text-base font-bold text-white tracking-tight leading-none">Radar</h1>
                <p className="text-[10px] text-white/40 font-medium tracking-wide mt-0.5">Live Intelligence</p>
              </div>
            </div>
            
            {/* Stats Pills - Compact */}
            <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="flex items-center gap-1.5">
                  <Target className="w-3 h-3 text-white/40" />
                  <span className="text-xs font-bold text-white tabular-nums">{totalDomains}</span>
                </div>
              </div>
              <div className="px-2.5 py-1 bg-accent/10 border border-accent/20 rounded-lg">
                <div className="flex items-center gap-1.5">
                  <CheckCircle2 className="w-3 h-3 text-accent" />
                  <span className="text-xs font-bold text-accent tabular-nums">{availableDomains.length}</span>
                </div>
              </div>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* SEARCH SECTION */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 pt-4 lg:pt-10 pb-6">
          {/* Desktop Hero Text */}
          <div className="hidden lg:block mb-8">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse" />
              <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Intelligence Hub</span>
            </div>
            <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em] text-white mb-2">
              Domain Radar
            </h1>
            <p className="text-white/40 text-sm max-w-md">
              Real-time monitoring across {marketStats.totalAuctions.toLocaleString()}+ auctions
            </p>
          </div>
          
          {/* Search Card */}
          <div className="relative">
            {/* Desktop Glow */}
            <div className="hidden lg:block absolute -inset-6 bg-gradient-to-tr from-accent/5 via-transparent to-accent/5 blur-3xl opacity-50 pointer-events-none" />
            
            <div className="relative bg-transparent lg:bg-[#0A0A0A] lg:border border-white/[0.08] overflow-hidden lg:rounded-none rounded-2xl">
              {/* Terminal Header - Desktop only */}
              <div className="hidden lg:flex items-center justify-between px-5 py-3 border-b border-white/[0.06] bg-black/40">
                <span className="text-[10px] font-mono text-white/40 flex items-center gap-2">
                  <Crosshair className="w-3 h-3 text-accent" />
                  Domain Search
                </span>
                <div className="flex gap-1.5">
                  <div className="w-2 h-2 rounded-full bg-white/10" />
                  <div className="w-2 h-2 rounded-full bg-white/10" />
                  <div className="w-2 h-2 rounded-full bg-accent/50" />
                </div>
              </div>
              
              {/* Search Input - App Style */}
              <div className="lg:p-6">
                <div className={clsx(
                  "relative border transition-all duration-300 rounded-xl lg:rounded-none overflow-hidden",
                  searchFocused 
                    ? "border-accent/50 bg-accent/[0.03] shadow-[0_0_20px_-5px_rgba(16,185,129,0.15)]" 
                    : "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-accent" : "text-white/30"
                    )} />
                    <input
                      ref={searchInputRef}
                      type="text"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      onFocus={() => setSearchFocused(true)}
                      onBlur={() => setSearchFocused(false)}
                      placeholder="Search domain..."
                      className="flex-1 bg-transparent px-3 py-4 text-base lg:text-lg text-white placeholder:text-white/20 outline-none font-medium"
                    />
                    {searchQuery && (
                      <button 
                        onClick={() => { setSearchQuery(''); setSearchResult(null) }}
                        className="p-4 text-white/30 hover:text-white active:text-white transition-colors"
                      >
                        <X className="w-5 h-5" />
                      </button>
                    )}
                  </div>
                </div>
                
                {/* Search Result */}
                {searchResult && (
                  <div className="mt-3 animate-in fade-in slide-in-from-bottom-4 duration-300">
                    {searchResult.loading ? (
                      <div className="flex items-center justify-center gap-3 py-6 bg-white/[0.02] border border-white/[0.06] rounded-xl lg:rounded-none">
                        <Loader2 className="w-5 h-5 animate-spin text-accent" />
                        <span className="text-sm text-white/50 font-medium">Scanning network...</span>
                      </div>
                    ) : (
                      <div className={clsx(
                        "border overflow-hidden rounded-xl lg:rounded-none shadow-2xl",
                        searchResult.is_available 
                          ? "border-accent/30 bg-[#0A0A0A]" 
                          : "border-white/[0.08] bg-[#0A0A0A]"
                      )}>
                        {/* Result Header */}
                        <div className={clsx(
                          "px-5 py-4 flex items-center justify-between border-b",
                          searchResult.is_available ? "bg-accent/[0.03] border-accent/10" : "bg-white/[0.01] border-white/[0.04]"
                        )}>
                          <div className="flex items-center gap-3">
                            {searchResult.is_available ? (
                              <div className="w-10 h-10 bg-accent/10 border border-accent/20 rounded-full flex items-center justify-center shrink-0">
                                <CheckCircle2 className="w-5 h-5 text-accent" />
                              </div>
                            ) : (
                              <div className="w-10 h-10 bg-white/5 border border-white/10 rounded-full flex items-center justify-center shrink-0">
                                <XCircle className="w-5 h-5 text-white/30" />
                              </div>
                            )}
                            <div className="min-w-0">
                              <div className="text-base lg:text-lg font-bold text-white truncate">{searchResult.domain}</div>
                              {!searchResult.is_available && searchResult.registrar && (
                                <div className="text-xs text-white/40 truncate">via {searchResult.registrar}</div>
                              )}
                            </div>
                          </div>
                          <span className={clsx(
                            "text-[10px] font-bold px-2.5 py-1 rounded-full uppercase tracking-wider shrink-0",
                            searchResult.is_available 
                              ? "bg-accent/10 text-accent border border-accent/20" 
                              : "bg-white/5 text-white/40 border border-white/10"
                          )}>
                            {searchResult.is_available ? 'Available' : 'Taken'}
                          </span>
                        </div>
                        
                        {/* Actions */}
                        <div className="p-4 flex flex-col gap-3">
                          <button
                            onClick={handleAddToWatchlist}
                            disabled={addingToWatchlist}
                            className={clsx(
                              "w-full py-3.5 text-sm font-bold rounded-lg flex items-center justify-center gap-2 transition-all active:scale-[0.98]",
                              searchResult.is_available 
                                ? "bg-white/5 text-white border border-white/10 hover:bg-white/10"
                                : "bg-accent/10 text-accent border border-accent/20 hover:bg-accent/20"
                            )}
                          >
                            {addingToWatchlist ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
                            {searchResult.is_available ? 'Add to Watchlist' : 'Track Availability'}
                          </button>
                          
                          {searchResult.is_available && (
                            <a
                              href={`https://www.namecheap.com/domains/registration/results/?domain=${searchResult.domain}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="w-full py-3.5 bg-accent text-[#020202] text-sm font-bold rounded-lg flex items-center justify-center gap-2 hover:bg-white active:scale-[0.98] transition-all shadow-[0_0_20px_-5px_rgba(16,185,129,0.4)]"
                            >
                              Register Now
                              <ArrowRight className="w-4 h-4" />
                            </a>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                )}
                
                {/* Hint */}
                {!searchResult && (
                  <p className="text-xs text-white/30 mt-3 text-center lg:text-left font-medium">
                    Type a domain to check status instantly
                  </p>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* QUICK ACTIONS - Mobile Grid */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="lg:hidden px-4 pb-6">
          <div className="grid grid-cols-3 gap-3">
            {[
              { href: '/terminal/watchlist', icon: Eye, label: 'Watchlist', badge: availableDomains.length, color: 'text-emerald-400', bg: 'bg-emerald-400/10', border: 'border-emerald-400/20' },
              { href: '/terminal/market', icon: Gavel, label: 'Market', color: 'text-blue-400', bg: 'bg-blue-400/10', border: 'border-blue-400/20' },
              { href: '/terminal/intel', icon: TrendingUp, label: 'Intel', color: 'text-amber-400', bg: 'bg-amber-400/10', border: 'border-amber-400/20' },
            ].map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={clsx(
                  "relative flex flex-col items-center justify-center gap-2 py-4 rounded-xl border transition-all active:scale-[0.96]",
                  "bg-[#0A0A0A] border-white/[0.08]"
                )}
              >
                <div className={clsx("w-10 h-10 rounded-full flex items-center justify-center", item.bg)}>
                  <item.icon className={clsx("w-5 h-5", item.color)} />
                </div>
                <span className="text-[11px] font-medium text-white/70">{item.label}</span>
                {item.badge !== undefined && item.badge > 0 && (
                  <span className="absolute -top-1.5 -right-1.5 min-w-[20px] h-[20px] px-1 bg-accent text-[#020202] text-[10px] font-bold rounded-full flex items-center justify-center border-2 border-[#020202]">
                    {item.badge}
                  </span>
                )}
              </Link>
            ))}
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* STATUS BAR */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10">
          <div className="flex items-center justify-between py-3 lg:py-4 border-y border-white/[0.06] bg-white/[0.01]">
            <div className="flex items-center gap-2">
              <div className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-accent opacity-75"></span>
                <span className="relative inline-flex rounded-full h-2 w-2 bg-accent"></span>
              </div>
              <span className="text-xs text-white/50 font-medium">Live Feed</span>
            </div>
            <div className="flex items-center gap-4 text-xs font-mono">
              <span className="text-white/30">{marketStats.totalAuctions.toLocaleString()} total</span>
              <span className="text-accent">{marketStats.endingSoon} ending</span>
            </div>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* WATCHLIST PREVIEW */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {domains && domains.length > 0 && (
          <section className="px-4 lg:px-10 py-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-sm font-bold text-white uppercase tracking-wider flex items-center gap-2">
                <Eye className="w-4 h-4 text-accent" />
                Your Watchlist
              </h2>
              <Link href="/terminal/watchlist" className="text-xs font-medium text-accent hover:text-white active:text-white transition-colors flex items-center gap-1">
                Manage
                <ChevronRight className="w-3 h-3" />
              </Link>
            </div>
            
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
              {domains.slice(0, 6).map((domain) => (
                <Link
                  key={domain.id}
                  href="/terminal/watchlist"
                  className={clsx(
                    "flex items-center gap-3 p-4 bg-[#0A0A0A] border rounded-xl lg:rounded-none transition-all active:scale-[0.99] group",
                    domain.is_available 
                      ? "border-accent/30 bg-accent/[0.03]" 
                      : "border-white/[0.06]"
                  )}
                >
                  <div className={clsx(
                    "w-10 h-10 rounded-lg lg:rounded-none flex items-center justify-center shrink-0",
                    domain.is_available 
                      ? "bg-accent/10 border border-accent/20" 
                      : "bg-white/[0.03] border border-white/[0.06]"
                  )}>
                    {domain.is_available ? (
                      <CheckCircle2 className="w-5 h-5 text-accent" />
                    ) : (
                      <Eye className="w-5 h-5 text-white/30" />
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-bold text-white truncate group-hover:text-accent transition-colors">
                      {domain.domain}
                    </div>
                    <div className={clsx(
                      "text-[10px] font-bold uppercase tracking-wider",
                      domain.is_available ? "text-accent" : "text-white/30"
                    )}>
                      {domain.is_available ? 'Available!' : 'Monitoring'}
                    </div>
                  </div>
                  {domain.is_available && (
                    <span className="px-2 py-1 bg-accent text-[#020202] text-[9px] font-bold rounded-sm shrink-0">
                      GET IT
                    </span>
                  )}
                </Link>
              ))}
            </div>
            
            {domains.length > 6 && (
              <Link 
                href="/terminal/watchlist" 
                className="mt-4 flex items-center justify-center gap-2 py-3 border border-white/[0.08] rounded-xl lg:rounded-none text-white/50 text-xs font-medium hover:text-white hover:border-white/20 active:bg-white/[0.02] transition-all"
              >
                View all {domains.length} domains
                <ArrowRight className="w-3 h-3" />
              </Link>
            )}
          </section>
        )}

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* HOT AUCTIONS - Feed Style */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-6 pb-28 lg:pb-10">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-bold text-white uppercase tracking-wider flex items-center gap-2">
              <Activity className="w-4 h-4 text-accent" />
              Live Auctions
            </h2>
            <Link href="/terminal/market" className="text-xs font-medium text-accent hover:text-white active:text-white transition-colors flex items-center gap-1">
              See all
              <ChevronRight className="w-3 h-3" />
            </Link>
          </div>
          
          {loadingData ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-6 h-6 text-accent animate-spin" />
            </div>
          ) : hotAuctions.length > 0 ? (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 lg:gap-px lg:bg-white/[0.06] lg:border lg:border-white/[0.06]">
              {hotAuctions.map((auction, i) => (
                <a
                  key={i}
                  href={auction.affiliate_url || '#'}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-4 p-4 bg-[#0A0A0A] border border-white/[0.06] rounded-xl lg:rounded-none lg:border-0 hover:bg-white/[0.02] active:scale-[0.99] transition-all group shadow-sm"
                >
                  <div className="w-10 h-10 lg:w-12 lg:h-12 bg-white/[0.03] border border-white/[0.06] rounded-lg lg:rounded-none flex items-center justify-center shrink-0 group-hover:border-accent/20 group-hover:bg-accent/5 transition-all">
                    <Gavel className="w-4 h-4 lg:w-5 lg:h-5 text-white/40 group-hover:text-accent" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="text-sm lg:text-base font-bold text-white truncate group-hover:text-accent transition-colors">
                      {auction.domain}
                    </div>
                    <div className="flex items-center gap-2 text-[11px] text-white/40 mt-0.5">
                      <span className="uppercase tracking-wider">{auction.platform}</span>
                      <span className="text-white/10">•</span>
                      <span className="flex items-center gap-1 text-white/60">
                        <Clock className="w-3 h-3" />
                        {auction.time_remaining}
                      </span>
                    </div>
                  </div>
                  <div className="text-right shrink-0">
                    <div className="text-base lg:text-lg font-bold text-accent font-mono">
                      ${auction.current_bid.toLocaleString()}
                    </div>
                    <div className="text-[9px] font-bold text-white/20 uppercase tracking-wider">current bid</div>
                  </div>
                </a>
              ))}
            </div>
          ) : (
            <div className="text-center py-12 border border-dashed border-white/[0.08] rounded-xl">
              <Gavel className="w-8 h-8 text-white/10 mx-auto mb-3" />
              <p className="text-white/30 text-sm">No active auctions</p>
            </div>
          )}

          {/* Desktop Quick Links */}
          <div className="hidden lg:grid grid-cols-3 gap-4 mt-8">
            {[
              { href: '/terminal/watchlist', icon: Eye, label: 'Watchlist', desc: 'Track domain availability' },
              { href: '/terminal/market', icon: Gavel, label: 'Market', desc: 'Browse all auctions' },
              { href: '/terminal/intel', icon: Globe, label: 'Intel', desc: 'TLD price analysis' },
            ].map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className="flex items-center gap-4 p-5 border border-white/[0.06] hover:border-accent/30 hover:bg-accent/[0.02] transition-all group"
              >
                <div className="w-12 h-12 bg-white/[0.02] border border-white/[0.08] flex items-center justify-center group-hover:border-accent/20 group-hover:bg-accent/10 transition-all">
                  <item.icon className="w-5 h-5 text-white/40 group-hover:text-accent transition-colors" />
                </div>
                <div>
                  <div className="text-sm font-medium text-white group-hover:text-accent transition-colors">{item.label}</div>
                  <div className="text-xs text-white/30">{item.desc}</div>
                </div>
                <ArrowRight className="w-4 h-4 text-white/10 group-hover:text-accent group-hover:translate-x-1 transition-all ml-auto" />
              </Link>
            ))}
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE BOTTOM NAV - Frosted Glass */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <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-accent" : "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-accent shadow-[0_0_10px_rgba(16,185,129,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>
            ))}
            
            {/* Menu Button */}
            <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 MENU - Slide Over */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {menuOpen && (
          <div className="lg:hidden fixed inset-0 z-[100]">
            {/* Backdrop */}
            <div 
              className="absolute inset-0 bg-black/60 backdrop-blur-sm animate-in fade-in duration-300"
              onClick={() => setMenuOpen(false)}
            />
            
            {/* Drawer Panel */}
            <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)' }}>
              
              {/* Drawer Header */}
              <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>
              
              {/* Navigation Sections */}
              <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>
                ))}
                
                {/* Settings Group */}
                <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>
              
              {/* User Card - Bottom */}
              <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 && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
    </div>
  )
}
