'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api, DomainHealthReport, HealthStatus } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { Sidebar } from '@/components/Sidebar'
import { Toast, useToast } from '@/components/Toast'
import {
  Plus,
  Trash2,
  RefreshCw,
  Loader2,
  Bell,
  BellOff,
  Eye,
  X,
  Activity,
  AlertTriangle,
  CheckCircle2,
  XCircle,
  Target,
  ExternalLink,
  Gavel,
  TrendingUp,
  Menu,
  Settings,
  Shield,
  LogOut,
  Crown,
  Sparkles,
  Coins,
  Tag,
  Zap,
  Search,
  ChevronUp,
  ChevronDown,
  Briefcase,
  ShoppingCart,
  Crosshair
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

// ============================================================================
// ADD MODAL COMPONENT (like Portfolio)
// ============================================================================

function AddModal({ 
  onClose, 
  onAdd 
}: { 
  onClose: () => void
  onAdd: (domain: string) => Promise<void>
}) {
  const [domain, setDomain] = useState('')
  const [adding, setAdding] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!domain.trim()) return
    setAdding(true)
    try {
      await onAdd(domain.trim().toLowerCase())
      onClose()
    } finally {
      setAdding(false)
    }
  }

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm" onClick={onClose}>
      <div 
        className="w-full max-w-md bg-[#0a0a0a] border border-white/10"
        onClick={e => e.stopPropagation()}
      >
        <div className="flex items-center justify-between p-4 border-b border-white/10">
          <div className="flex items-center gap-2">
            <Eye className="w-4 h-4 text-accent" />
            <span className="text-sm font-mono text-white uppercase tracking-wider">Add to Watchlist</span>
          </div>
          <button onClick={onClose} className="p-2 text-white/40 hover:text-white transition-colors">
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          <div>
            <label className="block text-[10px] font-mono text-white/40 mb-2 uppercase tracking-wider">Domain Name</label>
            <input
              type="text"
              value={domain}
              onChange={e => setDomain(e.target.value)}
              placeholder="example.com"
              autoFocus
              className="w-full px-4 py-3 bg-white/5 border border-white/10 text-white text-lg font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20"
            />
            <p className="text-[10px] font-mono text-white/30 mt-2">
              We'll check availability and notify you when it becomes available.
            </p>
          </div>

          <button
            type="submit"
            disabled={adding || !domain.trim()}
            className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-accent text-black text-sm font-bold uppercase tracking-wider hover:bg-white transition-colors disabled:opacity-50"
          >
            {adding ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
            Add to Watchlist
          </button>
        </form>
      </div>
    </div>
  )
}

// ============================================================================
// HELPERS
// ============================================================================

