'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api, PortfolioDomain, PortfolioSummary, DomainHealthReport, HealthStatus } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { Sidebar } from '@/components/Sidebar'
import { Toast, useToast } from '@/components/Toast'
import { BurnRateTimeline } from '@/components/cfo/BurnRateTimeline'
import { KillList } from '@/components/cfo/KillList'
import {
  Plus,
  Trash2,
  RefreshCw,
  Loader2,
  Briefcase,
  X,
  Target,
  TrendingUp,
  Settings,
  ShieldCheck,
  Shield,
  LogOut,
  Crown,
  Tag,
  Zap,
  Eye,
  ChevronUp,
  ChevronDown,
  Calendar,
  Edit3,
  CheckCircle,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Copy,
  Check,
  Navigation,
  Coins,
  Activity,
  Save,
  FileText,
  Building2,
  CreditCard,
  Crosshair,
  Wallet,
  Clock,
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

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

type PortfolioTab = 'assets' | 'financials'

interface CfoData {
  computed_at: string
  upcoming_30d_total_usd: number
  upcoming_30d_rows: Array<{
    domain_id: number
    domain: string
    renewal_date: string | null
    renewal_cost_usd: number | null
    cost_source: string
    is_sold: boolean
  }>
  monthly: Array<{ month: string; total_cost_usd: number; domains: number }>
  kill_list: Array<{
    domain_id: number
    domain: string
    renewal_date: string | null
    renewal_cost_usd: number | null
    cost_source: string
    auto_renew: boolean
    is_dns_verified: boolean
    yield_net_60d: number
    yield_clicks_60d: number
    reason: string
  }>
}

interface EditFormData {
  purchase_date: string
  purchase_price: string
  purchase_registrar: string
  registrar: string
  renewal_date: string
  renewal_cost: string
  auto_renew: boolean
  notes: string
  tags: string
  is_sold: boolean
  sale_date: string
  sale_price: string
}

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

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

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

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

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

function formatCurrency(value: number | null): string {
  if (value === null || value === undefined) return '—'
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(value)
}

function formatROI(roi: number | null): string {
  if (roi === null || roi === undefined) return '—'
  const sign = roi >= 0 ? '+' : ''
  return `${sign}${roi.toFixed(0)}%`
}

// ============================================================================
// EDIT MODAL COMPONENT
// ============================================================================

function EditModal({ 
  domain, 
  onClose, 
  onSave 
}: { 
  domain: PortfolioDomain
  onClose: () => void
  onSave: (data: Partial<EditFormData>) => Promise<void>
}) {
  const [form, setForm] = useState<EditFormData>({
    purchase_date: domain.purchase_date?.split('T')[0] || '',
    purchase_price: domain.purchase_price?.toString() || '',
    purchase_registrar: domain.purchase_registrar || '',
    registrar: domain.registrar || '',
    renewal_date: domain.renewal_date?.split('T')[0] || '',
    renewal_cost: domain.renewal_cost?.toString() || '',
    auto_renew: domain.auto_renew || false,
    notes: domain.notes || '',
    tags: domain.tags || '',
    is_sold: domain.is_sold || false,
    sale_date: domain.sale_date?.split('T')[0] || '',
    sale_price: domain.sale_price?.toString() || '',
  })
  const [saving, setSaving] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    try {
      await onSave({
        purchase_date: form.purchase_date || undefined,
        purchase_price: form.purchase_price ? parseFloat(form.purchase_price) : undefined,
        purchase_registrar: form.purchase_registrar || undefined,
        registrar: form.registrar || undefined,
        renewal_date: form.renewal_date || undefined,
        renewal_cost: form.renewal_cost ? parseFloat(form.renewal_cost) : undefined,
        auto_renew: form.auto_renew,
        notes: form.notes || undefined,
        tags: form.tags || undefined,
        is_sold: form.is_sold,
        sale_date: form.is_sold && form.sale_date ? form.sale_date : undefined,
        sale_price: form.is_sold && form.sale_price ? parseFloat(form.sale_price) : undefined,
      } as any)
      onClose()
    } finally {
      setSaving(false)
    }
  }
  
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm" onClick={onClose}>
      <div 
        className="w-full max-w-lg bg-[#0a0a0a] border border-white/10 max-h-[90vh] overflow-y-auto"
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-white/10">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <Edit3 className="w-4 h-4 text-accent" />
              <span className="text-[10px] font-mono text-accent uppercase tracking-wider">Edit Domain</span>
      </div>
            <h2 className="text-lg font-bold text-white font-mono">{domain.domain}</h2>
        </div>
          <button onClick={onClose} className="p-2 text-white/40 hover:text-white">
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          {/* Purchase Info */}
          <div className="space-y-3">
            <div className="flex items-center gap-2 text-[10px] font-mono text-white/40 uppercase tracking-wider">
              <CreditCard className="w-3.5 h-3.5" />
              Purchase Information
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-[10px] font-mono text-white/40 mb-1">Purchase Date</label>
                <input
                  type="date"
                  value={form.purchase_date}
                  onChange={e => setForm(f => ({ ...f, purchase_date: e.target.value }))}
                  className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-[10px] font-mono text-white/40 mb-1">Purchase Price ($)</label>
                <input
                  type="number"
                  step="0.01"
                  value={form.purchase_price}
                  onChange={e => setForm(f => ({ ...f, purchase_price: e.target.value }))}
                  placeholder="e.g. 500"
                  className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20"
                />
              </div>
            </div>
            <div>
              <label className="block text-[10px] font-mono text-white/40 mb-1">Purchased From</label>
              <input
                type="text"
                value={form.purchase_registrar}
                onChange={e => setForm(f => ({ ...f, purchase_registrar: e.target.value }))}
                placeholder="e.g. GoDaddy Auctions, Sedo"
                className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20"
              />
            </div>
          </div>

          {/* Current Registrar & Renewal */}
          <div className="space-y-3 pt-3 border-t border-white/10">
            <div className="flex items-center gap-2 text-[10px] font-mono text-white/40 uppercase tracking-wider">
              <Building2 className="w-3.5 h-3.5" />
              Registrar & Renewal
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-[10px] font-mono text-white/40 mb-1">Current Registrar</label>
                <input
                  type="text"
                  value={form.registrar}
                  onChange={e => setForm(f => ({ ...f, registrar: e.target.value }))}
                  placeholder="e.g. Namecheap"
                  className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20"
                />
              </div>
              <div>
                <label className="block text-[10px] font-mono text-white/40 mb-1">Renewal Cost ($)</label>
                <input
                  type="number"
                  step="0.01"
                  value={form.renewal_cost}
                  onChange={e => setForm(f => ({ ...f, renewal_cost: e.target.value }))}
                  placeholder="e.g. 12"
                  className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-[10px] font-mono text-white/40 mb-1">Renewal Date</label>
                <input
                  type="date"
                  value={form.renewal_date}
                  onChange={e => setForm(f => ({ ...f, renewal_date: e.target.value }))}
                  className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none"
                />
              </div>
              <div className="flex items-end">
                <label className="flex items-center gap-2 cursor-pointer py-2">
                  <input
                    type="checkbox"
                    checked={form.auto_renew}
                    onChange={e => setForm(f => ({ ...f, auto_renew: e.target.checked }))}
                    className="w-4 h-4 accent-accent"
                  />
                  <span className="text-sm font-mono text-white/60">Auto-Renew</span>
                </label>
              </div>
            </div>
          </div>

          {/* Notes & Tags */}
          <div className="space-y-3 pt-3 border-t border-white/10">
            <div className="flex items-center gap-2 text-[10px] font-mono text-white/40 uppercase tracking-wider">
              <FileText className="w-3.5 h-3.5" />
              Notes & Tags
            </div>
            <div>
              <label className="block text-[10px] font-mono text-white/40 mb-1">Tags (comma-separated)</label>
              <input
                type="text"
                value={form.tags}
                onChange={e => setForm(f => ({ ...f, tags: e.target.value }))}
                placeholder="e.g. premium, brandable, crypto"
                className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20"
              />
            </div>
            <div>
              <label className="block text-[10px] font-mono text-white/40 mb-1">Notes</label>
              <textarea
                value={form.notes}
                onChange={e => setForm(f => ({ ...f, notes: e.target.value }))}
                rows={3}
                placeholder="Private notes about this domain..."
                className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20 resize-none"
              />
            </div>
          </div>

          {/* Sale Status */}
          <div className="space-y-3 pt-3 border-t border-white/10">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={form.is_sold}
                onChange={e => setForm(f => ({ ...f, is_sold: e.target.checked }))}
                className="w-4 h-4 accent-accent"
              />
              <span className="text-sm font-mono text-white/60">Mark as Sold</span>
            </label>
            {form.is_sold && (
              <div className="grid grid-cols-2 gap-3 pl-6">
                <div>
                  <label className="block text-[10px] font-mono text-white/40 mb-1">Sale Date</label>
                  <input
                    type="date"
                    value={form.sale_date}
                    onChange={e => setForm(f => ({ ...f, sale_date: e.target.value }))}
                    className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-mono text-white/40 mb-1">Sale Price ($)</label>
                  <input
                    type="number"
                    step="0.01"
                    value={form.sale_price}
                    onChange={e => setForm(f => ({ ...f, sale_price: e.target.value }))}
                    className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none"
                  />
                </div>
          </div>
        )}
          </div>

          {/* Actions */}
          <div className="flex justify-end gap-2 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-mono text-white/60 hover:text-white transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={saving}
              className="flex items-center gap-2 px-4 py-2 bg-accent text-black text-sm font-bold uppercase tracking-wider hover:bg-white transition-colors disabled:opacity-50"
            >
              {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              Save Changes
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

// ============================================================================
// ADD MODAL COMPONENT
// ============================================================================

function AddModal({ 
  onClose, 
  onAdd,
  onStartVerify
}: { 
  onClose: () => void
  onAdd: (domain: string, data?: Partial<EditFormData>) => Promise<PortfolioDomain | void>
  onStartVerify?: (domain: PortfolioDomain) => void
}) {
  const [domain, setDomain] = useState('')
  const [showDetails, setShowDetails] = useState(false)
  const [wantToVerify, setWantToVerify] = useState(false)
  const [form, setForm] = useState<Partial<EditFormData>>({})
  const [adding, setAdding] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!domain.trim()) return
    setAdding(true)
    try {
      const created = await onAdd(domain.trim(), showDetails ? form : undefined) as PortfolioDomain | undefined
      if (wantToVerify && created && onStartVerify) {
        onClose()
        // Small delay to let the modal close before opening verify modal
        setTimeout(() => onStartVerify(created), 100)
      } else {
        onClose()
      }
    } finally {
      setAdding(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 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 max-h-[90vh] overflow-y-auto"
        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">
            <Plus className="w-4 h-4 text-accent" />
            <span className="text-sm font-mono text-white uppercase tracking-wider">Add Domain</span>
          </div>
          <button onClick={onClose} className="p-2 text-white/40 hover:text-white">
            <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-1">Domain Name</label>
            <input
              type="text"
              value={domain}
              onChange={e => setDomain(e.target.value)}
              placeholder="example.com"
              autoFocus
              className="w-full px-3 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"
            />
          </div>

          <button
            type="button"
            onClick={() => setShowDetails(!showDetails)}
            className="flex items-center gap-2 text-[10px] font-mono text-accent uppercase tracking-wider"
          >
            {showDetails ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
            {showDetails ? 'Hide Details' : 'Add Purchase Details'}
          </button>

          {showDetails && (
            <div className="space-y-3 pt-2">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-[10px] font-mono text-white/40 mb-1">Purchase Date</label>
                  <input
                    type="date"
                    value={form.purchase_date || ''}
                    onChange={e => setForm(f => ({ ...f, purchase_date: e.target.value }))}
                    className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-mono text-white/40 mb-1">Purchase Price ($)</label>
                  <input
                    type="number"
                    step="0.01"
                    value={form.purchase_price || ''}
                    onChange={e => setForm(f => ({ ...f, purchase_price: e.target.value }))}
                    className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none"
                  />
                </div>
              </div>
              <div>
                <label className="block text-[10px] font-mono text-white/40 mb-1">Registrar</label>
                <input
                  type="text"
                  value={form.registrar || ''}
                  onChange={e => setForm(f => ({ ...f, registrar: e.target.value }))}
                  placeholder="e.g. Namecheap"
                  className="w-full px-3 py-2 bg-white/5 border border-white/10 text-white text-sm font-mono focus:border-accent/50 focus:outline-none placeholder:text-white/20"
                />
              </div>
            </div>
          )}

          {/* Verify Option */}
          <div className="pt-2 border-t border-white/10">
            <label className="flex items-center gap-3 cursor-pointer group">
              <input
                type="checkbox"
                checked={wantToVerify}
                onChange={e => setWantToVerify(e.target.checked)}
                className="w-4 h-4 accent-accent"
              />
              <div className="flex-1">
                <div className="text-sm font-mono text-white/70 group-hover:text-white">
                  Verify DNS ownership
                </div>
                <div className="text-[10px] font-mono text-white/30">
                  Required for Yield and For Sale features
                </div>
              </div>
              <ShieldCheck className="w-4 h-4 text-white/20 group-hover:text-accent" />
            </label>
          </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" />}
            {wantToVerify ? 'Add & Verify' : 'Add to Portfolio'}
          </button>
        </form>
      </div>
    </div>
  )
}

// ============================================================================
// DNS VERIFICATION MODAL
// ============================================================================

function VerifyModal({ 
  domain, 
  onClose,
  onVerified
}: { 
  domain: PortfolioDomain
  onClose: () => void
  onVerified: () => void
}) {
  const [verificationCode, setVerificationCode] = useState<string | null>(domain.verification_code || null)
  const [copied, setCopied] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(!domain.verification_code)
  const [checking, setChecking] = useState(false)

  useEffect(() => {
    if (!verificationCode) {
      startVerification()
    }
  }, [])

  const startVerification = async () => {
    setLoading(true)
    try {
      const result = await api.startPortfolioDnsVerification(domain.id)
      setVerificationCode(result.verification_code)
    } catch (err: any) {
      setError(err?.message || 'Failed to start verification')
    } finally {
      setLoading(false)
    }
  }

  const checkVerification = async () => {
    setChecking(true)
    setError(null)
    try {
      const result = await api.checkPortfolioDnsVerification(domain.id)
      if (result.verified) {
        onVerified()
        onClose()
      } else {
        setError(result.message || 'DNS record not found yet. Please wait a few minutes and try again.')
      }
    } catch (err: any) {
      setError(err?.message || 'Verification failed')
    } finally {
      setChecking(false)
    }
  }

  const copyCode = () => {
    if (!verificationCode) return
    navigator.clipboard.writeText(verificationCode)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm" onClick={onClose}>
      <div 
        className="w-full max-w-lg bg-[#0a0a0a] border border-white/10"
        onClick={e => e.stopPropagation()}
      >
        <div className="flex items-center justify-between p-5 border-b border-white/10">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <ShieldCheck className="w-4 h-4 text-accent" />
              <span className="text-[10px] font-mono text-accent uppercase tracking-wider">Verify Ownership</span>
            </div>
            <h2 className="text-lg font-bold text-white font-mono">{domain.domain}</h2>
          </div>
          <button onClick={onClose} className="p-2 text-white/40 hover:text-white">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-5 space-y-5">
          {loading ? (
            <div className="flex items-center justify-center py-10">
              <Loader2 className="w-6 h-6 text-accent animate-spin" />
            </div>
          ) : verificationCode ? (
            <>
              {/* Step 1 */}
              <div className="space-y-3">
                <h3 className="text-sm font-bold text-white flex items-center gap-2">
                  <span className="w-6 h-6 bg-accent text-black text-xs font-bold flex items-center justify-center">1</span>
                  Add TXT Record at your Registrar
                </h3>
                
                <div className="p-4 bg-[#020202] border border-white/[0.08] space-y-3">
                  <p className="text-sm text-white/70">
                    Go to your registrar's DNS settings and add this TXT record:
                  </p>
                  
                  <div className="grid grid-cols-2 gap-2">
                    <div className="p-3 bg-white/5 border border-white/10 text-center">
                      <div className="text-[9px] font-mono text-white/40 uppercase mb-1">Type</div>
                      <div className="text-base font-bold text-white font-mono">TXT</div>
                    </div>
                    <div className="p-3 bg-white/5 border border-white/10 text-center">
                      <div className="text-[9px] font-mono text-white/40 uppercase mb-1">Name / Host</div>
                      <div className="text-base font-bold text-white font-mono">@</div>
                    </div>
                  </div>
                  
                  <div className="p-3 bg-accent/10 border border-accent/20">
                    <div className="text-[9px] font-mono text-accent/60 uppercase mb-1">Value (copy this)</div>
                    <div className="flex items-center gap-2">
                      <code className="flex-1 text-sm font-mono text-accent break-all">
                        {verificationCode}
                      </code>
                      <button
                        onClick={copyCode}
                        className="p-2 border border-accent/20 text-accent hover:bg-accent/10 transition-colors shrink-0"
                        title="Copy to clipboard"
                      >
                        {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                  
                  <div className="text-[10px] text-white/30">
                    <strong className="text-white/50">Tip:</strong> The "@" symbol means root domain. Some registrars use "empty" or the domain name itself.
                  </div>
                </div>
              </div>

              {/* Step 2 */}
              <div className="space-y-3">
                <h3 className="text-sm font-bold text-white flex items-center gap-2">
                  <span className="w-6 h-6 bg-white/10 text-white/60 text-xs font-bold flex items-center justify-center">2</span>
                  Verify
                </h3>
                
                <p className="text-xs text-white/50">
                  After adding the TXT record, wait 2-5 minutes for DNS propagation, then click verify.
                </p>

                {error && (
                  <div className="p-3 bg-amber-500/10 border border-amber-500/20 text-amber-400 text-xs font-mono flex items-start gap-2">
                    <Clock className="w-4 h-4 shrink-0 mt-0.5" />
                    {error}
                  </div>
                )}

                <button
                  onClick={checkVerification}
                  disabled={checking}
                  className="w-full flex items-center justify-center gap-2 py-3.5 bg-accent text-black text-sm font-bold uppercase tracking-wider hover:bg-white transition-colors disabled:opacity-50"
                >
                  {checking ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <ShieldCheck className="w-4 h-4" />
                  )}
                  Verify DNS Record
                </button>
              </div>
            </>
          ) : (
            <div className="text-center py-8">
              <AlertTriangle className="w-10 h-10 text-amber-400/50 mx-auto mb-3" />
              <p className="text-sm text-white/50">{error || 'Failed to generate verification code'}</p>
              <button
                onClick={startVerification}
                className="mt-4 px-4 py-2 bg-white/10 text-white text-xs font-bold uppercase"
              >
                Try Again
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

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

export default function PortfolioPage() {
  const { subscription, user, logout, checkAuth } = useStore()
  const { toast, showToast, hideToast } = useToast()
  const openAnalyze = useAnalyzePanelStore((s) => s.open)
  
  // Tab state
  const [activeTab, setActiveTab] = useState<PortfolioTab>('assets')
  
  const [domains, setDomains] = useState<PortfolioDomain[]>([])
  const [summary, setSummary] = useState<PortfolioSummary | null>(null)
  const [loading, setLoading] = useState(true)
  const [refreshingId, setRefreshingId] = useState<number | null>(null)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  
  // CFO / Financials data
  const [cfoData, setCfoData] = useState<CfoData | null>(null)
  const [cfoLoading, setCfoLoading] = useState(false)
  
  // Modals
  const [showAddModal, setShowAddModal] = useState(false)
  const [editingDomain, setEditingDomain] = useState<PortfolioDomain | null>(null)
  const [verifyingDomain, setVerifyingDomain] = useState<PortfolioDomain | null>(null)
  
  // Filter & Sort
  const [filter, setFilter] = useState<'all' | 'active' | 'sold' | 'expiring'>('all')
  const [sortField, setSortField] = useState<'domain' | 'value' | 'roi' | 'renewal' | 'purchased'>('domain')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
  
  // Health data
  const [healthByDomain, setHealthByDomain] = useState<Record<string, DomainHealthReport>>({})
  const [checkingHealth, setCheckingHealth] = useState<Set<string>>(new Set())
  const [healthLoadStarted, setHealthLoadStarted] = useState(false)
  
  // External status (Yield, Listed)
  const [yieldByDomain, setYieldByDomain] = useState<Record<string, { id: number; status: string; dns_verified: boolean }>>({})
  const [listedDomains, setListedDomains] = useState<Set<string>>(new Set())
  
  // Mobile
  const [navDrawerOpen, setNavDrawerOpen] = useState(false)
  const [expandedRow, setExpandedRow] = useState<number | null>(null)
  
  // Health detail overlay
  const [selectedHealthDomain, setSelectedHealthDomain] = useState<PortfolioDomain | null>(null)

  const tier = subscription?.tier || 'scout'
  const tierName = subscription?.tier_name || tier
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap
  
  // Tier limits
  const portfolioLimits: Record<string, number> = { scout: 5, trader: 50, tycoon: Infinity }
  const maxPortfolio = portfolioLimits[tier] || 5
  const formatLimit = (limit: number) => limit === Infinity ? '∞' : String(limit)

  useEffect(() => { checkAuth() }, [checkAuth])

  // Load all data
  const loadData = useCallback(async () => {
    setLoading(true)
    try {
      const [domainsData, summaryData] = await Promise.all([
        api.getPortfolio(),
        api.getPortfolioSummary()
      ])
      setDomains(domainsData)
      setSummary(summaryData)

      // Load yield domains
      try {
        const yieldData = await api.getYieldDomains()
        const map: Record<string, { id: number; status: string; dns_verified: boolean }> = {}
        for (const d of yieldData.domains || []) {
          const key = String((d as any).domain || '').toLowerCase()
          if (!key) continue
          map[key] = { id: Number((d as any).id), status: String((d as any).status || 'pending'), dns_verified: Boolean((d as any).dns_verified) }
        }
        setYieldByDomain(map)
      } catch { setYieldByDomain({}) }

      // Load listed domains
      try {
        const listings = await api.getMyListings()
        const active = (listings || []).filter((l: any) => l.status === 'active')
        setListedDomains(new Set(active.map((l: any) => String(l.domain).toLowerCase())))
      } catch { setListedDomains(new Set()) }
    } catch (err) {
      console.error('Failed to load portfolio:', err)
    } finally {
      setLoading(false)
    }
  }, [])

  // Load CFO/Financials data
  const loadCfoData = useCallback(async () => {
    setCfoLoading(true)
    try {
      const res = await api.getCfoSummary()
      setCfoData(res)
    } catch (err) {
      console.error('Failed to load CFO data:', err)
    } finally {
      setCfoLoading(false)
    }
  }, [])

  useEffect(() => { loadData() }, [loadData])
  
  // Load CFO data when switching to financials tab
  useEffect(() => {
    if (activeTab === 'financials' && !cfoData && !cfoLoading) {
      loadCfoData()
    }
  }, [activeTab, cfoData, cfoLoading, loadCfoData])

  // Auto-load health data for all domains when domains are first loaded
  useEffect(() => {
    // Only run once when domains are first loaded
    if (!domains.length || healthLoadStarted) return
    
    setHealthLoadStarted(true)
    
    const loadHealthForDomains = async () => {
      // Load health for up to 20 domains to avoid too many requests
      const domainsToCheck = domains.slice(0, 20)
      
      for (const domain of domainsToCheck) {
        const key = domain.domain.toLowerCase()
        // Skip if already have health data
        if (healthByDomain[key]) continue
        
        // Add to checking set
        setCheckingHealth(prev => new Set(prev).add(key))
        
        try {
          const report = await api.quickHealthCheck(domain.domain)
          setHealthByDomain(prev => ({ ...prev, [key]: report }))
        } catch {
          // Silently fail for individual domains
    } finally {
          setCheckingHealth(prev => {
            const next = new Set(prev)
            next.delete(key)
            return next
          })
        }
        
        // Small delay to avoid rate limiting
        await new Promise(resolve => setTimeout(resolve, 300))
      }
    }
    
    loadHealthForDomains()
  }, [domains, healthLoadStarted])

  // Stats
  const stats = useMemo(() => {
    const active = domains.filter(d => !d.is_sold).length
    const sold = domains.filter(d => d.is_sold).length
    const verified = domains.filter(d => d.is_dns_verified && !d.is_sold).length
    const expiringSoon = domains.filter(d => {
      if (d.is_sold || !d.renewal_date) return false
      const days = getDaysUntil(d.renewal_date)
      return days !== null && days <= 30 && days > 0
    }).length
    const upcoming30dCost = cfoData?.upcoming_30d_total_usd || 0
    return { total: domains.length, active, sold, verified, expiringSoon, upcoming30dCost }
  }, [domains, cfoData])

  // Filter & Sort
  const filteredDomains = useMemo(() => {
    let filtered = domains.filter(d => {
      if (filter === 'active') return !d.is_sold
      if (filter === 'sold') return d.is_sold
      if (filter === 'expiring') {
        const days = getDaysUntil(d.renewal_date)
        return !d.is_sold && days !== null && days <= 30 && days > 0
      }
      return true
    })
    
    const mult = sortDirection === 'asc' ? 1 : -1
    filtered.sort((a, b) => {
      switch (sortField) {
        case 'domain': return mult * a.domain.localeCompare(b.domain)
        case 'value': return mult * ((a.estimated_value || 0) - (b.estimated_value || 0))
        case 'roi': return mult * ((a.roi || 0) - (b.roi || 0))
        case 'renewal':
          const aRen = a.renewal_date ? new Date(a.renewal_date).getTime() : Infinity
          const bRen = b.renewal_date ? new Date(b.renewal_date).getTime() : Infinity
          return mult * (aRen - bRen)
        case 'purchased':
          const aPur = a.purchase_date ? new Date(a.purchase_date).getTime() : 0
          const bPur = b.purchase_date ? new Date(b.purchase_date).getTime() : 0
          return mult * (aPur - bPur)
        default: return 0
      }
    })
    return filtered
  }, [domains, filter, sortField, sortDirection])

  const handleSort = (field: typeof sortField) => {
    if (sortField === field) {
      setSortDirection(d => d === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDirection('asc')
    }
  }

  // Actions
  const handleHealthCheck = async (domainName: string, showError = true) => {
    const key = domainName.toLowerCase()
    if (checkingHealth.has(key)) return
    setCheckingHealth(prev => new Set(prev).add(key))
    try {
      const report = await api.quickHealthCheck(domainName)
      setHealthByDomain(prev => ({ ...prev, [key]: report }))
    } catch (err: any) {
      if (showError) {
        showToast(err?.message || 'Health check failed', 'error')
      }
    } finally {
      setCheckingHealth(prev => {
        const next = new Set(prev)
        next.delete(key)
        return next
      })
    }
  }

  const handleRefreshValue = async (id: number) => {
    setRefreshingId(id)
    try {
      const updated = await api.refreshDomainValue(id)
      setDomains(prev => prev.map(d => d.id === id ? updated : d))
      showToast('Value updated', 'success')
    } catch {
      showToast('Update failed', 'error')
    } finally {
      setRefreshingId(null)
    }
  }

  const handleDelete = async (id: number, name: string) => {
    if (!confirm(`Remove ${name} from portfolio?`)) return
    setDeletingId(id)
    try {
      await api.deletePortfolioDomain(id)
      setDomains(prev => prev.filter(d => d.id !== id))
      showToast('Domain removed', 'success')
    } catch {
      showToast('Failed to remove', 'error')
    } finally {
      setDeletingId(null)
    }
  }

  const handleAddDomain = async (domain: string, data?: any): Promise<PortfolioDomain> => {
    try {
      const created = await api.addPortfolioDomain({ domain, ...data })
      setDomains(prev => [created, ...prev])
      showToast(`${domain} added to portfolio`, 'success')
      return created
    } catch (err: any) {
      showToast(err?.message || 'Failed to add domain', 'error')
      throw err
    }
  }

  const handleUpdateDomain = async (id: number, data: any) => {
    try {
      const updated = await api.updatePortfolioDomain(id, data)
      setDomains(prev => prev.map(d => d.id === id ? updated : d))
      showToast('Domain updated', 'success')
    } catch (err: any) {
      showToast(err?.message || 'Update failed', 'error')
      throw err
    }
  }

  // Navigation
  const mobileNavItems = [
    { href: '/terminal/hunt', label: 'Hunt', icon: Crosshair, active: false },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: false },
    { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase, active: true },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: false },
  ]

  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 },
      { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase, active: true },
      { 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 },
    ]}
  ]

  // Render helpers
  const renderHealth = (domain: PortfolioDomain) => {
    const key = domain.domain.toLowerCase()
    const health = healthByDomain[key]
    const isChecking = checkingHealth.has(key)
    const cfg = healthConfig[(health?.status as HealthStatus) || 'unknown']
    
    return (
      <button
        onClick={() => {
          setSelectedHealthDomain(domain)
          if (!health) handleHealthCheck(domain.domain)
        }}
        disabled={isChecking}
        title={health ? `${cfg.label} • Score ${health.score}/100 • Click for details` : 'Run health check'}
        className={clsx(
          "flex items-center gap-1 px-2 py-1 text-[10px] font-mono uppercase border transition-colors",
          cfg.color, cfg.bg, cfg.border,
          "hover:opacity-80 disabled:opacity-50"
        )}
      >
        {isChecking ? (
          <Loader2 className="w-3 h-3 animate-spin" />
        ) : (
          <>
            <Activity className="w-3 h-3" />
            {health ? health.score : '—'}
          </>
        )}
      </button>
    )
  }

  const renderStatusBadges = (domain: PortfolioDomain) => {
    const badges = []
    if (domain.is_dns_verified) {
      badges.push(
        <span key="verified" title="DNS Verified" className="flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-mono uppercase bg-accent/10 text-accent border border-accent/20">
          <ShieldCheck className="w-3 h-3" />
        </span>
      )
    }
    const y = yieldByDomain[domain.domain.toLowerCase()]
    if (y) {
      const isActive = y.status === 'active'
      badges.push(
        <span
          key="yield"
          title={`Yield: ${y.status}`}
          className={clsx(
            "flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-mono uppercase border",
            isActive ? "bg-accent/10 text-accent border-accent/20" : "bg-amber-400/10 text-amber-400 border-amber-400/20"
          )}
        >
          <Coins className="w-3 h-3" />
        </span>
      )
    }
    if (listedDomains.has(domain.domain.toLowerCase())) {
      badges.push(
        <span key="listed" title="Listed for Sale" className="flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-mono uppercase bg-blue-400/10 text-blue-400 border border-blue-400/20">
          <Tag className="w-3 h-3" />
        </span>
      )
    }
    return badges.length > 0 ? <div className="flex items-center gap-1">{badges}</div> : null
  }

  const renderYieldCell = (domain: PortfolioDomain) => {
    const y = yieldByDomain[domain.domain.toLowerCase()]
    const canActivate = domain.is_dns_verified && !domain.is_sold
    if (y?.status === 'active') {
      return (
        <Link
          href={`/terminal/yield`}
          className="inline-flex items-center justify-center w-full px-2 py-1 text-[10px] font-mono uppercase border border-accent/20 bg-accent/10 text-accent hover:opacity-90"
          title="Manage Yield"
        >
          ⚡ Active
        </Link>
      )
    }
    if (y) {
      return (
        <Link
          href={`/terminal/yield`}
          className="inline-flex items-center justify-center w-full px-2 py-1 text-[10px] font-mono uppercase border border-amber-400/20 bg-amber-400/10 text-amber-300 hover:opacity-90"
          title="Continue Yield setup"
        >
          {y.status}
        </Link>
      )
    }
    return (
      <Link
        href={canActivate ? `/terminal/yield?activate=${encodeURIComponent(domain.domain)}` : `/terminal/portfolio`}
        className={clsx(
          "inline-flex items-center justify-center w-full px-2 py-1 text-[10px] font-mono uppercase border",
          canActivate
            ? "border-white/10 bg-white/[0.02] text-white/50 hover:text-white hover:bg-white/[0.05]"
            : "border-white/10 bg-white/[0.01] text-white/20 cursor-not-allowed"
        )}
        title={canActivate ? "Activate Yield" : "Verify DNS first to activate Yield"}
        onClick={(e) => { if (!canActivate) e.preventDefault() }}
      >
        💤 Idle
      </Link>
    )
  }

  return (
    <div className="min-h-screen bg-[#020202]">
      <div className="hidden lg:block"><Sidebar /></div>
      
      <main className="lg:pl-[240px] pb-24 lg:pb-0">
        {/* 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">Portfolio</span>
              </div>
              <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>

            {/* Tab Bar - Scrollable */}
            <div className="-mx-4 px-4 overflow-x-auto">
              <div className="flex gap-1 min-w-max pb-1">
                <button
                  onClick={() => setActiveTab('assets')}
                  className={clsx(
                    'flex items-center gap-1.5 px-3 py-2 border transition-all shrink-0',
                    activeTab === 'assets'
                      ? 'border-accent/40 bg-accent/10 text-accent'
                      : 'border-transparent text-white/40 active:bg-white/5'
                  )}
                >
                  <Briefcase className="w-3.5 h-3.5" />
                  <span className="text-[10px] font-bold uppercase tracking-wider font-mono">Assets</span>
                </button>
                <button
                  onClick={() => setActiveTab('financials')}
                  className={clsx(
                    'flex items-center gap-1.5 px-3 py-2 border transition-all shrink-0',
                    activeTab === 'financials'
                      ? 'border-orange-500/40 bg-orange-500/10 text-orange-400'
                      : 'border-transparent text-white/40 active:bg-white/5'
                  )}
                >
                  <Wallet className="w-3.5 h-3.5" />
                  <span className="text-[10px] font-bold uppercase tracking-wider font-mono">Financials</span>
                  {stats.upcoming30dCost > 0 && (
                    <span className="px-1 py-0.5 text-[8px] bg-orange-500/20 text-orange-400 border border-orange-500/30">
                      ${Math.round(stats.upcoming30dCost)}
                    </span>
                  )}
                </button>
              </div>
            </div>
          </div>
        </header>

        {/* DESKTOP HEADER */}
        <section className="hidden lg:block px-10 pt-10 pb-6">
          <div className="flex items-start justify-between gap-8">
            <div className="space-y-4">
              <div>
                <div className="flex items-center gap-2 mb-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">Portfolio Manager</span>
              </div>
                <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em] text-white">
                  My Portfolio
                  <span className="text-white/30 ml-3 font-mono text-[2rem]">{stats.total}/{formatLimit(maxPortfolio)}</span>
                </h1>
                <p className="text-sm text-white/40 font-mono max-w-lg mt-2">
                  Track your domain investments. Add purchase details, monitor values, verify ownership, and list for sale.
              </p>
            </div>
            
              {/* TABS - Directly under subtitle */}
              <div className="flex gap-2 pt-2">
              <button
                  onClick={() => setActiveTab('assets')}
                  className={clsx(
                    'flex items-center gap-2 px-4 py-2.5 border transition-all',
                    activeTab === 'assets'
                      ? 'border-accent bg-accent/10 text-accent'
                      : 'border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.02]'
                  )}
                >
                  <Briefcase className="w-4 h-4" />
                  <span className="text-xs font-bold uppercase tracking-wider">Assets</span>
              </button>
                <button
                  onClick={() => setActiveTab('financials')}
                  className={clsx(
                    'flex items-center gap-2 px-4 py-2.5 border transition-all',
                    activeTab === 'financials'
                      ? 'border-orange-500 bg-orange-500/10 text-orange-400'
                      : 'border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.02]'
                  )}
                >
                  <Wallet className="w-4 h-4" />
                  <span className="text-xs font-bold uppercase tracking-wider">Financials</span>
                  {stats.upcoming30dCost > 0 && (
                    <span className="px-1.5 py-0.5 text-[9px] bg-orange-500/20 text-orange-400 border border-orange-500/30">
                      ${Math.round(stats.upcoming30dCost)}
                    </span>
                  )}
                </button>
              </div>
          </div>

            <div className="flex items-center gap-8">
              <div className="text-right" title="Total invested">
                <div className="text-2xl font-bold text-white font-mono">{formatCurrency(summary?.total_invested || 0)}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase">Invested</div>
        </div>
              <div className="text-right" title="Current market value">
                <div className="text-2xl font-bold text-accent font-mono">{formatCurrency(summary?.total_value || 0)}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase">Value</div>
              </div>
              <div className="text-right" title="Return on investment">
                <div className={clsx("text-2xl font-bold font-mono", (summary?.overall_roi || 0) >= 0 ? "text-accent" : "text-rose-400")}>
                  {formatROI(summary?.overall_roi || 0)}
                </div>
                <div className="text-[9px] font-mono text-white/30 uppercase">ROI</div>
              </div>
              <div className="pl-6 border-l border-white/10">
                <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 BAR - Only for assets tab */}
        <section className="hidden lg:block px-10 py-3 border-y border-white/[0.08] bg-white/[0.01]">
          {activeTab === 'assets' && (
            <div className="flex items-center gap-2 overflow-x-auto">
              {[
                { value: 'all', label: 'All', count: stats.total },
                { value: 'active', label: 'Active', count: stats.active },
                { value: 'sold', label: 'Sold', count: stats.sold },
                { value: 'expiring', label: 'Expiring Soon', count: stats.expiringSoon },
              ].map((item) => (
                <button
                  key={item.value}
                  onClick={() => setFilter(item.value as any)}
                  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>
          )}
          {activeTab === 'financials' && (
            <div className="text-[10px] font-mono text-white/40 uppercase tracking-wider">
              Financial Overview & Renewal Costs
            </div>
          )}
        </section>

        {/* TAB CONTENT */}
        <section className="px-4 lg:px-10 py-6">
          {/* FINANCIALS TAB */}
          {activeTab === 'financials' && (
            <div className="space-y-4">
              {cfoLoading ? (
                <div className="flex items-center justify-center py-16">
                  <Loader2 className="w-6 h-6 text-accent animate-spin" />
                </div>
              ) : !cfoData ? (
                <div className="text-center py-16 border border-dashed border-white/[0.08]">
                  <Wallet className="w-10 h-10 text-white/10 mx-auto mb-4" />
                  <p className="text-white/40 text-sm font-mono mb-1">No financial data</p>
                  <p className="text-white/25 text-xs font-mono mb-4">Add domains to your portfolio to see costs</p>
                  <button
                    onClick={loadCfoData}
                    className="inline-flex items-center gap-2 px-4 py-2 border border-white/10 text-white/60 text-xs font-bold uppercase hover:bg-white/5"
                  >
                    <RefreshCw className="w-4 h-4" />Refresh
                  </button>
               </div>
              ) : (
                <>
                  {/* Summary Cards */}
                  <div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
                    <div className="border border-orange-500/20 bg-orange-500/[0.03] p-4">
                      <div className="flex items-center gap-2 mb-2">
                        <Wallet className="w-4 h-4 text-orange-400" />
                        <span className="text-[10px] font-mono text-orange-400/60 uppercase tracking-wider">Next 30 Days</span>
          </div>
                      <div className="text-2xl font-bold text-orange-400 font-mono">${Math.round(cfoData.upcoming_30d_total_usd)}</div>
                      <div className="text-[10px] font-mono text-white/30 mt-1">{cfoData.upcoming_30d_rows.length} renewals due</div>
                    </div>
                    
                    <div className="border border-white/[0.08] bg-white/[0.02] p-4">
                      <div className="flex items-center gap-2 mb-2">
                        <Calendar className="w-4 h-4 text-white/40" />
                        <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Annual Burn</span>
                      </div>
                      <div className="text-2xl font-bold text-white font-mono">
                        ${Math.round(cfoData.monthly.reduce((sum, m) => sum + m.total_cost_usd, 0))}
                      </div>
                      <div className="text-[10px] font-mono text-white/30 mt-1">Based on 12-month forecast</div>
                    </div>
                    
                    <div className="border border-white/[0.08] bg-white/[0.02] p-4">
                      <div className="flex items-center gap-2 mb-2">
                        <Trash2 className="w-4 h-4 text-white/40" />
                        <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Drop Candidates</span>
                      </div>
                      <div className="text-2xl font-bold text-white font-mono">{cfoData.kill_list.length}</div>
                      <div className="text-[10px] font-mono text-white/30 mt-1">No yield, expiring soon</div>
                    </div>
                  </div>

                  {/* Upcoming Renewals */}
                  {cfoData.upcoming_30d_rows.length > 0 && (
                    <div className="border border-white/[0.08] bg-[#020202]">
                      <div className="px-4 py-3 border-b border-white/[0.08]">
                        <div className="text-[10px] font-mono uppercase tracking-widest text-white/40">Upcoming Costs</div>
                        <div className="text-sm font-bold text-white">Next 30 days</div>
                      </div>
                      <div className="divide-y divide-white/[0.06]">
                        {cfoData.upcoming_30d_rows.slice(0, 10).map((r) => (
                          <div key={r.domain_id} className="px-4 py-2 flex items-center justify-between text-[11px] font-mono">
                            <span className="text-white/60 truncate">{r.domain}</span>
                            <span className="text-white/40 shrink-0">
                              {r.renewal_date ? r.renewal_date.slice(0, 10) : '—'} · ${Math.round(r.renewal_cost_usd || 0)}
                            </span>
                          </div>
                        ))}
                      </div>
            </div>
          )}

                  {/* Burn Rate Timeline */}
                  <BurnRateTimeline monthly={cfoData.monthly} />

                  {/* Kill List */}
                  <KillList rows={cfoData.kill_list} onChanged={loadCfoData} />

                  {/* Tips */}
                  <div className="border border-white/[0.08] bg-[#020202] p-4">
                    <div className="text-[10px] font-mono uppercase tracking-widest text-white/40 mb-2">What to do next</div>
                    <div className="text-[12px] font-mono text-white/50 space-y-1">
                      <div>- If a renewal cost is missing, fill it in on the domain in <span className="text-white/70">Assets → Edit</span>.</div>
                      <div>- "Set to Drop" is a local flag — you still need to disable auto-renew at your registrar.</div>
                      <div>- Want to cover costs? Activate Yield only for <span className="text-white/70">DNS‑verified</span> domains.</div>
                </div>
                  </div>
                </>
              )}
            </div>
          )}

          {/* ASSETS TAB (Domain List) */}
          {activeTab === 'assets' && (
            <>
              {loading ? (
                <div className="flex items-center justify-center py-20">
              <Loader2 className="w-6 h-6 text-accent animate-spin" />
                </div>
          ) : !filteredDomains.length ? (
            <div className="text-center py-24 border border-dashed border-white/[0.08] bg-white/[0.01]">
              <Briefcase 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 found</p>
              <p className="text-white/20 text-xs font-mono mt-3 uppercase tracking-wider max-w-sm mx-auto leading-relaxed">
                Add your first domain to start tracking your portfolio
              </p>
              <button
                onClick={() => setShowAddModal(true)}
                className="mt-6 inline-flex items-center gap-2 px-5 py-3 bg-accent text-black text-xs font-black uppercase tracking-widest hover:bg-white transition-colors"
              >
                <Plus className="w-4 h-4" />Add Domain
              </button>
            </div>
              ) : (
            <div className="border border-white/[0.08] bg-[#020202] overflow-hidden">
              {/* Desktop Table Header */}
              <div className="hidden lg:grid grid-cols-[minmax(150px,1.5fr)_minmax(100px,1fr)_80px_70px_90px_70px_70px_50px_auto] gap-4 px-5 py-3 text-[10px] font-mono text-white/40 uppercase tracking-[0.12em] border-b border-white/[0.08] bg-white/[0.02]">
                <button onClick={() => handleSort('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>
                <div>Registrar</div>
                <button onClick={() => handleSort('purchased')} className="flex items-center gap-1 justify-center hover:text-white transition-colors">
                  <span className={clsx(sortField === 'purchased' && "text-accent font-bold")}>Bought</span>
                  {sortField === 'purchased' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                </button>
                <button onClick={() => handleSort('renewal')} className="flex items-center gap-1 justify-center hover:text-white transition-colors">
                  <span className={clsx(sortField === 'renewal' && "text-accent font-bold")}>Exp.</span>
                  {sortField === 'renewal' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                </button>
                <button onClick={() => handleSort('value')} className="flex items-center gap-1 justify-end hover:text-white transition-colors">
                  <span className={clsx(sortField === 'value' && "text-accent font-bold")}>Value</span>
                  {sortField === 'value' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                </button>
                <button onClick={() => handleSort('roi')} className="flex items-center gap-1 justify-end hover:text-white transition-colors">
                  <span className={clsx(sortField === 'roi' && "text-accent font-bold")}>ROI</span>
                  {sortField === 'roi' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3 text-accent" /> : <ChevronDown className="w-3 h-3 text-accent" />)}
                </button>
                <div className="text-center">Yield</div>
                <div className="text-center">Health</div>
                <div className="text-right pr-1">Actions</div>
              </div>
              
              {/* Table Body */}
              <div className="divide-y divide-white/[0.04]">

              {filteredDomains.map((domain) => {
                const daysUntilRenewal = getDaysUntil(domain.renewal_date)
                const isExpiringSoon = daysUntilRenewal !== null && daysUntilRenewal <= 30 && daysUntilRenewal > 0
                const isExpired = daysUntilRenewal !== null && daysUntilRenewal <= 0
                const roiPositive = (domain.roi || 0) >= 0
                const isExpanded = expandedRow === domain.id
                const tags = domain.tags?.split(',').map(t => t.trim()).filter(Boolean) || []

                return (
                  <div 
                    key={domain.id} 
                    className={clsx(
                      "group transition-all",
                      domain.is_sold && "opacity-60"
                    )}
                  >
                    {/* DESKTOP ROW */}
                    <div className="hidden lg:grid grid-cols-[minmax(150px,1.5fr)_minmax(100px,1fr)_80px_70px_90px_70px_70px_50px_auto] gap-4 px-5 py-3 items-center group-hover:bg-white/[0.02]">
                      {/* Domain */}
                      <div className="flex items-center gap-3 min-w-0">
                        <button
                          onClick={() => openAnalyze(domain.domain)}
                          className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors text-left"
                        >
                          {domain.domain}
                        </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">
                          {renderStatusBadges(domain)}
                          {!domain.is_dns_verified && !domain.is_sold && (
                            <button
                              onClick={() => setVerifyingDomain(domain)}
                              className="text-amber-400 hover:text-amber-300"
                            >
                              Verify
                            </button>
                          )}
                        </div>
                      </div>

                      {/* Registrar */}
                      <div className="min-w-0">
                        <div className="text-sm font-mono text-white/60 truncate">{domain.registrar || '—'}</div>
                      </div>

                      {/* Purchased */}
                      <div className="text-center">
                        <div className="text-sm font-mono text-white/50">{formatShortDate(domain.purchase_date)}</div>
                      </div>

                      {/* Expires */}
                      <div className="text-center">
                        {domain.is_sold ? (
                          <span className="text-[10px] font-mono text-white/30 uppercase">Sold</span>
                        ) : (
                          <span className={clsx(
                            "text-sm font-mono",
                            isExpired ? "text-rose-400 font-bold" : isExpiringSoon ? "text-orange-400 font-bold" : "text-white/50"
                          )}>
                            {daysUntilRenewal !== null ? `${daysUntilRenewal}d` : '—'}
                          </span>
                        )}
                      </div>

                      {/* Value */}
                      <div className="text-right">
                        <span className="text-sm font-bold text-accent font-mono">{formatCurrency(domain.estimated_value)}</span>
                      </div>

                      {/* ROI */}
                      <div className="text-right">
                        <span className={clsx("text-sm font-bold font-mono", roiPositive ? "text-accent" : "text-rose-400")}>
                          {formatROI(domain.roi)}
                        </span>
                      </div>

                      {/* Yield */}
                      <div className="flex justify-center">
                        {renderYieldCell(domain)}
                      </div>

                      {/* Health */}
                      <div className="flex justify-center">
                        {renderHealth(domain)}
                      </div>

                      {/* Actions */}
                      <div className="flex items-center justify-end gap-1 opacity-40 group-hover:opacity-100 transition-all">
                        <button
                          onClick={() => openAnalyze(domain.domain)}
                          title="Analyze"
                          className="w-8 h-8 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-3.5 h-3.5" />
                        </button>
                        <button
                          onClick={() => setEditingDomain(domain)}
                          title="Edit"
                          className="w-8 h-8 flex items-center justify-center text-white/40 hover:text-white border border-white/10 hover:bg-white/5 transition-all"
                        >
                          <Edit3 className="w-3.5 h-3.5" />
                        </button>
                        <button
                          onClick={() => handleDelete(domain.id, domain.domain)}
                          disabled={deletingId === domain.id}
                          title="Remove"
                          className="w-8 h-8 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-3.5 h-3.5 animate-spin" />
                          ) : (
                            <Trash2 className="w-3.5 h-3.5" />
                          )}
                        </button>
                      </div>
                    </div>

                    {/* MOBILE ROW */}
                    <div className="lg:hidden">
                      <div 
                        className="p-3 cursor-pointer"
                        onClick={() => setExpandedRow(isExpanded ? null : domain.id)}
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div className="flex items-center gap-2.5 min-w-0 flex-1">
                            <div className="min-w-0 flex-1">
                              <div className="text-sm font-bold text-white font-mono truncate">{domain.domain}</div>
                              <div className="flex items-center gap-1.5 mt-0.5 flex-wrap">
                                {domain.registrar && (
                                  <span className="text-[10px] font-mono text-white/30">{domain.registrar}</span>
                                )}
                                {renderStatusBadges(domain)}
                    </div>
                </div>
                </div>
                          <div className="text-right shrink-0">
                            <div className="text-sm font-bold text-accent font-mono">{formatCurrency(domain.estimated_value)}</div>
                            <div className={clsx("text-[10px] font-mono", roiPositive ? "text-accent" : "text-rose-400")}>
                              {formatROI(domain.roi)}
        </div>
               </div>
            </div>
                
                        {/* Quick info row */}
                        <div className="flex items-center justify-between mt-2 pt-2 border-t border-white/[0.05] text-[10px] font-mono text-white/40">
                          <div className="flex items-center gap-3">
                            <span title="Purchase price">{formatCurrency(domain.purchase_price)}</span>
                            {daysUntilRenewal !== null && !domain.is_sold && (
                              <span className={clsx("flex items-center gap-1", isExpiringSoon ? "text-orange-400" : "")}>
                                <Calendar className="w-3 h-3" />{daysUntilRenewal}d
                              </span>
                            )}
              </div>
                          <ChevronDown className={clsx("w-4 h-4 transition-transform", isExpanded && "rotate-180")} />
            </div>
                </div>
                
                      {/* Expanded details */}
                      {isExpanded && (
                        <div className="px-3 pb-3 space-y-3 border-t border-white/[0.05]">
                          <div className="grid grid-cols-2 gap-3 pt-3 text-[10px] font-mono">
            <div>
                              <div className="text-white/30 uppercase mb-0.5">Purchased</div>
                              <div className="text-white/60">{formatDate(domain.purchase_date)}</div>
                              <div className="text-white/40">{formatCurrency(domain.purchase_price)}</div>
            </div>
                  <div>
                              <div className="text-white/30 uppercase mb-0.5">Renewal</div>
                              <div className={clsx(isExpiringSoon ? "text-orange-400" : "text-white/60")}>{formatDate(domain.renewal_date)}</div>
                              <div className="text-white/40">{formatCurrency(domain.renewal_cost)}/yr</div>
                  </div>
                </div>
                
                          {domain.notes && (
                            <div className="text-[10px] font-mono">
                              <div className="text-white/30 uppercase mb-0.5">Notes</div>
                              <div className="text-white/50">{domain.notes}</div>
                </div>
                          )}
                
                          {/* Actions */}
                          <div className="flex items-center gap-2 pt-2">
                            {renderHealth(domain)}
              <button
                              onClick={() => openAnalyze(domain.domain)}
                              className="flex items-center gap-1 px-2 py-1.5 text-[9px] font-mono uppercase border border-white/10 text-white/60 bg-white/5 hover:text-accent hover:border-accent/20 hover:bg-accent/10"
              >
                              <Shield className="w-3 h-3" />
                              Analyze
              </button>
                            <Link
                              href={
                                domain.is_dns_verified && !domain.is_sold
                                  ? `/terminal/yield?activate=${encodeURIComponent(domain.domain)}`
                                  : `/terminal/portfolio`
                              }
                              onClick={(e) => { if (!domain.is_dns_verified || domain.is_sold) e.preventDefault() }}
                              className={clsx(
                                "flex items-center gap-1 px-2 py-1.5 text-[9px] font-mono uppercase border",
                                domain.is_dns_verified && !domain.is_sold
                                  ? "border-white/10 text-white/60 bg-white/5 hover:text-white hover:bg-white/10"
                                  : "border-white/10 text-white/20 bg-white/[0.02] cursor-not-allowed"
                              )}
                            >
                              <Coins className="w-3 h-3" />
                              Yield
                            </Link>
                            {!domain.is_dns_verified && !domain.is_sold && (
              <button
                                onClick={() => setVerifyingDomain(domain)}
                                className="flex items-center gap-1 px-2 py-1.5 text-[9px] font-mono uppercase border border-amber-400/30 text-amber-400 bg-amber-400/5"
                              >
                                <ShieldCheck className="w-3 h-3" />Verify
                              </button>
                            )}
                            <button
                              onClick={() => setEditingDomain(domain)}
                              className="flex items-center gap-1 px-2 py-1.5 text-[9px] font-mono uppercase border border-white/10 text-white/60 bg-white/5"
                            >
                              <Edit3 className="w-3 h-3" />Edit
                            </button>
                            <button
                              onClick={() => handleRefreshValue(domain.id)}
                              disabled={refreshingId === domain.id}
                              className="p-1.5 text-white/30 hover:text-accent"
                            >
                              <RefreshCw className={clsx("w-4 h-4", refreshingId === domain.id && "animate-spin")} />
                            </button>
                            <button
                              onClick={() => handleDelete(domain.id, domain.domain)}
                              className="p-1.5 text-white/30 hover:text-rose-400 ml-auto"
                            >
                              <Trash2 className="w-4 h-4" />
              </button>
            </div>
            </div>
                      )}
                    </div>
                  </div>
                )
              })}
              </div>
            </div>
          )}
            </>
          )}
        </section>

        {/* MOBILE BOTTOM NAV */}
        <nav className="lg:hidden fixed bottom-0 inset-x-0 z-50 bg-[#020202]/95 backdrop-blur-md border-t border-white/[0.08] pb-safe">
          <div className="grid grid-cols-5 gap-1 px-2 py-2">
            {mobileNavItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={clsx(
                  "flex flex-col items-center gap-0.5 py-2 transition-colors",
                  item.active ? "text-accent" : "text-white/40"
                )}
              >
                <item.icon className="w-5 h-5" />
                <span className="text-[9px] font-mono uppercase tracking-wider">{item.label}</span>
              </Link>
            ))}
            <button
              onClick={() => setNavDrawerOpen(true)}
              className="flex flex-col items-center gap-0.5 py-2 text-white/40"
            >
              <Navigation className="w-5 h-5" />
              <span className="text-[9px] font-mono uppercase tracking-wider">Menu</span>
            </button>
               </div>
        </nav>

        {/* NAVIGATION DRAWER */}
        {navDrawerOpen && (
          <div className="lg:hidden fixed inset-0 z-50 bg-black/80 backdrop-blur-sm" onClick={() => setNavDrawerOpen(false)}>
            <div 
              className="absolute right-0 top-0 bottom-0 w-72 bg-[#0a0a0a] border-l border-white/10 overflow-y-auto"
              onClick={e => e.stopPropagation()}
            >
              <div className="p-4 border-b border-white/10 flex items-center justify-between">
                <span className="text-sm font-mono text-white">Navigation</span>
                <button onClick={() => setNavDrawerOpen(false)} className="p-2 text-white/40">
                  <X className="w-5 h-5" />
                </button>
                  </div>
              <div className="p-4 space-y-6">
                {drawerNavSections.map(section => (
                  <div key={section.title}>
                    <div className="text-[10px] font-mono text-white/30 uppercase tracking-wider mb-2">{section.title}</div>
                    <div className="space-y-1">
                      {section.items.map(item => (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={() => setNavDrawerOpen(false)}
                          className={clsx(
                            "flex items-center gap-3 px-3 py-2.5 transition-colors",
                            'active' in item && item.active ? "bg-accent/10 text-accent" : "text-white/60 hover:bg-white/5"
                          )}
                        >
                          <item.icon className="w-4 h-4" />
                          <span className="text-sm font-mono">{item.label}</span>
                        </Link>
                      ))}
              </div>
                  </div>
                ))}
                </div>
              {user && (
                <div className="p-4 border-t border-white/10 mt-4">
                  <div className="flex items-center gap-3 mb-4">
                    <div className="w-10 h-10 bg-accent/10 border border-accent/20 flex items-center justify-center">
                      <TierIcon className="w-5 h-5 text-accent" />
              </div>
                  <div>
                      <div className="text-sm font-mono text-white">{user.email?.split('@')[0]}</div>
                      <div className="text-[10px] font-mono text-accent uppercase">{tierName}</div>
            </div>
                </div>
                  <div className="space-y-1">
                    <Link href="/terminal/settings" className="flex items-center gap-3 px-3 py-2 text-white/60 hover:bg-white/5">
                      <Settings className="w-4 h-4" /><span className="text-sm font-mono">Settings</span>
                    </Link>
                    <button onClick={logout} className="w-full flex items-center gap-3 px-3 py-2 text-white/60 hover:bg-white/5">
                      <LogOut className="w-4 h-4" /><span className="text-sm font-mono">Logout</span>
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </main>

      {/* MODALS */}
      {showAddModal && (
        <AddModal 
          onClose={() => setShowAddModal(false)} 
          onAdd={handleAddDomain}
          onStartVerify={(domain) => setVerifyingDomain(domain)}
        />
      )}
      {editingDomain && (
        <EditModal 
          domain={editingDomain} 
          onClose={() => setEditingDomain(null)} 
          onSave={(data) => handleUpdateDomain(editingDomain.id, data)}
        />
      )}
      {verifyingDomain && (
        <VerifyModal
          domain={verifyingDomain}
          onClose={() => setVerifyingDomain(null)}
          onVerified={() => {
            loadData()
            showToast('Domain verified!', 'success')
          }}
        />
      )}
      
      {/* HEALTH DETAIL OVERLAY */}
      {selectedHealthDomain && (
        <div 
          className="fixed inset-0 z-[100] bg-black/80 flex items-center justify-center p-4"
          onClick={() => setSelectedHealthDomain(null)}
        >
          <div 
            className="w-full max-w-md bg-[#0A0A0A] border border-white/[0.08]"
            onClick={e => e.stopPropagation()}
          >
            {/* Header */}
            <div className="px-5 py-4 border-b border-white/[0.08] flex items-center justify-between">
              <div>
                <div className="text-[10px] font-mono text-white/40 uppercase tracking-wider mb-1">Health Check</div>
                <h3 className="text-lg font-bold text-white font-mono">{selectedHealthDomain.domain}</h3>
              </div>
              <button
                onClick={() => setSelectedHealthDomain(null)}
                className="p-2 text-white/40 hover:text-white transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            
            {/* Body */}
            <div className="p-5">
              {(() => {
                const key = selectedHealthDomain.domain.toLowerCase()
                const health = healthByDomain[key]
                const isLoading = checkingHealth.has(key)
                const cfg = healthConfig[(health?.status as HealthStatus) || 'unknown']
                
                return (
                  <>
                    {/* Score Badge */}
                    <div className="flex items-center gap-3 mb-5">
                      <div className={clsx(
                        "px-3 py-1.5 text-sm font-mono font-bold uppercase border",
                        cfg.bg, cfg.color, cfg.border
                      )}>
                        {cfg.label}
            </div>
                      {health?.score !== undefined && (
                        <span className="text-sm font-mono text-white/60">Score: {health.score}/100</span>
                      )}
            </div>
              
                    {/* Checks */}
                    {health ? (
                      <div className="space-y-px mb-5 border border-white/[0.08]">
                        {/* DNS */}
                        <div className="flex items-center justify-between px-4 py-3 bg-[#020202]">
                          <span className="text-sm font-mono text-white/70">DNS Resolution</span>
                          {health.dns?.has_a || health.dns?.has_ns ? (
                            <div className="flex items-center gap-2">
                              <CheckCircle2 className="w-5 h-5 text-accent" />
                              <span className="text-sm font-mono text-accent font-bold">OK</span>
                            </div>
                          ) : (
                            <div className="flex items-center gap-2">
                              <XCircle className="w-5 h-5 text-rose-400" />
                              <span className="text-sm font-mono text-rose-400 font-bold">FAIL</span>
                            </div>
                          )}
              </div>
                
                        {/* HTTP */}
                        <div className="flex items-center justify-between px-4 py-3 bg-[#020202]">
                          <span className="text-sm font-mono text-white/70">HTTP Access</span>
                          {health.http?.is_reachable ? (
                            <div className="flex items-center gap-2">
                              <CheckCircle2 className="w-5 h-5 text-accent" />
                              <span className="text-sm font-mono text-accent font-bold">OK</span>
              </div>
                          ) : (
                            <div className="flex items-center gap-2">
                              <XCircle className="w-5 h-5 text-rose-400" />
                              <span className="text-sm font-mono text-rose-400 font-bold">{health.http?.error?.substring(0, 15) || 'FAIL'}</span>
            </div>
                  )}
                </div>
                
                        {/* SSL */}
                        <div className="flex items-center justify-between px-4 py-3 bg-[#020202]">
                          <span className="text-sm font-mono text-white/70">SSL Certificate</span>
                          {health.ssl?.has_certificate ? (
                            <div className="flex items-center gap-2">
                              <CheckCircle2 className="w-5 h-5 text-accent" />
                              <span className="text-sm font-mono text-accent font-bold">VALID</span>
            </div>
                          ) : (
                            <div className="flex items-center gap-2">
                              <XCircle className="w-5 h-5 text-rose-400" />
                              <span className="text-sm font-mono text-rose-400 font-bold">MISSING</span>
              </div>
        )}
        </div>

                        {/* Parked Status */}
                        <div className="flex items-center justify-between px-4 py-3 bg-[#020202]">
                          <span className="text-sm font-mono text-white/70">Not Parked</span>
                          {!health.dns?.is_parked && !health.http?.is_parked ? (
                            <div className="flex items-center gap-2">
                              <CheckCircle2 className="w-5 h-5 text-accent" />
                              <span className="text-sm font-mono text-accent font-bold">OK</span>
              </div>
                          ) : (
                            <div className="flex items-center gap-2">
                              <AlertTriangle className="w-5 h-5 text-amber-400" />
                              <span className="text-sm font-mono text-amber-400 font-bold">PARKED</span>
                            </div>
                    )}
                  </div>
        </div>
                    ) : (
                      <div className="py-10 text-center text-white/40 text-sm font-mono mb-5 border border-white/[0.08] bg-[#020202]">
                        {isLoading ? 'Running health check...' : 'Click below to run health check'}
        </div>
                    )}
                
                    {/* Run Check Button */}
                  <button
                      onClick={() => handleHealthCheck(selectedHealthDomain.domain)}
                      disabled={isLoading}
                      className="w-full py-3.5 bg-accent text-black text-sm font-bold uppercase tracking-wider hover:bg-white transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
                    >
                      {isLoading ? (
                        <Loader2 className="w-5 h-5 animate-spin" />
                      ) : (
                        <>
                          <RefreshCw className="w-5 h-5" />
                          {health ? 'Refresh Check' : 'Run Check'}
                        </>
                      )}
                  </button>
                  </>
                )
              })()}
        </div>
        </div>
      </div>
        )}
      
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
    </div>
  )
}
