'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api, DomainHealthReport, HealthStatus } from '@/lib/api'
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
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

// ============================================================================
// 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 [newDomain, setNewDomain] = useState('')
  const [adding, setAdding] = useState(false)
  const [searchFocused, setSearchFocused] = useState(false)
  const [refreshingId, setRefreshingId] = useState<number | null>(null)
  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')
  
  // Mobile Menu
  const [menuOpen, setMenuOpen] = useState(false)

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

  // Stats
  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 []
    return 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((a, b) => {
      if (a.is_available && !b.is_available) return -1
      if (!a.is_available && b.is_available) return 1
      return a.name.localeCompare(b.name)
    })
  }, [domains, filter])

  // Handlers
  const handleAdd = useCallback(async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newDomain.trim()) return
    const domainName = newDomain.trim().toLowerCase()
    setAdding(true)
    try {
      await addDomain(domainName)
      showToast(`Added: ${domainName}`, 'success')
      setNewDomain('')
    } catch (err: any) {
      showToast(err.message || 'Failed', 'error')
    } finally {
      setAdding(false)
    }
  }, [newDomain, 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')
    } catch { showToast('Update failed', 'error') }
    finally { setRefreshingId(null) }
  }, [refreshDomain, showToast])

  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/radar', label: 'Radar', icon: Target, active: false },
    { href: '/terminal/market', label: 'Market', icon: Gavel, active: false },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: true },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: false },
  ]
  
  const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap
  
  const drawerNavSections = [
    {
      title: 'Discover',
      items: [
        { href: '/terminal/radar', label: 'Radar', icon: Target },
        { href: '/terminal/market', label: 'Market', icon: Gavel },
        { href: '/terminal/intel', label: 'Intel', icon: TrendingUp },
      ]
    },
    {
      title: 'Manage',
      items: [
        { href: '/terminal/watchlist', label: 'Watchlist', icon: Eye },
        { href: '/terminal/sniper', label: 'Sniper', icon: Target },
      ]
    },
    {
      title: 'Monetize',
      items: [
        { href: '/terminal/yield', label: 'Yield', icon: Coins, isNew: true },
        { href: '/terminal/listing', label: 'For Sale', icon: Tag },
      ]
    }
  ]

  return (
    <div className="min-h-screen bg-[#020202]">
      {/* Desktop Sidebar */}
      <div className="hidden lg:block">
        <Sidebar />
      </div>
      
      {/* Main Content */}
      <main className="lg:pl-[240px]">
        
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <header 
          className="lg:hidden sticky top-0 z-40 bg-[#020202]/95 backdrop-blur-md border-b border-white/[0.08]" 
          style={{ paddingTop: 'env(safe-area-inset-top)' }}
        >
          <div className="px-4 py-3">
            {/* Top Row */}
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Watchlist</span>
              </div>
              <div className="flex items-center gap-2 text-[10px] font-mono text-white/40">
                <span>{stats.total} domains</span>
                <span className="text-accent">{stats.available} available</span>
              </div>
            </div>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-3 gap-2">
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{stats.total}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Tracked</div>
              </div>
              <div className="bg-accent/[0.05] border border-accent/20 p-2">
                <div className="text-lg font-bold text-accent tabular-nums">{stats.available}</div>
                <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Available</div>
              </div>
              <div className="bg-orange-500/[0.05] border border-orange-500/20 p-2">
                <div className="text-lg font-bold text-orange-400 tabular-nums">{stats.expiring}</div>
                <div className="text-[9px] font-mono text-orange-400/60 uppercase tracking-wider">Expiring</div>
              </div>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* ADD DOMAIN */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-4">
          <form onSubmit={handleAdd} className="relative">
            <div className={clsx(
              "flex items-center border-2 transition-all duration-200",
              searchFocused 
                ? "border-accent/50 bg-accent/[0.02]" 
                : "border-white/[0.08] bg-white/[0.02]"
            )}>
              <Plus className={clsx(
                "w-4 h-4 ml-4 transition-colors",
                searchFocused ? "text-accent" : "text-white/30"
              )} />
              <input
                type="text"
                value={newDomain}
                onChange={(e) => setNewDomain(e.target.value)}
                onFocus={() => setSearchFocused(true)}
                onBlur={() => setSearchFocused(false)}
                placeholder="Add domain to watch..."
                className="flex-1 bg-transparent px-3 py-3 text-sm text-white placeholder:text-white/20 outline-none font-mono"
              />
              <button
                type="submit"
                disabled={adding || !newDomain.trim()}
                className="h-full px-4 py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white transition-colors disabled:opacity-30 flex items-center gap-2"
              >
                {adding ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Add'}
              </button>
            </div>
          </form>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* FILTERS */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 pb-4 border-b border-white/[0.08]">
          <div className="flex items-center gap-1">
            {[
              { 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(
                  "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>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DESKTOP HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="hidden lg:block px-10 pt-10 pb-6">
          <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6">
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Domain Surveillance</span>
              </div>
              
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em]">
                <span className="text-white">Watchlist</span>
                <span className="text-white/30 ml-3 font-mono text-[2rem]">{stats.total}</span>
              </h1>
            </div>
            
            <div className="flex gap-8">
              <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>
          </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-16 border border-dashed border-white/[0.08]">
              <Eye className="w-8 h-8 text-white/10 mx-auto mb-3" />
              <p className="text-white/40 text-sm font-mono">No domains in your watchlist</p>
              <p className="text-white/25 text-xs font-mono mt-1">Add a domain above to start monitoring</p>
            </div>
          ) : (
            <div className="space-y-px bg-white/[0.04] border border-white/[0.08]">
              {filteredDomains.map((domain) => {
                const health = healthReports[domain.id]
                const healthStatus = health?.status || 'unknown'
                const config = healthConfig[healthStatus]
                const days = getDaysUntilExpiry(domain.expiration_date)
                
                return (
                  <div
                    key={domain.id}
                    className="bg-[#020202] hover:bg-white/[0.02] transition-all"
                  >
                    {/* Mobile Row */}
                    <div className="lg:hidden p-3">
                      <div className="flex items-start justify-between gap-3 mb-2">
                        <div className="flex items-center gap-3 min-w-0 flex-1">
                          <div className={clsx(
                            "w-8 h-8 flex items-center justify-center border shrink-0",
                            domain.is_available 
                              ? "bg-accent/10 border-accent/20" 
                              : "bg-white/[0.02] border-white/[0.06]"
                          )}>
                            {domain.is_available ? (
                              <CheckCircle2 className="w-4 h-4 text-accent" />
                            ) : (
                              <Eye className="w-4 h-4 text-white/30" />
                            )}
                          </div>
                          <div className="min-w-0 flex-1">
                            <div className="text-sm font-bold text-white font-mono truncate">{domain.name}</div>
                            <div className="text-[10px] font-mono text-white/30">
                              {domain.registrar || 'Unknown registrar'}
                            </div>
                          </div>
                        </div>
                        
                        <div className="text-right shrink-0">
                          <div className={clsx(
                            "text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 mb-1",
                            domain.is_available ? "text-accent bg-accent/10" : "text-white/30 bg-white/5"
                          )}>
                            {domain.is_available ? 'AVAIL' : 'TAKEN'}
                          </div>
                          <button
                            onClick={() => { setSelectedDomain(domain.id); handleHealthCheck(domain.id) }}
                            className="flex items-center gap-1"
                          >
                            {loadingHealth[domain.id] ? (
                              <Loader2 className="w-3 h-3 animate-spin text-white/30" />
                            ) : (
                              <>
                                <Activity className={clsx("w-3 h-3", config.color)} />
                                <span className={clsx("text-[9px] font-mono", config.color)}>{config.label}</span>
                              </>
                            )}
                          </button>
                        </div>
                      </div>
                      
                      {/* Actions */}
                      <div className="flex gap-2">
                        <button
                          onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                          disabled={togglingNotifyId === domain.id}
                          className={clsx(
                            "flex-1 py-2 text-[10px] font-bold uppercase tracking-wider border flex items-center justify-center gap-1.5 transition-all",
                            domain.notify_on_available 
                              ? "border-accent bg-accent/10 text-accent" 
                              : "border-white/[0.08] text-white/40"
                          )}
                        >
                          {togglingNotifyId === domain.id ? (
                            <Loader2 className="w-3 h-3 animate-spin" />
                          ) : domain.notify_on_available ? (
                            <Bell className="w-3 h-3" />
                          ) : (
                            <BellOff className="w-3 h-3" />
                          )}
                          Alert
                        </button>
                        
                        <button
                          onClick={() => handleRefresh(domain.id)}
                          disabled={refreshingId === domain.id}
                          className="px-4 py-2 border border-white/[0.08] text-white/40"
                        >
                          <RefreshCw className={clsx("w-4 h-4", refreshingId === domain.id && "animate-spin")} />
                        </button>
                        
                        <button
                          onClick={() => handleDelete(domain.id, domain.name)}
                          disabled={deletingId === domain.id}
                          className="px-4 py-2 border border-white/[0.08] text-white/40 hover:text-rose-400 hover:border-rose-400/20 hover:bg-rose-400/5"
                        >
                          {deletingId === domain.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>
                    
                    {/* Desktop Row */}
                    <div className="hidden lg:flex items-center justify-between p-3 gap-4 group">
                      <div className="flex items-center gap-3 min-w-0 flex-1">
                        <div className={clsx(
                          "w-8 h-8 flex items-center justify-center border shrink-0",
                          domain.is_available 
                            ? "bg-accent/10 border-accent/20" 
                            : "bg-white/[0.02] border-white/[0.06]"
                        )}>
                          {domain.is_available ? (
                            <CheckCircle2 className="w-4 h-4 text-accent" />
                          ) : (
                            <Eye className="w-4 h-4 text-white/30" />
                          )}
                        </div>
                        <div className="min-w-0">
                          <div className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors">{domain.name}</div>
                          <div className="text-[10px] font-mono text-white/30">
                            {domain.registrar || 'Unknown'}
                          </div>
                        </div>
                        <a href={`https://${domain.name}`} target="_blank" className="opacity-0 group-hover:opacity-50 hover:!opacity-100 transition-opacity ml-2">
                          <ExternalLink className="w-3.5 h-3.5 text-white/40" />
                        </a>
                      </div>
                      
                      {/* Status */}
                      <div className="w-20 shrink-0">
                        <span className={clsx(
                          "text-[10px] font-mono font-bold uppercase px-2 py-0.5",
                          domain.is_available ? "text-accent bg-accent/10" : "text-white/30 bg-white/5"
                        )}>
                          {domain.is_available ? 'AVAIL' : 'TAKEN'}
                        </span>
                      </div>
                      
                      {/* Health */}
                      <button
                        onClick={() => { setSelectedDomain(domain.id); handleHealthCheck(domain.id) }}
                        className="w-24 flex items-center gap-1.5 hover:opacity-80 transition-opacity shrink-0"
                      >
                        {loadingHealth[domain.id] ? (
                          <Loader2 className="w-3.5 h-3.5 animate-spin text-white/30" />
                        ) : (
                          <>
                            <Activity className={clsx("w-3.5 h-3.5", config.color)} />
                            <span className={clsx("text-xs font-mono", config.color)}>{config.label}</span>
                          </>
                        )}
                      </button>
                      
                      {/* Expires */}
                      <div className="w-24 text-xs font-mono text-white/50 shrink-0">
                        {days !== null && days <= 30 && days > 0 ? (
                          <span className="text-orange-400 font-bold">{days}d</span>
                        ) : (
                          formatExpiryDate(domain.expiration_date)
                        )}
                      </div>
                      
                      {/* Alert */}
                      <button
                        onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                        disabled={togglingNotifyId === domain.id}
                        className={clsx(
                          "w-8 h-8 flex items-center justify-center border transition-colors shrink-0",
                          domain.notify_on_available 
                            ? "text-accent border-accent/20 bg-accent/10" 
                            : "text-white/20 border-white/10 hover:text-white/40"
                        )}
                      >
                        {togglingNotifyId === domain.id ? (
                          <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        ) : domain.notify_on_available ? (
                          <Bell className="w-3.5 h-3.5" />
                        ) : (
                          <BellOff className="w-3.5 h-3.5" />
                        )}
                      </button>
                      
                      {/* Actions */}
                      <div className="flex items-center gap-1 shrink-0 opacity-50 group-hover:opacity-100 transition-opacity">
                        <button
                          onClick={() => handleRefresh(domain.id)}
                          disabled={refreshingId === domain.id}
                          className="w-7 h-7 flex items-center justify-center text-white/20 hover:text-white border border-white/10 hover:bg-white/5 transition-all"
                        >
                          <RefreshCw className={clsx("w-3.5 h-3.5", refreshingId === domain.id && "animate-spin")} />
                        </button>
                        <button
                          onClick={() => handleDelete(domain.id, domain.name)}
                          disabled={deletingId === domain.id}
                          className="w-7 h-7 flex items-center justify-center text-white/20 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-3.5 h-3.5 animate-spin" />
                          ) : (
                            <Trash2 className="w-3.5 h-3.5" />
                          )}
                        </button>
                      </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>
      
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
    </div>
  )
}