function getDaysUntilExpiry(expirationDate: string | null): number | null {
  if (!expirationDate) return null
  const expDate = new Date(expirationDate)
  const now = new Date()
  const diffTime = expDate.getTime() - now.getTime()
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

function formatExpiryDate(expirationDate: string | null): string {
  if (!expirationDate) return '—'
  return new Date(expirationDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
}

const healthConfig: Record<HealthStatus, { label: string; color: string; bg: string }> = {
  healthy: { label: 'Healthy', color: 'text-accent', bg: 'bg-accent/10 border-accent/20' },
  weakening: { label: 'Weak', color: 'text-amber-400', bg: 'bg-amber-500/10 border-amber-500/20' },
  parked: { label: 'Parked', color: 'text-blue-400', bg: 'bg-blue-500/10 border-blue-500/20' },
  critical: { label: 'Critical', color: 'text-rose-400', bg: 'bg-rose-500/10 border-rose-500/20' },
  unknown: { label: 'Unknown', color: 'text-white/40', bg: 'bg-white/5 border-white/10' },
}

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

export default function WatchlistPage() {
  const { domains, addDomain, deleteDomain, refreshDomain, updateDomain, subscription, user, logout, checkAuth } = useStore()
  const { toast, showToast, hideToast } = useToast()
  const openAnalyzePanel = useAnalyzePanelStore((s) => s.open)
  
  // Wrapper to open analyze panel with domain status
  const openAnalyze = useCallback((domainData: { name: string; status: string; is_available: boolean; expiration_date: string | null; deletion_date?: string | null }) => {
    // Map domain status to drop status format
    const statusMap: Record<string, 'available' | 'dropping_soon' | 'taken' | 'unknown'> = {
      'available': 'available',
      'dropping_soon': 'dropping_soon',
      'taken': 'taken',
      'error': 'unknown',
      'unknown': 'unknown',
    }
    openAnalyzePanel(domainData.name, {
      status: statusMap[domainData.status] || (domainData.is_available ? 'available' : 'taken'),
      deletion_date: domainData.deletion_date || domainData.expiration_date,
      is_drop: false,
    })
  }, [openAnalyzePanel])
  
  // Modal state
  const [showAddModal, setShowAddModal] = useState(false)
  const [refreshingId, setRefreshingId] = useState<number | null>(null)
  const [refreshingAll, setRefreshingAll] = useState(false)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [togglingNotifyId, setTogglingNotifyId] = useState<number | null>(null)
  const [healthReports, setHealthReports] = useState<Record<number, DomainHealthReport>>({})
  const [loadingHealth, setLoadingHealth] = useState<Record<number, boolean>>({})
  const [selectedDomain, setSelectedDomain] = useState<number | null>(null)
  const [filter, setFilter] = useState<'all' | 'available' | 'expiring'>('all')
  const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null)
  
  // Sorting
  const [sortField, setSortField] = useState<'domain' | 'status' | 'health' | 'expiry'>('domain')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
  
  // Mobile Menu
  const [menuOpen, setMenuOpen] = useState(false)

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

  // Stats
  // Tier limits
  const tier = subscription?.tier || 'scout'
  const watchlistLimits: Record<string, number> = { scout: 5, trader: 50, tycoon: Infinity }
  const maxWatchlist = watchlistLimits[tier] || 5
  const formatLimit = (limit: number) => limit === Infinity ? '∞' : String(limit)
  
  const stats = useMemo(() => {
    const available = domains?.filter(d => d.is_available) || []
    const expiringSoon = domains?.filter(d => {
      if (d.is_available || !d.expiration_date) return false
      const days = getDaysUntilExpiry(d.expiration_date)
      return days !== null && days <= 30 && days > 0
    }) || []
    return { total: domains?.length || 0, available: available.length, expiring: expiringSoon.length }
  }, [domains])

  // Filtered
  const filteredDomains = useMemo(() => {
    if (!domains) return []
    let filtered = domains.filter(d => {
      if (filter === 'available') return d.is_available
      if (filter === 'expiring') {
        const days = getDaysUntilExpiry(d.expiration_date)
        return days !== null && days <= 30 && days > 0
      }
      return true
    })
    
    // Sort
    const mult = sortDirection === 'asc' ? 1 : -1
    filtered.sort((a, b) => {
      switch (sortField) {
        case 'domain': return mult * a.name.localeCompare(b.name)
        case 'status': 
          if (a.is_available && !b.is_available) return mult * -1
          if (!a.is_available && b.is_available) return mult * 1
          return 0
        case 'health':
          const aHealth = healthReports[a.id]?.score || 0
          const bHealth = healthReports[b.id]?.score || 0
          return mult * (aHealth - bHealth)
        case 'expiry':
          const aExp = a.expiration_date ? new Date(a.expiration_date).getTime() : Infinity
          const bExp = b.expiration_date ? new Date(b.expiration_date).getTime() : Infinity
          return mult * (aExp - bExp)
        default: return 0
      }
    })
    
    return filtered
  }, [domains, filter, sortField, sortDirection, healthReports])
  
  const handleSortWatch = useCallback((field: typeof sortField) => {
    if (sortField === field) {
      setSortDirection(d => d === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDirection('asc')
    }
  }, [sortField])

  // Handlers
  const handleAdd = useCallback(async (domainName: string) => {
    try {
      await addDomain(domainName)
      showToast(`Added: ${domainName}`, 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed', 'error')
      throw err
    }
  }, [addDomain, showToast])
  
  // Auto-trigger health check for newly added domains
  useEffect(() => {
    if (!domains?.length) return
    
    domains.forEach(domain => {
      if (!healthReports[domain.id] && !loadingHealth[domain.id]) {
        setLoadingHealth(prev => ({ ...prev, [domain.id]: true }))
        api.getDomainHealth(domain.id, { refresh: false })
          .then(report => {
            setHealthReports(prev => ({ ...prev, [domain.id]: report }))
          })
          .catch(() => {})
          .finally(() => {
            setLoadingHealth(prev => ({ ...prev, [domain.id]: false }))
          })
      }
    })
  }, [domains])

  const handleRefresh = useCallback(async (id: number) => {
    setRefreshingId(id)
    try {
      await refreshDomain(id)
      showToast('Intel updated', 'success')
      setLastRefreshTime(new Date())
    } catch { showToast('Update failed', 'error') }
    finally { setRefreshingId(null) }
  }, [refreshDomain, showToast])

  // Refresh All Domains
  const handleRefreshAll = useCallback(async () => {
    if (refreshingAll) return
    setRefreshingAll(true)
    try {
      const result = await api.refreshAllDomains()
      
      // Refresh the domain list to get updated data
      await checkAuth()
      
      // Show appropriate message based on changes
      if (result.changes.length > 0) {
        const takenCount = result.changes.filter(c => c.change === 'became_taken').length
        const availableCount = result.changes.filter(c => c.change === 'became_available').length
        
        if (takenCount > 0 && availableCount > 0) {
          showToast(`${result.checked} domains checked. ${availableCount} became available, ${takenCount} were taken!`, 'success')
        } else if (takenCount > 0) {
          showToast(`${result.checked} domains checked. ${takenCount} domain(s) were registered!`, 'warning')
        } else if (availableCount > 0) {
          showToast(`${result.checked} domains checked. ${availableCount} domain(s) are now available!`, 'success')
        }
      } else {
        showToast(`All ${result.checked} domains checked. No status changes.`, 'success')
      }
      
      setLastRefreshTime(new Date())
    } catch (err: any) {
      showToast(err.message || 'Refresh failed', 'error')
    } finally {
      setRefreshingAll(false)
    }
  }, [refreshingAll, checkAuth, showToast])

  // Auto-refresh available domains every 2 minutes for Tycoon users
  useEffect(() => {
    const hasAvailableDomains = domains?.some(d => d.is_available)
    const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
    const isTycoon = tierName.toLowerCase() === 'tycoon'
    
    // Only auto-refresh if user is Tycoon and has available domains
    if (!isTycoon || !hasAvailableDomains) return
    
    const interval = setInterval(async () => {
      // Silently refresh all available domains to catch status changes
      try {
        await api.refreshAllDomains()
        await checkAuth() // Refresh domain list
      } catch {
        // Silent fail - don't show error for background refresh
      }
    }, 2 * 60 * 1000) // 2 minutes
    
    return () => clearInterval(interval)
  }, [domains, subscription, checkAuth])

  const handleDelete = useCallback(async (id: number, name: string) => {
    if (!confirm(`Drop target: ${name}?`)) return
    setDeletingId(id)
    try {
      await deleteDomain(id)
      showToast('Target dropped', 'success')
    } catch { showToast('Failed', 'error') }
    finally { setDeletingId(null) }
  }, [deleteDomain, showToast])

  const handleToggleNotify = useCallback(async (id: number, current: boolean) => {
    setTogglingNotifyId(id)
    try {
      await api.updateDomainNotify(id, !current)
      updateDomain(id, { notify_on_available: !current })
      showToast(!current ? 'Alerts armed' : 'Alerts disarmed', 'success')
    } catch { showToast('Failed', 'error') }
    finally { setTogglingNotifyId(null) }
  }, [updateDomain, showToast])

  const handleHealthCheck = useCallback(async (id: number) => {
    if (loadingHealth[id]) return
    setLoadingHealth(prev => ({ ...prev, [id]: true }))
    try {
      const report = await api.getDomainHealth(id, { refresh: true })
      setHealthReports(prev => ({ ...prev, [id]: report }))
    } catch {}
    finally { setLoadingHealth(prev => ({ ...prev, [id]: false })) }
  }, [loadingHealth])

  // Load health
  useEffect(() => {
    const load = async () => {
      if (!domains?.length) return
      try {
        const data = await api.getDomainsHealthCache()
        if (data?.reports) setHealthReports(prev => ({ ...prev, ...data.reports }))
      } catch {}
    }
    load()
  }, [domains])

  // Selected domain for detail view
  const selectedDomainData = selectedDomain ? domains?.find(d => d.id === selectedDomain) : null
  const selectedHealth = selectedDomain ? healthReports[selectedDomain] : null

  // Mobile Nav
  const mobileNavItems = [
    { href: '/terminal/hunt', label: 'Hunt', icon: Crosshair, active: false },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: true },
    { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase, active: false },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: false },
  ]
  
  const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap
  
  const drawerNavSections = [
    {
      title: 'Discover',
      items: [
        { href: '/terminal/hunt', label: 'Hunt', icon: Crosshair },
        { href: '/terminal/intel', label: 'Intel', icon: TrendingUp },
      ]
    },
    {
      title: 'Manage',
      items: [
        { href: '/terminal/watchlist', label: 'Watchlist', icon: Eye, active: true },
        { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase },
        { href: '/terminal/sniper', label: 'Sniper', icon: Target },
      ]
    },
    {
      title: 'Monetize',
      items: [
        { href: '/terminal/yield', label: 'Yield', icon: Coins },
        { 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">
                <Eye className="w-4 h-4 text-accent" />
                <span className="text-sm font-mono text-white font-bold">Watchlist</span>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={handleRefreshAll}
                  disabled={refreshingAll || !stats.total}
                  className="flex items-center gap-1 px-2 py-1.5 border border-white/10 text-white/60 text-[10px] font-bold uppercase disabled:opacity-50"
                >
                  <RefreshCw className={clsx("w-3 h-3", refreshingAll && "animate-spin")} />
                </button>
                <button
                  onClick={() => setShowAddModal(true)}
                  className="flex items-center gap-1.5 px-3 py-1.5 bg-accent text-black text-[10px] font-bold uppercase"
                >
                  <Plus className="w-3.5 h-3.5" />
                  Add
                </button>
              </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 text-center">
                <div className="text-lg font-bold text-white tabular-nums">{stats.total}<span className="text-white/30">/{formatLimit(maxWatchlist)}</span></div>
                <div className="text-[8px] font-mono text-white/30 uppercase">Tracked</div>
              </div>
              <div className="bg-accent/[0.05] border border-accent/20 p-2 text-center">
                <div className="text-lg font-bold text-accent tabular-nums">{stats.available}</div>
                <div className="text-[8px] font-mono text-accent/60 uppercase">Available</div>
              </div>
              <div className="bg-orange-500/[0.05] border border-orange-500/20 p-2 text-center">
                <div className="text-lg font-bold text-orange-400 tabular-nums">{stats.expiring}</div>
                <div className="text-[8px] font-mono text-orange-400/60 uppercase">Expiring</div>
              </div>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DESKTOP HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="hidden lg:block px-10 pt-10 pb-6">
          <div className="flex items-end justify-between gap-8">
            <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">Watchlist</span>
              </div>
              
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em] text-white">
                Watchlist
              </h1>
              <p className="text-sm text-white/40 font-mono mt-2 max-w-md">
                Track domains you want. Get alerts when they become available or expire.
              </p>
            </div>
            
            <div className="flex items-center gap-8">
              <div className="text-right">
                <div className="text-2xl font-bold text-white font-mono">{stats.total}<span className="text-white/30">/{formatLimit(maxWatchlist)}</span></div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Tracked</div>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold text-accent font-mono">{stats.available}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Available</div>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold text-orange-400 font-mono">{stats.expiring}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Expiring</div>
              </div>
              <div className="pl-6 border-l border-white/10 flex items-center gap-3">
                <button
                  onClick={handleRefreshAll}
                  disabled={refreshingAll || !stats.total}
                  className="flex items-center gap-2 px-4 py-3 border border-white/10 text-white/60 text-xs font-bold uppercase tracking-wider hover:bg-white/5 hover:text-white transition-colors disabled:opacity-50"
                  title={lastRefreshTime ? `Last refresh: ${lastRefreshTime.toLocaleTimeString()}` : 'Refresh all domains'}
                >
                  <RefreshCw className={clsx("w-4 h-4", refreshingAll && "animate-spin")} />
                  {refreshingAll ? 'Checking...' : 'Refresh All'}
                </button>
                <button
                  onClick={() => setShowAddModal(true)}
                  className="flex items-center gap-2 px-5 py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white transition-colors"
                >
                  <Plus className="w-4 h-4" />
                  Add Domain
                </button>
              </div>
            </div>
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* FILTERS */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-4 border-b border-white/[0.08] bg-white/[0.01]">
          <div className="flex items-center gap-2 overflow-x-auto">
            {[
              { value: 'all', label: 'All', count: stats.total },
              { value: 'available', label: 'Available', count: stats.available },
              { value: 'expiring', label: 'Expiring', count: stats.expiring },
            ].map((item) => (
              <button
                key={item.value}
                onClick={() => setFilter(item.value as typeof filter)}
                className={clsx(
                  "shrink-0 px-3 py-2 text-[10px] font-mono uppercase tracking-wider border transition-colors",
                  filter === item.value 
                    ? "bg-white/10 text-white border-white/20" 
                    : "text-white/40 border-transparent hover:text-white/60"
                )}
              >
                {item.label} ({item.count})
              </button>
            ))}
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DOMAIN LIST */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-4 pb-28 lg:pb-10">
          {!filteredDomains.length ? (
            <div className="text-center py-24 border border-dashed border-white/[0.08] bg-white/[0.01]">
              <Eye className="w-16 h-16 text-white/5 mx-auto mb-6" />
              <p className="text-white/50 text-sm font-mono uppercase tracking-widest font-bold">No domains in watchlist</p>
              <p className="text-white/20 text-xs font-mono mt-3 uppercase tracking-wider max-w-sm mx-auto leading-relaxed">
                Add a domain to start monitoring availability and expiry
              </p>
            </div>
          ) : (
            <div className="border border-white/[0.08] bg-[#020202] overflow-hidden">
                {/* Desktop Table Header */}
                <div className="hidden lg:grid grid-cols-[1fr_100px_100px_100px_80px_180px] gap-6 px-6 py-4 text-[10px] font-mono text-white/40 uppercase tracking-[0.15em] border-b border-white/[0.08] bg-white/[0.02]">
                  <button onClick={() => handleSortWatch('domain')} className="flex items-center gap-2 hover:text-white transition-colors text-left">
                    <span className={clsx(sortField === 'domain' && "text-accent font-bold")}>Domain</span>
                    {sortField === 'domain' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                  </button>
                  <button onClick={() => handleSortWatch('status')} className="flex items-center gap-2 justify-center hover:text-white transition-colors">
                    <span className={clsx(sortField === 'status' && "text-accent font-bold")}>Status</span>
                    {sortField === 'status' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                  </button>
                  <button onClick={() => handleSortWatch('health')} className="flex items-center gap-2 justify-center hover:text-white transition-colors">
                    <span className={clsx(sortField === 'health' && "text-accent font-bold")}>Health</span>
                    {sortField === 'health' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                  </button>
                  <button onClick={() => handleSortWatch('expiry')} className="flex items-center gap-2 justify-center hover:text-white transition-colors">
                    <span className={clsx(sortField === 'expiry' && "text-accent font-bold")}>Expiry</span>
                    {sortField === 'expiry' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                  </button>
                  <div className="text-center">Alert</div>
                  <div className="text-right">Actions</div>
                </div>
                
                {/* Table Body */}
                <div className="divide-y divide-white/[0.04]">
                
              {filteredDomains.map((domain) => {
                const health = healthReports[domain.id]
                const healthStatus = health?.status || 'unknown'
                const config = healthConfig[healthStatus]
                const days = getDaysUntilExpiry(domain.expiration_date)
                
                // Domain status display config (consistent with DropsTab)
                const domainStatus = domain.status || (domain.is_available ? 'available' : 'taken')
                const statusConfig = {
                  available: { label: 'AVAIL', color: 'text-accent', bg: 'bg-accent/5 border-accent/20' },
                  dropping_soon: { label: 'TRANSITION', color: 'text-amber-400', bg: 'bg-amber-400/5 border-amber-400/20' },
                  taken: { label: 'TAKEN', color: 'text-white/40', bg: 'bg-white/5 border-white/10' },
                  error: { label: 'ERROR', color: 'text-rose-400', bg: 'bg-rose-400/5 border-rose-400/20' },
                  unknown: { label: 'CHECK', color: 'text-white/30', bg: 'bg-white/5 border-white/5' },
                }[domainStatus] || { label: 'UNKNOWN', color: 'text-white/30', bg: 'bg-white/5 border-white/5' }
                
                return (
                  <div
                    key={domain.id}
                    className="bg-[#020202] hover:bg-white/[0.02] transition-all"
                  >
                    {/* Mobile Row */}
                    <div className={clsx("lg:hidden p-5", domain.is_available && "bg-accent/[0.02]")}>
                      <div className="flex items-start justify-between gap-4 mb-4">
                        <div className="min-w-0">
                          <button 
                            onClick={() => openAnalyze(domain)} 
                            className="text-lg font-bold text-white font-mono truncate block text-left hover:text-accent transition-colors"
                          >
                            {domain.name}
                          </button>
                          <div className="flex items-center gap-2 mt-2 text-[10px] font-mono text-white/30 uppercase tracking-wider">
                            <span className="bg-white/5 px-2 py-0.5 border border-white/5">{domain.registrar || 'Unknown'}</span>
                            {days !== null && days <= 30 && days > 0 && (
                              <span className="text-orange-400 font-bold">{days}d left</span>
                            )}
                          </div>
                        </div>

                        <div className="text-right shrink-0">
                          <div className={clsx(
                            "text-[10px] font-mono px-2 py-0.5 mt-1 inline-block border",
                            statusConfig.color, statusConfig.bg
                          )}>
                            {statusConfig.label}
                          </div>
                        </div>
                      </div>
                      
                      {/* Actions */}
                      <div className="flex gap-2">
                        {domain.is_available ? (
                          <a
                            href={`https://www.namecheap.com/domains/registration/results/?domain=${domain.name}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex-1 h-12 text-xs font-black uppercase tracking-widest flex items-center justify-center gap-2 bg-accent text-black hover:bg-white transition-all"
                          >
                            Buy
                          </a>
                        ) : (
                          <button
                            onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                            disabled={togglingNotifyId === domain.id}
                            className={clsx(
                              "flex-1 h-12 text-xs font-bold uppercase tracking-widest border flex items-center justify-center gap-2 transition-all",
                              domain.notify_on_available 
                                ? "border-accent bg-accent/5 text-accent" 
                                : "border-white/10 text-white/50 hover:bg-white/5"
                            )}
                          >
                            {togglingNotifyId === domain.id ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : domain.notify_on_available ? (
                              <Bell className="w-4 h-4" />
                            ) : (
                              <BellOff className="w-4 h-4" />
                            )}
                            {domain.notify_on_available ? 'Alert ON' : 'Alert'}
                          </button>
                        )}
                        
                        <button
                          onClick={() => openAnalyze(domain)}
                          className="w-14 h-12 border border-white/10 text-white/50 flex items-center justify-center hover:text-accent hover:border-accent/30 hover:bg-accent/5 transition-all"
                        >
                          <Shield className="w-5 h-5" />
                        </button>
                        
                        <button
                          onClick={() => handleDelete(domain.id, domain.name)}
                          disabled={deletingId === domain.id}
                          className="w-14 h-12 border border-white/10 text-white/50 flex items-center justify-center hover:text-rose-400 hover:border-rose-400/30 hover:bg-rose-400/5 transition-all"
                        >
                          {deletingId === domain.id ? (
                            <Loader2 className="w-5 h-5 animate-spin" />
                          ) : (
                            <Trash2 className="w-5 h-5" />
                          )}
                        </button>
                      </div>
                    </div>
                    
                    {/* Desktop Row */}
                    <div className={clsx(
                      "hidden lg:grid grid-cols-[1fr_100px_100px_100px_80px_180px] gap-6 items-center px-6 py-4 group transition-all",
                      domain.is_available ? "bg-accent/[0.02]" : ""
                    )}>
                      {/* Domain */}
                      <div className="flex items-center gap-3 min-w-0">
                        <button
                          onClick={() => openAnalyze(domain)}
                          className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors text-left"
                          title="Analyze"
                        >
                          {domain.name}
                        </button>
                        <div className="flex items-center gap-2 text-[9px] font-mono text-white/20 uppercase tracking-wider opacity-0 group-hover:opacity-100 transition-opacity">
                          <span>{domain.registrar || 'Unknown'}</span>
                        </div>
                      </div>
                      
                      {/* Status */}
                      <div className="flex justify-center">
                        <span className={clsx(
                          "text-[10px] font-mono font-bold uppercase px-2.5 py-1.5 border",
                          statusConfig.color, statusConfig.bg
                        )}>
                          {statusConfig.label}
                        </span>
                      </div>
                      
                      {/* Health */}
                      <div className="flex justify-center">
                        <button
                          onClick={() => { setSelectedDomain(domain.id); handleHealthCheck(domain.id) }}
                          className={clsx(
                            "flex items-center gap-1.5 px-2.5 py-1.5 text-[10px] font-mono uppercase border transition-colors hover:opacity-80",
                            config.color, "border-white/10"
                          )}
                        >
                          {loadingHealth[domain.id] ? (
                            <Loader2 className="w-3 h-3 animate-spin" />
                          ) : (
                            <>
                              <Activity className="w-3 h-3" />
                              {config.label}
                            </>
                          )}
                        </button>
                      </div>
                      
                      {/* Expires */}
                      <div className="text-center text-sm font-mono">
                        {days !== null && days <= 30 && days > 0 ? (
                          <span className="text-orange-400 font-bold">{days}d</span>
                        ) : (
                          <span className="text-white/50">{formatExpiryDate(domain.expiration_date)}</span>
                        )}
                      </div>
                      
                      {/* Alert */}
                      <div className="flex justify-center">
                        <button
                          onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                          disabled={togglingNotifyId === domain.id}
                          className={clsx(
                            "w-10 h-10 flex items-center justify-center border transition-all",
                            domain.notify_on_available 
                              ? "text-accent border-accent/30 bg-accent/10" 
                              : "text-white/20 border-white/10 hover:text-white/40 hover:bg-white/5"
                          )}
                        >
                          {togglingNotifyId === domain.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : domain.notify_on_available ? (
                            <Bell className="w-4 h-4" />
                          ) : (
                            <BellOff className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                      
                      {/* Actions */}
                      <div className="flex items-center justify-end gap-2 opacity-40 group-hover:opacity-100 transition-all">
                        {domain.is_available ? (
                          <a
                            href={`https://www.namecheap.com/domains/registration/results/?domain=${domain.name}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="h-10 px-5 bg-accent text-black text-[10px] font-black uppercase tracking-widest flex items-center gap-2 hover:bg-white transition-colors"
                          >
                            <ShoppingCart className="w-4 h-4" />
                            Buy
                          </a>
                        ) : (
                          <>
                            <button
                              onClick={() => handleRefresh(domain.id)}
                              disabled={refreshingId === domain.id}
                              title="Refresh"
                              className="w-10 h-10 flex items-center justify-center text-white/40 hover:text-white border border-white/10 hover:bg-white/5 transition-all"
                            >
                              <RefreshCw className={clsx("w-4 h-4", refreshingId === domain.id && "animate-spin")} />
                            </button>
                            <button
                              onClick={() => openAnalyze(domain)}
                              title="Analyze"
                              className="w-10 h-10 flex items-center justify-center text-white/40 hover:text-accent border border-white/10 hover:bg-accent/10 hover:border-accent/20 transition-all"
                            >
                              <Shield className="w-4 h-4" />
                            </button>
                          </>
                        )}
                        <button
                          onClick={() => handleDelete(domain.id, domain.name)}
                          disabled={deletingId === domain.id}
                          title="Remove"
                          className="w-10 h-10 flex items-center justify-center text-white/40 hover:text-rose-400 border border-white/10 hover:border-rose-400/20 hover:bg-rose-500/10 transition-all"
                        >
                          {deletingId === domain.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>
                  </div>
                )
              })}
                </div>
            </div>
          )}
        </section>

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

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* HEALTH MODAL */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {selectedDomainData && (
          <div 
            className="fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/80" 
            onClick={() => setSelectedDomain(null)}
          >
            <div 
              className="w-full max-w-md bg-[#0A0A0A] border border-white/[0.08]" 
              onClick={(e) => e.stopPropagation()}
            >
              {/* Header */}
              <div className="flex items-center justify-between px-4 py-3 border-b border-white/[0.08]">
                <div className="flex items-center gap-2">
                  <Activity className="w-4 h-4 text-accent" />
                  <span className="text-xs font-mono text-accent uppercase tracking-wider">Health Report</span>
                </div>
                <button onClick={() => setSelectedDomain(null)} className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40 hover:text-white">
                  <X className="w-4 h-4" />
                </button>
              </div>
              
              {/* Content */}
              <div className="p-4">
                {/* Domain */}
                <div className="mb-4">
                  <h3 className="text-base font-bold text-white font-mono">{selectedDomainData.name}</h3>
                  <div className="flex items-center gap-2 mt-2">
                    <span className={clsx(
                      "text-[10px] font-mono font-bold uppercase px-2 py-1 border",
                      healthConfig[selectedHealth?.status || 'unknown'].bg,
                      healthConfig[selectedHealth?.status || 'unknown'].color
                    )}>
                      {healthConfig[selectedHealth?.status || 'unknown'].label}
                    </span>
                    {selectedHealth?.score !== undefined && (
                      <span className="text-[10px] font-mono text-white/40">Score: {selectedHealth.score}/100</span>
                    )}
                  </div>
                </div>
                
                {/* Checks */}
                {selectedHealth ? (
                  <div className="space-y-px mb-4 border border-white/[0.08]">
                    {/* DNS */}
                    <div className="flex items-center justify-between px-3 py-2 bg-[#020202]">
                      <span className="text-xs font-mono text-white/60">DNS</span>
                      {selectedHealth.dns?.has_a || selectedHealth.dns?.has_ns ? (
                        <div className="flex items-center gap-1">
                          <CheckCircle2 className="w-4 h-4 text-accent" />
                          <span className="text-[10px] font-mono text-accent">OK</span>
                        </div>
                      ) : (
                        <div className="flex items-center gap-1">
                          <XCircle className="w-4 h-4 text-rose-400" />
                          <span className="text-[10px] font-mono text-rose-400">FAIL</span>
                        </div>
                      )}
                    </div>
                    
                    {/* HTTP */}
                    <div className="flex items-center justify-between px-3 py-2 bg-[#020202]">
                      <span className="text-xs font-mono text-white/60">HTTP</span>
                      {selectedHealth.http?.is_reachable ? (
                        <div className="flex items-center gap-1">
                          <CheckCircle2 className="w-4 h-4 text-accent" />
                          <span className="text-[10px] font-mono text-accent">OK</span>
                        </div>
                      ) : (
                        <div className="flex items-center gap-1">
                          <XCircle className="w-4 h-4 text-rose-400" />
                          <span className="text-[10px] font-mono text-rose-400">{selectedHealth.http?.error || 'FAIL'}</span>
                        </div>
                      )}
                    </div>
                    
                    {/* SSL */}
                    <div className="flex items-center justify-between px-3 py-2 bg-[#020202]">
                      <span className="text-xs font-mono text-white/60">SSL</span>
                      {selectedHealth.ssl?.has_certificate ? (
                        <div className="flex items-center gap-1">
                          <CheckCircle2 className="w-4 h-4 text-accent" />
                          <span className="text-[10px] font-mono text-accent">VALID</span>
                        </div>
                      ) : (
                        <div className="flex items-center gap-1">
                          <XCircle className="w-4 h-4 text-rose-400" />
                          <span className="text-[10px] font-mono text-rose-400">MISSING</span>
                        </div>
                      )}
                    </div>
                    
                    {/* Parked */}
                    <div className="flex items-center justify-between px-3 py-2 bg-[#020202]">
                      <span className="text-xs font-mono text-white/60">NOT PARKED</span>
                      {!selectedHealth.dns?.is_parked && !selectedHealth.http?.is_parked ? (
                        <div className="flex items-center gap-1">
                          <CheckCircle2 className="w-4 h-4 text-accent" />
                          <span className="text-[10px] font-mono text-accent">OK</span>
                        </div>
                      ) : (
                        <div className="flex items-center gap-1">
                          <AlertTriangle className="w-4 h-4 text-amber-400" />
                          <span className="text-[10px] font-mono text-amber-400">PARKED</span>
                        </div>
                      )}
                    </div>
                  </div>
                ) : (
                  <div className="py-8 text-center text-white/30 text-xs font-mono mb-4 border border-white/[0.08] bg-[#020202]">
                    Run health check to see results
                  </div>
                )}
                
                {/* Refresh Button */}
                <button
                  onClick={() => handleHealthCheck(selectedDomainData.id)}
                  disabled={loadingHealth[selectedDomainData.id]}
                  className="w-full py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white transition-colors flex items-center justify-center gap-2"
                >
                  {loadingHealth[selectedDomainData.id] ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <>
                      <RefreshCw className="w-4 h-4" />
                      Run Check
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        )}
      </main>
      
      {/* ADD MODAL */}
      {showAddModal && (
        <AddModal 
          onClose={() => setShowAddModal(false)} 
          onAdd={handleAdd}
        />
      )}
      
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
    </div>
  )
}
