'use client'

import { useEffect, useState, useMemo, useCallback, useRef } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { Toast, useToast } from '@/components/Toast'
import {
  Eye,
  Gavel,
  ExternalLink,
  Plus,
  Activity,
  ArrowRight,
  CheckCircle2,
  XCircle,
  Loader2,
  Crosshair,
  Zap,
  Globe,
  Target,
  Search,
  Home,
  BarChart3,
  Settings,
  Bell,
  ChevronRight,
  TrendingUp,
  RefreshCw
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

// ============================================================================
// 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
}

// ============================================================================
// MOBILE BOTTOM NAV
// ============================================================================

function MobileBottomNav({ active }: { active: string }) {
  const navItems = [
    { id: 'radar', label: 'Radar', icon: Crosshair, href: '/terminal/radar' },
    { id: 'market', label: 'Market', icon: Gavel, href: '/terminal/market' },
    { id: 'watchlist', label: 'Watch', icon: Eye, href: '/terminal/watchlist' },
    { id: 'intel', label: 'Intel', icon: BarChart3, href: '/terminal/intel' },
  ]

  return (
    <nav className="lg:hidden fixed bottom-0 left-0 right-0 z-50 bg-[#0a0a0a]/95 backdrop-blur-xl border-t border-white/10 safe-area-bottom">
      <div className="flex items-center justify-around h-16">
        {navItems.map((item) => {
          const isActive = active === item.id
          return (
            <Link
              key={item.id}
              href={item.href}
              className="flex flex-col items-center justify-center flex-1 h-full active:scale-95 transition-transform"
            >
              <item.icon className={clsx(
                "w-6 h-6 mb-1 transition-colors",
                isActive ? "text-accent" : "text-white/40"
              )} />
              <span className={clsx(
                "text-[10px] font-medium transition-colors",
                isActive ? "text-accent" : "text-white/40"
              )}>
                {item.label}
              </span>
              {isActive && (
                <div className="absolute bottom-2 w-1 h-1 bg-accent rounded-full" />
              )}
            </Link>
          )
        })}
      </div>
    </nav>
  )
}

// ============================================================================
// MOBILE HEADER
// ============================================================================

function MobileHeader({ 
  onSearchOpen,
  isRefreshing,
  onRefresh
}: { 
  onSearchOpen: () => void
  isRefreshing: boolean
  onRefresh: () => void
}) {
  return (
    <header className="lg:hidden sticky top-0 z-40 bg-[#020202]/95 backdrop-blur-xl border-b border-white/[0.08] safe-area-top">
      <div className="flex items-center justify-between px-4 h-14">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center">
            <Crosshair className="w-4 h-4 text-accent" />
          </div>
          <div>
            <h1 className="text-base font-semibold text-white">Radar</h1>
            <div className="flex items-center gap-1.5">
              <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse" />
              <span className="text-[10px] text-accent font-mono">Live</span>
            </div>
          </div>
        </div>
        
        <div className="flex items-center gap-2">
          <button 
            onClick={onRefresh}
            disabled={isRefreshing}
            className="w-10 h-10 flex items-center justify-center text-white/50 active:text-white transition-colors"
          >
            <RefreshCw className={clsx("w-5 h-5", isRefreshing && "animate-spin")} />
          </button>
          <button 
            onClick={onSearchOpen}
            className="w-10 h-10 bg-accent/10 border border-accent/30 flex items-center justify-center text-accent active:scale-95 transition-transform"
          >
            <Search className="w-5 h-5" />
          </button>
        </div>
      </div>
    </header>
  )
}

// ============================================================================
// MOBILE SEARCH MODAL
// ============================================================================

