'use client'

import { useEffect, useState, useMemo, useCallback, memo } from 'react'
import { useStore } from '@/lib/store'
import { api, DomainHealthReport, HealthStatus } from '@/lib/api'
import { TerminalLayout } from '@/components/TerminalLayout'
import { Toast, useToast } from '@/components/Toast'
import {
  Plus,
  Trash2,
  RefreshCw,
  Loader2,
  Bell,
  BellOff,
  ExternalLink,
  Eye,
  Sparkles,
  ArrowUpRight,
  X,
  Activity,
  Shield,
  AlertTriangle,
  ShoppingCart,
  HelpCircle,
  Search,
  Filter,
  CheckCircle2,
  Globe,
  Clock,
  Calendar,
  MoreVertical,
  ChevronDown,
  ArrowRight
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

// ============================================================================
// SHARED COMPONENTS
// ============================================================================

function Tooltip({ children, content }: { children: React.ReactNode; content: string }) {
  return (
    <div className="relative flex items-center group/tooltip w-fit">
      {children}
      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-zinc-900 border border-zinc-800 rounded text-[10px] text-zinc-300 whitespace-nowrap opacity-0 group-hover/tooltip:opacity-100 transition-opacity pointer-events-none z-50 shadow-xl">
        {content}
        {/* Arrow */}
        <div className="absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-zinc-800" />
      </div>
    </div>
  )
}

function StatCard({ 
  label, 
  value, 
  subValue, 
  icon: Icon, 
  trend 
}: { 
  label: string
  value: string | number
  subValue?: string
  icon: any
  trend?: 'up' | 'down' | 'neutral' | 'active'
}) {
  return (
    <div className="bg-zinc-900/40 border border-white/5 p-4 relative overflow-hidden group hover:border-white/10 transition-colors">
      <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
        <Icon className="w-16 h-16" />
      </div>
      <div className="relative z-10">
        <div className="flex items-center gap-2 text-zinc-400 mb-1">
          <Icon className="w-4 h-4" />
          <span className="text-xs font-medium uppercase tracking-wider">{label}</span>
        </div>
        <div className="flex items-baseline gap-2">
          <span className="text-2xl font-bold text-white tracking-tight">{value}</span>
          {subValue && <span className="text-xs text-zinc-500 font-medium">{subValue}</span>}
        </div>
        {trend && (
          <div className={clsx(
            "mt-2 text-[10px] font-medium px-1.5 py-0.5 w-fit rounded border",
            trend === 'up' && "text-emerald-400 border-emerald-400/20 bg-emerald-400/5",
            trend === 'down' && "text-rose-400 border-rose-400/20 bg-rose-400/5",
            trend === 'active' && "text-blue-400 border-blue-400/20 bg-blue-400/5 animate-pulse",
            trend === 'neutral' && "text-zinc-400 border-zinc-400/20 bg-zinc-400/5",
          )}>
            {trend === 'active' ? '● LIVE MONITORING' : trend === 'up' ? '▲ POSITIVE' : '▼ NEGATIVE'}
          </div>
        )}
      </div>
    </div>
  )
}

// Health status badge configuration
const healthStatusConfig: Record<HealthStatus, { 
  label: string
  color: string
  icon: typeof Activity
  description: string
  dot: string
}> = {
  healthy: { 
    label: 'Online', 
    color: 'text-emerald-400', 
    icon: Activity,
    description: 'Domain is active and reachable',
    dot: 'bg-emerald-400'
  },
  weakening: { 
    label: 'Issues', 
    color: 'text-amber-400', 
    icon: AlertTriangle,
    description: 'Warning signs detected',
    dot: 'bg-amber-400'
  },
  parked: { 
    label: 'Parked', 
    color: 'text-blue-400', 
    icon: ShoppingCart,
    description: 'Domain is parked/for sale',
    dot: 'bg-blue-400'
  },
  critical: { 
    label: 'Offline', 
    color: 'text-rose-400', 
    icon: AlertTriangle,
    description: 'Domain is offline/error',
    dot: 'bg-rose-400'
  },
  unknown: { 
    label: 'Unknown', 
    color: 'text-zinc-400', 
    icon: HelpCircle,
    description: 'Status unknown',
    dot: 'bg-zinc-600'
  },
}

type FilterStatus = 'watching' | 'portfolio' | 'available'

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

export default function WatchlistPage() {
  const { domains, addDomain, deleteDomain, refreshDomain, subscription } = useStore()
  const { toast, showToast, hideToast } = useToast()
  
  const [newDomain, setNewDomain] = useState('')
  const [adding, setAdding] = useState(false)
  const [refreshingId, setRefreshingId] = useState<number | null>(null)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [togglingNotifyId, setTogglingNotifyId] = useState<number | null>(null)
  const [filterStatus, setFilterStatus] = useState<FilterStatus>('watching')
  const [searchQuery, setSearchQuery] = useState('')
  
  // Health check state
  const [healthReports, setHealthReports] = useState<Record<number, DomainHealthReport>>({})
  const [loadingHealth, setLoadingHealth] = useState<Record<number, boolean>>({})
  const [selectedHealthDomainId, setSelectedHealthDomainId] = useState<number | null>(null)

  // Memoized stats
  const stats = useMemo(() => ({
    availableCount: domains?.filter(d => d.is_available).length || 0,
    watchingCount: domains?.filter(d => !d.is_available).length || 0,
    domainsUsed: domains?.length || 0,
    domainLimit: subscription?.domain_limit || 5,
  }), [domains, subscription?.domain_limit])

  const canAddMore = stats.domainsUsed < stats.domainLimit

  // Memoized filtered domains
  const filteredDomains = useMemo(() => {
    if (!domains) return []
    
    return domains.filter(domain => {
      if (searchQuery && !domain.name.toLowerCase().includes(searchQuery.toLowerCase())) {
        return false
      }
      if (filterStatus === 'available' && !domain.is_available) return false
      // 'portfolio' logic would go here
      return true
    })
  }, [domains, searchQuery, filterStatus])

  // Callbacks
  const handleAddDomain = useCallback(async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newDomain.trim()) return
    
    setAdding(true)
    try {
      await addDomain(newDomain.trim())
      setNewDomain('')
      showToast(`Added ${newDomain.trim()} to watchlist`, 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed to add domain', 'error')
    } finally {
      setAdding(false)
    }
  }, [newDomain, addDomain, showToast])

  const handleRefresh = useCallback(async (id: number) => {
    setRefreshingId(id)
    try {
      await refreshDomain(id)
      showToast('Domain status refreshed', 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed to refresh', 'error')
    } finally {
      setRefreshingId(null)
    }
  }, [refreshDomain, showToast])

  const handleDelete = useCallback(async (id: number, name: string) => {
    if (!confirm(`Remove ${name} from your watchlist?`)) return
    
    setDeletingId(id)
    try {
      await deleteDomain(id)
      showToast(`Removed ${name} from watchlist`, 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed to remove', 'error')
    } finally {
      setDeletingId(null)
    }
  }, [deleteDomain, showToast])

  const handleToggleNotify = useCallback(async (id: number, currentState: boolean) => {
    setTogglingNotifyId(id)
    try {
      await api.updateDomainNotify(id, !currentState)
      showToast(!currentState ? 'Notifications enabled' : 'Notifications disabled', 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed to update', 'error')
    } finally {
      setTogglingNotifyId(null)
    }
  }, [showToast])

  const handleHealthCheck = useCallback(async (domainId: number) => {
    if (loadingHealth[domainId]) return
    
    setLoadingHealth(prev => ({ ...prev, [domainId]: true }))
    try {
      const report = await api.getDomainHealth(domainId)
      setHealthReports(prev => ({ ...prev, [domainId]: report }))
      setSelectedHealthDomainId(domainId)
    } catch (err: any) {
      showToast(err.message || 'Health check failed', 'error')
    } finally {
      setLoadingHealth(prev => ({ ...prev, [domainId]: false }))
    }
  }, [loadingHealth, showToast])

  return (
    <TerminalLayout hideHeaderSearch={true}>
      <div className="relative font-sans text-zinc-100 selection:bg-emerald-500/30">
        {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
        
        {/* Ambient Background Glow */}
        <div className="fixed inset-0 pointer-events-none overflow-hidden">
          <div className="absolute top-0 right-1/4 w-[800px] h-[600px] bg-emerald-500/5 rounded-full blur-[120px] mix-blend-screen" />
          <div className="absolute bottom-0 left-1/4 w-[600px] h-[500px] bg-blue-500/5 rounded-full blur-[100px] mix-blend-screen" />
        </div>

        <div className="relative z-10 max-w-[1600px] mx-auto p-4 md:p-8 space-y-8">
          
          {/* Header Section */}
          <div className="flex flex-col md:flex-row justify-between items-start md:items-end gap-6 border-b border-white/5 pb-8">
            <div className="space-y-2">
              <div className="flex items-center gap-3">
                <div className="h-8 w-1 bg-emerald-500 rounded-full shadow-[0_0_10px_rgba(16,185,129,0.5)]" />
                <h1 className="text-3xl font-bold tracking-tight text-white">Watchlist</h1>
              </div>
              <p className="text-zinc-400 max-w-lg">
                Monitor availability, expiration dates, and health metrics for your critical domains.
              </p>
            </div>
            
            {/* Quick Stats Pills */}
            <div className="flex gap-2">
               <div className="px-3 py-1.5 rounded-full bg-white/5 border border-white/10 flex items-center gap-2 text-xs font-medium text-zinc-300">
                <div className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
                {stats.watchingCount} Active
              </div>
              <div className="px-3 py-1.5 rounded-full bg-white/5 border border-white/10 flex items-center gap-2 text-xs font-medium text-zinc-300">
                <Sparkles className="w-3.5 h-3.5 text-amber-400" />
                {stats.availableCount} Available
              </div>
            </div>
          </div>

          {/* Metric Grid */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <StatCard 
              label="Total Assets" 
              value={stats.domainsUsed} 
              subValue={`/ ${stats.domainLimit === -1 ? '∞' : stats.domainLimit}`}
              icon={Eye}
              trend="active"
            />
            <StatCard 
              label="Actionable" 
              value={stats.availableCount} 
              subValue="Domains"
              icon={Sparkles}
              trend={stats.availableCount > 0 ? 'up' : 'neutral'}
            />
            <StatCard 
              label="Monitoring" 
              value={stats.watchingCount} 
              subValue="Checks/hr"
              icon={Activity}
            />
             <StatCard 
              label="Plan Usage" 
              value={`${Math.round((stats.domainsUsed / (stats.domainLimit === -1 ? 100 : stats.domainLimit)) * 100)}%`} 
              subValue="Capacity"
              icon={Shield}
              trend={stats.domainsUsed >= stats.domainLimit ? 'down' : 'neutral'}
            />
          </div>

          {/* Control Bar */}
          <div className="sticky top-4 z-30 bg-black/80 backdrop-blur-md border border-white/10 rounded-xl p-2 flex flex-col md:flex-row gap-4 items-center justify-between shadow-2xl">
            {/* Filter Pills */}
            <div className="flex items-center gap-1 bg-white/5 p-1 rounded-lg">
              {(['watching', 'available'] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setFilterStatus(tab)}
                  className={clsx(
                    "px-4 py-1.5 rounded-md text-xs font-medium transition-all",
                    filterStatus === tab 
                      ? "bg-zinc-800 text-white shadow-sm" 
                      : "text-zinc-400 hover:text-zinc-200 hover:bg-white/5"
                  )}
                >
                  {tab.charAt(0).toUpperCase() + tab.slice(1)}
                </button>
              ))}
            </div>

            {/* Add Domain Input */}
            <form onSubmit={handleAddDomain} className="flex-1 max-w-md w-full relative group">
              <input
                type="text"
                value={newDomain}
                onChange={(e) => setNewDomain(e.target.value)}
                placeholder="Add domain to watch (e.g. apple.com)..."
                className="w-full bg-black/50 border border-white/10 rounded-lg pl-10 pr-12 py-2 text-sm text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 focus:ring-1 focus:ring-emerald-500/50 transition-all"
              />
              <Plus className="absolute left-3 top-2.5 w-4 h-4 text-zinc-500 group-focus-within:text-emerald-500 transition-colors" />
              <button 
                type="submit"
                disabled={adding || !newDomain.trim() || !canAddMore}
                className="absolute right-2 top-1.5 p-1 hover:bg-emerald-500/20 rounded text-zinc-500 hover:text-emerald-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {adding ? <Loader2 className="w-4 h-4 animate-spin" /> : <ArrowUpRight className="w-4 h-4" />}
              </button>
            </form>

            {/* Search Filter */}
             <div className="relative w-full md:w-64">
              <Search className="absolute left-3 top-2.5 w-4 h-4 text-zinc-500" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Filter watchlist..."
                className="w-full bg-black/50 border border-white/10 rounded-lg pl-9 pr-4 py-2 text-sm text-white placeholder:text-zinc-600 focus:outline-none focus:border-white/20 transition-all"
              />
            </div>
          </div>

          {/* Limit Warning */}
          {!canAddMore && (
            <div className="bg-amber-500/10 border border-amber-500/20 rounded-lg p-3 flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm text-amber-400">
                <AlertTriangle className="w-4 h-4" />
                <span>Limit reached. Upgrade plan to track more domains.</span>
              </div>
              <Link href="/pricing" className="text-xs font-bold text-amber-400 hover:text-amber-300 flex items-center gap-1 uppercase tracking-wide">
                Upgrade <ArrowUpRight className="w-3 h-3" />
              </Link>
            </div>
          )}

          {/* Data Grid */}
          <div className="bg-zinc-900/40 border border-white/5 rounded-xl overflow-hidden backdrop-blur-sm">
            {/* Table Header */}
            <div className="grid grid-cols-12 gap-4 px-6 py-3 bg-white/[0.02] border-b border-white/5 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">
              <div className="col-span-12 md:col-span-4">Domain</div>
              <div className="hidden md:block md:col-span-2 text-center">Status</div>
              <div className="hidden md:block md:col-span-2 text-center">Health</div>
              <div className="hidden md:block md:col-span-2 text-center">Alerts</div>
              <div className="hidden md:block md:col-span-2 text-right">Actions</div>
            </div>

            {filteredDomains.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-20 text-center">
                <div className="w-16 h-16 rounded-full bg-white/5 flex items-center justify-center mb-4">
                  <Eye className="w-8 h-8 text-zinc-600" />
                </div>
                <h3 className="text-lg font-medium text-white mb-1">
                  {searchQuery ? "No matches found" : "Watchlist is empty"}
                </h3>
                <p className="text-zinc-500 text-sm max-w-xs mx-auto mb-6">
                  {searchQuery ? "Try adjusting your filters." : "Start by adding domains you want to track above."}
                </p>
                {!searchQuery && (
                  <button 
                    onClick={() => document.querySelector('input')?.focus()}
                    className="text-emerald-400 text-sm hover:text-emerald-300 transition-colors flex items-center gap-2"
                  >
                    Add first domain <ArrowRight className="w-4 h-4" />
                  </button>
                )}
              </div>
            ) : (
              <div className="divide-y divide-white/5">
                {filteredDomains.map((domain) => {
                  const health = healthReports[domain.id]
                  const healthConfig = health ? healthStatusConfig[health.status] : null
                  
                  return (
                    <div key={domain.id} className="grid grid-cols-12 gap-4 px-6 py-4 items-center hover:bg-white/[0.04] transition-all group relative">
                      
                      {/* Mobile Layout (Visible only on mobile) */}
                      <div className="md:hidden col-span-12 space-y-3">
                         <div className="flex justify-between items-start">
                            <div>
                              <div className="font-mono font-bold text-white text-lg">{domain.name}</div>
                              <div className="flex items-center gap-2 mt-1">
                                <span className={clsx(
                                  "text-xs px-2 py-0.5 rounded-full border",
                                  domain.is_available 
                                    ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" 
                                    : "bg-zinc-800 text-zinc-400 border-zinc-700"
                                )}>
                                  {domain.is_available ? 'AVAILABLE' : 'TAKEN'}
                                </span>
                              </div>
                            </div>
                            <button
                              onClick={() => handleDelete(domain.id, domain.name)}
                              className="p-2 text-zinc-500 hover:text-rose-400 transition-colors"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                         </div>
                         
                         <div className="flex justify-between items-center pt-2 border-t border-white/5">
                            <button
                              onClick={() => handleHealthCheck(domain.id)}
                              className="text-xs text-zinc-400 flex items-center gap-1.5 hover:text-white"
                            >
                              <Activity className="w-3.5 h-3.5" />
                              Check Health
                            </button>
                            <button
                               onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                               className={clsx(
                                 "text-xs flex items-center gap-1.5",
                                 domain.notify_on_available ? "text-emerald-400" : "text-zinc-500"
                               )}
                            >
                              {domain.notify_on_available ? <Bell className="w-3.5 h-3.5" /> : <BellOff className="w-3.5 h-3.5" />}
                              {domain.notify_on_available ? 'Alerts On' : 'Alerts Off'}
                            </button>
                         </div>
                      </div>

                      {/* Desktop Layout */}
                      {/* Domain */}
                      <div className="hidden md:block col-span-4">
                        <div className="flex items-center gap-3">
                          <div className="relative">
                            <div className={clsx(
                              "w-2 h-2 rounded-full",
                              domain.is_available ? "bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.5)]" : "bg-zinc-600"
                            )} />
                            {domain.is_available && <div className="absolute inset-0 bg-emerald-500 rounded-full animate-ping opacity-50" />}
                          </div>
                          <span className="font-mono font-bold text-white text-[15px] tracking-tight">{domain.name}</span>
                        </div>
                      </div>

                      {/* Status */}
                      <div className="hidden md:flex col-span-2 justify-center">
                         <span className={clsx(
                            "text-[11px] font-medium px-2 py-0.5 rounded border uppercase tracking-wider",
                            domain.is_available 
                              ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" 
                              : "bg-zinc-800 text-zinc-400 border-zinc-700"
                          )}>
                            {domain.is_available ? 'Available' : 'Registered'}
                          </span>
                      </div>

                      {/* Health */}
                      <div className="hidden md:flex col-span-2 justify-center">
                        {healthConfig ? (
                           <Tooltip content={healthConfig.description}>
                            <button 
                              onClick={() => setSelectedHealthDomainId(domain.id)}
                              className={clsx(
                                "flex items-center gap-2 px-2 py-1 rounded hover:bg-white/5 transition-colors",
                                healthConfig.color
                              )}
                            >
                              <healthConfig.icon className="w-4 h-4" />
                              <span className="text-xs font-medium">{healthConfig.label}</span>
                            </button>
                          </Tooltip>
                        ) : (
                          <Tooltip content="Click to run health check">
                            <button 
                              onClick={() => handleHealthCheck(domain.id)}
                              disabled={loadingHealth[domain.id]}
                              className="text-zinc-600 hover:text-zinc-400 transition-colors"
                            >
                              {loadingHealth[domain.id] ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                              ) : (
                                <Activity className="w-4 h-4" />
                              )}
                            </button>
                          </Tooltip>
                        )}
                      </div>

                      {/* Alerts */}
                      <div className="hidden md:flex col-span-2 justify-center">
                         <Tooltip content={domain.notify_on_available ? "Notifications enabled" : "Notifications disabled"}>
                            <button
                              onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                              disabled={togglingNotifyId === domain.id}
                              className={clsx(
                                "p-1.5 rounded-lg transition-all",
                                domain.notify_on_available 
                                  ? "text-emerald-400 bg-emerald-400/10 hover:bg-emerald-400/20" 
                                  : "text-zinc-600 hover:text-zinc-400 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>
                         </Tooltip>
                      </div>

                      {/* Actions */}
                      <div className="hidden md:flex col-span-2 justify-end items-center gap-2">
                        <Tooltip content="Force refresh status">
                           <button
                            onClick={() => handleRefresh(domain.id)}
                            className={clsx(
                              "p-1.5 rounded-lg text-zinc-500 hover:text-white hover:bg-white/10 transition-colors",
                              refreshingId === domain.id && "animate-spin text-emerald-400"
                            )}
                          >
                            <RefreshCw className="w-4 h-4" />
                          </button>
                        </Tooltip>

                        <Tooltip content="Remove from watchlist">
                          <button
                            onClick={() => handleDelete(domain.id, domain.name)}
                            className="p-1.5 rounded-lg text-zinc-500 hover:text-rose-400 hover:bg-rose-400/10 transition-colors"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </Tooltip>

                        {domain.is_available && (
                           <Tooltip content="Register at Namecheap">
                            <a
                              href={`https://www.namecheap.com/domains/registration/results/?domain=${domain.name}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="ml-2 flex items-center gap-1.5 px-3 py-1.5 bg-emerald-500 text-white text-[11px] font-bold uppercase tracking-wider rounded hover:bg-emerald-400 transition-colors shadow-lg shadow-emerald-500/20"
                            >
                              Buy <ArrowRight className="w-3 h-3" />
                            </a>
                          </Tooltip>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </div>

        {/* Health Report Modal */}
        {selectedHealthDomainId && healthReports[selectedHealthDomainId] && (
          <HealthReportModal 
            report={healthReports[selectedHealthDomainId]} 
            onClose={() => setSelectedHealthDomainId(null)} 
          />
        )}
      </div>
    </TerminalLayout>
  )
}

// Health Report Modal Component - memoized
const HealthReportModal = memo(function HealthReportModal({ 
  report, 
  onClose 
}: { 
  report: DomainHealthReport
  onClose: () => void 
}) {
  const config = healthStatusConfig[report.status]
  const Icon = config.icon

  return (
    <div 
      className="fixed inset-0 z-[100] bg-black/80 backdrop-blur-sm flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div 
        className="w-full max-w-lg bg-[#0A0A0A] border border-white/10 rounded-2xl shadow-2xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-white/5 bg-white/[0.02]">
          <div className="flex items-center gap-3">
            <div className={clsx("p-2 rounded-lg bg-white/5 border border-white/10")}>
              <Icon className={clsx("w-5 h-5", config.color)} />
            </div>
            <div>
              <h3 className="font-mono font-bold text-lg text-white tracking-tight">{report.domain}</h3>
              <p className="text-xs text-zinc-500">{config.description}</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-full text-zinc-500 hover:text-white transition-colors">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Score */}
        <div className="p-6 border-b border-white/5">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs font-medium text-zinc-500 uppercase tracking-wider">Health Score</span>
            <span className={clsx(
              "text-2xl font-bold tabular-nums",
              report.score >= 70 ? "text-emerald-400" :
              report.score >= 40 ? "text-amber-400" : "text-rose-400"
            )}>
              {report.score}/100
            </span>
          </div>
          <div className="h-2 bg-zinc-800 rounded-full overflow-hidden">
            <div 
              className={clsx(
                "h-full rounded-full transition-all duration-1000",
                report.score >= 70 ? "bg-emerald-500 shadow-[0_0_10px_rgba(16,185,129,0.5)]" :
                report.score >= 40 ? "bg-amber-500 shadow-[0_0_10px_rgba(245,158,11,0.5)]" : "bg-rose-500 shadow-[0_0_10px_rgba(244,63,94,0.5)]"
              )}
              style={{ width: `${report.score}%` }}
            />
          </div>
        </div>

        {/* Check Results */}
        <div className="p-6 space-y-4 max-h-[400px] overflow-y-auto custom-scrollbar">
          
          {/* Section: Infrastructure */}
          <div>
             <h4 className="text-xs font-bold text-zinc-400 uppercase tracking-widest mb-3 flex items-center gap-2">
                <Globe className="w-3 h-3" /> Infrastructure
             </h4>
             <div className="grid grid-cols-2 gap-3">
                <div className="bg-white/5 border border-white/5 rounded-lg p-3">
                   <div className="text-[10px] text-zinc-500 uppercase mb-1">DNS Status</div>
                   <div className="flex items-center gap-2 text-sm font-medium text-white">
                      <span className={report.dns?.has_ns ? "text-emerald-400" : "text-rose-400"}>
                         {report.dns?.has_ns ? '● Active' : '○ Missing'}
                      </span>
                   </div>
                </div>
                 <div className="bg-white/5 border border-white/5 rounded-lg p-3">
                   <div className="text-[10px] text-zinc-500 uppercase mb-1">Web Server</div>
                   <div className="flex items-center gap-2 text-sm font-medium text-white">
                      <span className={report.http?.is_reachable ? "text-emerald-400" : "text-rose-400"}>
                         {report.http?.is_reachable ? `● HTTP ${report.http?.status_code}` : '○ Unreachable'}
                      </span>
                   </div>
                </div>
             </div>
          </div>

          {/* Section: Security */}
           <div>
             <h4 className="text-xs font-bold text-zinc-400 uppercase tracking-widest mb-3 mt-2 flex items-center gap-2">
                <Shield className="w-3 h-3" /> Security
             </h4>
             <div className="bg-white/5 border border-white/5 rounded-lg p-3">
                <div className="flex justify-between items-center mb-2">
                   <span className="text-sm font-medium text-white">SSL Certificate</span>
                   <span className={clsx(
                      "text-xs px-2 py-0.5 rounded border",
                      report.ssl?.is_valid 
                        ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" 
                        : "bg-rose-500/10 text-rose-400 border-rose-500/20"
                   )}>
                      {report.ssl?.is_valid ? 'SECURE' : 'INSECURE'}
                   </span>
                </div>
                {report.ssl?.days_until_expiry && (
                   <div className="text-xs text-zinc-500">
                      Expires in <span className="text-white font-mono">{report.ssl.days_until_expiry}</span> days
                   </div>
                )}
             </div>
          </div>

          {/* Signals & Recommendations */}
          {((report.signals?.length || 0) > 0 || (report.recommendations?.length || 0) > 0) && (
            <div className="space-y-3 pt-2">
              {(report.signals?.length || 0) > 0 && (
                <div>
                  <h4 className="text-xs font-medium text-zinc-500 uppercase tracking-wider mb-2">Signals</h4>
                  <ul className="space-y-2">
                    {report.signals?.map((signal, i) => (
                      <li key={i} className="text-xs text-zinc-300 flex items-start gap-2 bg-white/[0.02] p-2 rounded">
                        <Activity className="w-3.5 h-3.5 text-emerald-400 mt-0.5 shrink-0" />
                        {signal}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 bg-zinc-950 border-t border-white/5">
          <p className="text-[10px] text-zinc-600 text-center font-mono">
            LAST CHECK: {new Date(report.checked_at).toLocaleString().toUpperCase()}
          </p>
        </div>
      </div>
    </div>
  )
})