function MobileSearchModal({
  isOpen,
  onClose,
  searchQuery,
  setSearchQuery,
  searchResult,
  addingToWatchlist,
  onAddToWatchlist
}: {
  isOpen: boolean
  onClose: () => void
  searchQuery: string
  setSearchQuery: (q: string) => void
  searchResult: SearchResult | null
  addingToWatchlist: boolean
  onAddToWatchlist: () => void
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  
  useEffect(() => {
    if (isOpen && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 100)
    }
  }, [isOpen])

  if (!isOpen) return null

  return (
    <div className="lg:hidden fixed inset-0 z-50 bg-[#020202] animate-in fade-in slide-in-from-bottom-4 duration-300">
      {/* Header */}
      <div className="flex items-center gap-3 px-4 h-16 border-b border-white/10 safe-area-top">
        <button 
          onClick={onClose}
          className="text-white/50 text-sm font-medium"
        >
          Cancel
        </button>
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-white/30" />
          <input
            ref={inputRef}
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search domain..."
            className="w-full h-10 bg-white/5 border border-white/10 pl-11 pr-4 text-white placeholder:text-white/30 outline-none focus:border-accent/50 rounded-lg"
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="none"
          />
        </div>
      </div>

      {/* Results */}
      <div className="flex-1 overflow-auto p-4">
        {searchResult?.loading && (
          <div className="flex items-center justify-center gap-3 py-16 text-white/40">
            <Loader2 className="w-6 h-6 animate-spin text-accent" />
            <span className="text-sm">Checking...</span>
          </div>
        )}

        {searchResult && !searchResult.loading && (
          <div className={clsx(
            "border-2 overflow-hidden",
            searchResult.is_available ? "bg-accent/5 border-accent/40" : "bg-white/[0.02] border-white/10"
          )}>
            {/* Status Banner */}
            <div className={clsx(
              "px-5 py-4 flex items-center gap-4",
              searchResult.is_available ? "bg-accent/10" : "bg-white/[0.02]"
            )}>
              {searchResult.is_available ? (
                <div className="w-12 h-12 bg-accent/20 border border-accent/40 flex items-center justify-center">
                  <CheckCircle2 className="w-6 h-6 text-accent" />
                </div>
              ) : (
                <div className="w-12 h-12 bg-white/5 border border-white/10 flex items-center justify-center">
                  <XCircle className="w-6 h-6 text-white/30" />
                </div>
              )}
              <div className="flex-1">
                <div className="text-lg font-semibold text-white">{searchResult.domain}</div>
                <div className={clsx(
                  "text-xs font-medium",
                  searchResult.is_available ? "text-accent" : "text-white/40"
                )}>
                  {searchResult.is_available ? 'Available for registration' : 'Already registered'}
                </div>
              </div>
            </div>

            {/* Details */}
            {!searchResult.is_available && searchResult.registrar && (
              <div className="px-5 py-3 border-t border-white/[0.06] bg-black/20">
                <div className="flex items-center justify-between text-xs">
                  <span className="text-white/40">Registrar</span>
                  <span className="text-white/70">{searchResult.registrar}</span>
                </div>
              </div>
            )}

            {/* Actions */}
            <div className="p-4 border-t border-white/[0.06] space-y-3">
              <button
                onClick={onAddToWatchlist}
                disabled={addingToWatchlist}
                className={clsx(
                  "w-full h-14 flex items-center justify-center gap-3 text-base font-semibold transition-colors active:scale-[0.98]",
                  searchResult.is_available 
                    ? "border border-white/20 text-white/80 active:bg-white/10"
                    : "border border-accent/30 text-accent active:bg-accent/10"
                )}
              >
                {addingToWatchlist ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
                {searchResult.is_available ? 'Add to Watchlist' : 'Track for Availability'}
              </button>
              
              {searchResult.is_available && (
                <a
                  href={`https://www.namecheap.com/domains/registration/results/?domain=${searchResult.domain}`}
                  target="_blank"
                  className="w-full h-14 bg-accent text-black text-base font-bold flex items-center justify-center gap-3 active:bg-white transition-colors active:scale-[0.98]"
                >
                  Register Now
                  <ArrowRight className="w-5 h-5" />
                </a>
              )}
            </div>
          </div>
        )}

        {!searchResult && searchQuery.length === 0 && (
          <div className="text-center py-16">
            <div className="w-16 h-16 mx-auto bg-white/[0.02] border border-white/10 flex items-center justify-center mb-4">
              <Search className="w-8 h-8 text-white/10" />
            </div>
            <p className="text-white/30 text-sm">Enter a domain to check availability</p>
          </div>
        )}
      </div>
    </div>
  )
}

// ============================================================================
// STAT CARD - Mobile Optimized
// ============================================================================

function StatCard({ label, value, highlight, icon: Icon }: { 
  label: string
  value: string | number
  highlight?: boolean
  icon: any
}) {
  return (
    <div className="bg-white/[0.02] border border-white/[0.06] p-4 active:bg-white/[0.04] transition-colors">
      <div className="flex items-center gap-2 mb-2">
        <Icon className={clsx("w-4 h-4", highlight ? "text-accent" : "text-white/30")} />
        <span className="text-[10px] font-mono text-white/40 tracking-wide">{label}</span>
      </div>
      <div className={clsx(
        "text-2xl font-display",
        highlight ? "text-accent" : "text-white"
      )}>
        {value}
      </div>
    </div>
  )
}

// ============================================================================
// AUCTION CARD - Mobile Optimized
// ============================================================================

function AuctionCard({ auction }: { auction: HotAuction }) {
  return (
    <a
      href={auction.affiliate_url || '#'}
      target="_blank"
      className="flex items-center gap-4 p-4 bg-white/[0.02] border border-white/[0.06] active:bg-white/[0.05] transition-colors"
    >
      <div className="w-10 h-10 bg-white/5 border border-white/10 flex items-center justify-center shrink-0">
        <span className="text-[10px] font-mono text-white/40">{auction.platform.substring(0, 2)}</span>
      </div>
      <div className="flex-1 min-w-0">
        <div className="text-sm font-medium text-white truncate">{auction.domain}</div>
        <div className="text-[10px] text-white/40">{auction.time_remaining}</div>
      </div>
      <div className="text-right shrink-0">
        <div className="font-mono text-base font-semibold text-accent">${auction.current_bid.toLocaleString()}</div>
        <div className="text-[10px] text-white/30">Current bid</div>
      </div>
      <ChevronRight className="w-4 h-4 text-white/20 shrink-0" />
    </a>
  )
}

// ============================================================================
// DESKTOP LIVE TICKER
// ============================================================================

function LiveTicker({ items }: { items: { label: string; value: string; highlight?: boolean }[] }) {
  return (
    <div className="hidden lg:block relative border-y border-white/[0.08] bg-black/40 overflow-hidden">
      <div className="absolute left-0 top-0 bottom-0 w-16 bg-gradient-to-r from-[#020202] to-transparent z-10" />
      <div className="absolute right-0 top-0 bottom-0 w-16 bg-gradient-to-l from-[#020202] to-transparent z-10" />
      
      <div className="flex animate-[ticker_30s_linear_infinite] py-2.5" style={{ width: 'max-content' }}>
        {[...items, ...items, ...items].map((item, i) => (
          <div key={i} className="flex items-center gap-3 px-6 border-r border-white/[0.08]">
            <span className="text-[10px] font-mono tracking-wide text-white/30">{item.label}</span>
            <span className={clsx(
              "text-xs font-mono font-medium",
              item.highlight ? "text-accent" : "text-white/70"
            )}>{item.value}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

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

export default function RadarPage() {
  const { isAuthenticated, user, domains, addDomain } = 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 [isRefreshing, setIsRefreshing] = useState(false)
  
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResult, setSearchResult] = useState<SearchResult | null>(null)
  const [addingToWatchlist, setAddingToWatchlist] = useState(false)
  const [searchFocused, setSearchFocused] = useState(false)
  const [mobileSearchOpen, setMobileSearchOpen] = useState(false)
  const searchInputRef = useRef<HTMLInputElement>(null)

  // Load Data
  const loadDashboardData = useCallback(async () => {
    try {
      const summary = await api.getDashboardSummary()
      setHotAuctions((summary.market.ending_soon_preview || []).slice(0, 5))
      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)
      setIsRefreshing(false)
    }
  }, [])

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true)
    await loadDashboardData()
  }, [loadDashboardData])

  useEffect(() => {
    if (isAuthenticated) loadDashboardData()
  }, [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(`Target acquired: ${searchQuery.trim()}`, 'success')
      setSearchQuery('')
      setSearchResult(null)
      setMobileSearchOpen(false)
    } catch (err: any) {
      showToast(err.message || 'Mission 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
  
  const tickerItems = [
    { label: 'Status', value: 'ONLINE', highlight: true },
    { label: 'Tracking', value: totalDomains.toString() },
    { label: 'Available', value: availableDomains.length.toString(), highlight: availableDomains.length > 0 },
    { label: 'Auctions', value: marketStats.totalAuctions.toString() },
  ]

  return (
    <>
      {/* Mobile Header */}
      <MobileHeader 
        onSearchOpen={() => setMobileSearchOpen(true)} 
        isRefreshing={isRefreshing}
        onRefresh={handleRefresh}
      />

      {/* Mobile Search Modal */}
      <MobileSearchModal
        isOpen={mobileSearchOpen}
        onClose={() => setMobileSearchOpen(false)}
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
        searchResult={searchResult}
        addingToWatchlist={addingToWatchlist}
        onAddToWatchlist={handleAddToWatchlist}
      />

      {/* Mobile Content */}
      <div className="lg:hidden min-h-screen bg-[#020202] pb-20">
        {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
        
        {/* Stats Grid */}
        <div className="p-4 grid grid-cols-2 gap-2">
          <StatCard label="Tracking" value={totalDomains} icon={Eye} />
          <StatCard label="Available" value={availableDomains.length} highlight={availableDomains.length > 0} icon={CheckCircle2} />
          <StatCard label="Auctions" value={marketStats.totalAuctions} icon={Gavel} />
          <StatCard label="Ending Soon" value={marketStats.endingSoon} icon={Activity} />
        </div>

        {/* Available Alert */}
        {availableDomains.length > 0 && (
          <div className="mx-4 mb-4 p-4 bg-accent/10 border border-accent/30">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-accent/20 border border-accent/40 flex items-center justify-center">
                <Bell className="w-5 h-5 text-accent" />
              </div>
              <div className="flex-1">
                <div className="text-sm font-semibold text-white">{availableDomains.length} Domain{availableDomains.length > 1 ? 's' : ''} Available!</div>
                <div className="text-xs text-accent">Check your watchlist now</div>
              </div>
              <Link href="/terminal/watchlist" className="w-10 h-10 bg-accent flex items-center justify-center">
                <ArrowRight className="w-5 h-5 text-black" />
              </Link>
            </div>
          </div>
        )}

        {/* Section: Live Auctions */}
        <div className="px-4 mb-6">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <Gavel className="w-4 h-4 text-accent" />
              <span className="text-sm font-semibold text-white">Live Auctions</span>
            </div>
            <Link href="/terminal/market" className="text-xs text-accent font-medium">
              See all
            </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="space-y-2">
              {hotAuctions.map((auction, i) => (
                <AuctionCard key={i} auction={auction} />
              ))}
            </div>
          ) : (
            <div className="text-center py-12 border border-dashed border-white/10">
              <Gavel className="w-8 h-8 text-white/10 mx-auto mb-2" />
              <p className="text-white/30 text-sm">No active auctions</p>
            </div>
          )}
        </div>

        {/* Section: Quick Links */}
        <div className="px-4 mb-6">
          <div className="flex items-center gap-2 mb-3">
            <Zap className="w-4 h-4 text-white/50" />
            <span className="text-sm font-semibold text-white">Quick Actions</span>
          </div>
          
          <div className="grid grid-cols-2 gap-2">
            {[
              { label: 'TLD Intel', desc: 'Price trends', href: '/terminal/intel', icon: TrendingUp },
              { label: 'Sniper', desc: 'Set alerts', href: '/terminal/sniper', icon: Target },
            ].map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className="p-4 bg-white/[0.02] border border-white/[0.06] active:bg-white/[0.05] transition-colors"
              >
                <item.icon className="w-5 h-5 text-accent mb-3" />
                <div className="text-sm font-medium text-white">{item.label}</div>
                <div className="text-[10px] text-white/40">{item.desc}</div>
              </Link>
            ))}
          </div>
        </div>
      </div>

      {/* Mobile Bottom Nav */}
      <MobileBottomNav active="radar" />

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* DESKTOP LAYOUT */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <div className="hidden lg:block">
        <CommandCenterLayout minimal>
          {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
          
          {/* HERO */}
          <section className="pt-6 lg:pt-8 pb-10">
            <div className="grid lg:grid-cols-2 gap-10 lg:gap-16 items-center">
              
              {/* Left: Typography */}
              <div className="space-y-5">
                <div className="inline-flex items-center gap-3">
                  <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse shadow-[0_0_10px_rgba(16,185,129,0.8)]" />
                  <span className="text-[10px] font-mono tracking-[0.15em] text-accent">
                    Intelligence Hub
                  </span>
                </div>
                
                <h1 className="font-display text-[2rem] sm:text-[2.5rem] lg:text-[2.75rem] leading-[1] tracking-[-0.02em]">
                  <span className="block text-white">Domain Radar</span>
                  <span className="block text-white/30">Find your next acquisition.</span>
                </h1>
                
                <p className="text-sm text-white/50 max-w-md font-light leading-relaxed">
                  Real-time monitoring across {marketStats.totalAuctions.toLocaleString()}+ auctions. 
                  <span className="text-white/70"> Your targets. Your intel.</span>
                </p>
                
                {/* Stats Row */}
                <div className="flex gap-8 lg:gap-10 pt-5 border-t border-white/[0.08]">
                  <div>
                    <div className="text-xl lg:text-2xl font-display text-white">{totalDomains}</div>
                    <div className="text-[9px] tracking-wide text-white/30 font-mono mt-1">Tracking</div>
                  </div>
                  <div>
                    <div className="text-xl lg:text-2xl font-display text-accent">{availableDomains.length}</div>
                    <div className="text-[9px] tracking-wide text-white/30 font-mono mt-1">Available</div>
                  </div>
                  <div>
                    <div className="text-xl lg:text-2xl font-display text-white">{marketStats.endingSoon}</div>
                    <div className="text-[9px] tracking-wide text-white/30 font-mono mt-1">Ending Soon</div>
                  </div>
                </div>
              </div>
              
              {/* Right: Search Terminal */}
              <div className="relative">
                <div className="absolute -inset-4 bg-gradient-to-tr from-accent/10 via-transparent to-accent/5 blur-3xl opacity-30" />
                
                <div className="relative bg-[#0A0A0A] border border-white/10 overflow-hidden">
                  {/* Header Bar */}
                  <div className="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>
                  
                  <div className="p-5 lg:p-6">
                    {/* Input */}
                    <div className={clsx(
                      "relative border-2 transition-all duration-300 bg-black/30",
                      searchFocused ? "border-accent/60 shadow-[0_0_30px_-10px_rgba(16,185,129,0.3)]" : "border-white/10"
                    )}>
                      <input
                        ref={searchInputRef}
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        onFocus={() => setSearchFocused(true)}
                        onBlur={() => setSearchFocused(false)}
                        placeholder="example.com"
                        className="w-full bg-transparent px-4 py-4 text-lg text-white placeholder:text-white/20 outline-none"
                      />
                      {searchQuery && (
                        <button 
                          onClick={() => { setSearchQuery(''); setSearchResult(null) }}
                          className="absolute right-4 top-1/2 -translate-y-1/2 text-white/30 hover:text-white transition-colors"
                        >
                          <XCircle className="w-5 h-5" />
                        </button>
                      )}
                    </div>
                    
                    {/* Results */}
                    {searchResult && (
                      <div className="mt-5">
                        {searchResult.loading ? (
                          <div className="flex items-center justify-center gap-3 py-6 text-white/40">
                            <Loader2 className="w-4 h-4 animate-spin" />
                            <span className="text-sm">Checking availability...</span>
                          </div>
                        ) : (
                          <div className={clsx(
                            "p-5 border-2 transition-all",
                            searchResult.is_available 
                              ? "bg-accent/5 border-accent/40" 
                              : "bg-white/[0.02] border-white/10"
                          )}>
                            {/* Status Header */}
                            <div className="flex items-center justify-between mb-4">
                              <div className="flex items-center gap-3">
                                {searchResult.is_available ? (
                                  <CheckCircle2 className="w-5 h-5 text-accent" />
                                ) : (
                                  <XCircle className="w-5 h-5 text-white/30" />
                                )}
                                <span className="text-lg font-medium text-white">{searchResult.domain}</span>
                              </div>
                              <span className={clsx(
                                "text-xs font-medium px-3 py-1",
                                searchResult.is_available 
                                  ? "text-accent bg-accent/10" 
                                  : "text-white/40 bg-white/5"
                              )}>
                                {searchResult.is_available ? 'Available' : 'Taken'}
                              </span>
                            </div>
                            
                            {/* Registrar Info for taken domains */}
                            {!searchResult.is_available && searchResult.registrar && (
                              <p className="text-xs text-white/40 mb-4">
                                Registered with {searchResult.registrar}
                              </p>
                            )}
                            
                            {/* Actions */}
                            <div className="flex gap-3">
                              <button
                                onClick={handleAddToWatchlist}
                                disabled={addingToWatchlist}
                                className={clsx(
                                  "flex-1 py-3 text-sm font-medium transition-colors flex items-center justify-center gap-2",
                                  searchResult.is_available 
                                    ? "border border-white/20 text-white/80 hover:bg-white/5"
                                    : "border border-accent/30 text-accent hover:bg-accent/10"
                                )}
                              >
                                {addingToWatchlist ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
                                {searchResult.is_available ? 'Add to Watchlist' : 'Track for Availability'}
                              </button>
                              {searchResult.is_available && (
                                <a
                                  href={`https://www.namecheap.com/domains/registration/results/?domain=${searchResult.domain}`}
                                  target="_blank"
                                  className="flex-1 py-3 bg-accent text-black text-sm font-bold hover:bg-white transition-colors flex items-center justify-center gap-2"
                                >
                                  Register Now <ArrowRight className="w-4 h-4" />
                                </a>
                              )}
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                    
                    {/* Hint */}
                    {!searchResult && (
                      <p className="text-xs text-white/20 mt-4 text-center">
                        Enter a domain name to check availability
                      </p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </section>

          {/* Ticker */}
          <LiveTicker items={tickerItems} />

          {/* CONTENT GRID */}
          <section className="py-8 lg:py-10">
            <div className="grid lg:grid-cols-3 gap-px bg-white/[0.08] border border-white/[0.08]">
              
              {/* Hot Auctions - 2 cols */}
              <div className="lg:col-span-2 bg-[#020202] p-6 lg:p-8">
                <div className="flex items-center justify-between mb-5">
                  <div className="flex items-center gap-2">
                    <Gavel className="w-4 h-4 text-accent" />
                    <span className="text-sm font-semibold text-white">Live Auctions</span>
                  </div>
                  <Link href="/terminal/market" className="text-xs text-white/40 hover:text-white transition-colors">
                    View all →
                  </Link>
                </div>
                
                {loadingData ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-5 h-5 text-accent animate-spin" />
                  </div>
                ) : hotAuctions.length > 0 ? (
                  <div className="space-y-1">
                    {hotAuctions.map((auction, i) => (
                      <a
                        key={i}
                        href={auction.affiliate_url || '#'}
                        target="_blank"
                        className="flex items-center justify-between p-3 bg-white/[0.02] hover:bg-white/[0.05] transition-colors group"
                      >
                        <div className="flex items-center gap-3">
                          <span className="text-[10px] font-mono text-white/25 w-6">{auction.platform.substring(0, 3)}</span>
                          <div>
                            <div className="text-sm text-white group-hover:text-accent transition-colors">{auction.domain}</div>
                            <div className="text-[10px] text-white/30">{auction.time_remaining}</div>
                          </div>
                        </div>
                        <div className="font-mono text-sm text-accent font-medium">${auction.current_bid.toLocaleString()}</div>
                      </a>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 text-white/20 text-sm">No active auctions</div>
                )}
              </div>
              
              {/* Quick Links */}
              <div className="bg-[#020202] p-6 lg:p-8">
                <div className="flex items-center gap-2 mb-5">
                  <Zap className="w-4 h-4 text-white/50" />
                  <span className="text-sm font-semibold text-white">Quick Access</span>
                </div>
                
                <div className="space-y-2">
                  {[
                    { label: 'Watchlist', href: '/terminal/watchlist', icon: Eye },
                    { label: 'Market', href: '/terminal/market', icon: Gavel },
                    { label: 'Intel', href: '/terminal/intel', icon: Globe },
                  ].map((item) => (
                    <Link
                      key={item.href}
                      href={item.href}
                      className="flex items-center gap-3 p-3 border border-white/[0.05] hover:border-accent/30 hover:bg-accent/5 transition-all group"
                    >
                      <item.icon className="w-4 h-4 text-white/30 group-hover:text-accent transition-colors" />
                      <span className="text-sm text-white/70 group-hover:text-white transition-colors flex-1">{item.label}</span>
                      <ArrowRight className="w-3 h-3 text-white/15 group-hover:text-accent group-hover:translate-x-0.5 transition-all" />
                    </Link>
                  ))}
                </div>
                
                {/* Status */}
                <div className="mt-6 pt-4 border-t border-white/[0.05]">
                  <div className="flex items-center gap-2">
                    <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse" />
                    <span className="text-[10px] font-mono text-white/30">System online</span>
                  </div>
                </div>
              </div>
              
            </div>
          </section>
        </CommandCenterLayout>
      </div>
      
      <style jsx global>{`
        @keyframes ticker {
          0% { transform: translateX(0); }
          100% { transform: translateX(-33.33%); }
        }
        
        /* Safe area for notch and home indicator */
        .safe-area-top {
          padding-top: env(safe-area-inset-top);
        }
        .safe-area-bottom {
          padding-bottom: env(safe-area-inset-bottom);
        }
        
        /* Prevent overscroll on mobile */
        @media (max-width: 1023px) {
          html, body {
            overscroll-behavior: none;
          }
        }
      `}</style>
    </>
  )
}
