'use client'

import { useEffect, useState, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { useStore } from '@/lib/store'
import { api, PortfolioDomain, PortfolioSummary, DomainValuation } from '@/lib/api'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { Toast, useToast } from '@/components/Toast'
import {
  Plus,
  Trash2,
  RefreshCw,
  Loader2,
  Clock,
  AlertCircle,
  Calendar,
  History,
  Bell,
  BellOff,
  Check,
  X,
  Zap,
  Crown,
  Briefcase,
  Eye,
  DollarSign,
  Tag,
  Edit2,
  Sparkles,
  CreditCard,
  Globe,
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

type TabType = 'watchlist' | 'portfolio'

interface DomainHistory {
  id: number
  status: string
  is_available: boolean
  checked_at: string
}

function DashboardContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const {
    isAuthenticated,
    isLoading,
    checkAuth,
    domains,
    subscription,
    addDomain,
    deleteDomain,
    refreshDomain,
  } = useStore()

  const { toast, showToast, hideToast } = useToast()
  const [activeTab, setActiveTab] = useState<TabType>('watchlist')
  const [newDomain, setNewDomain] = useState('')
  const [adding, setAdding] = useState(false)
  const [refreshingId, setRefreshingId] = useState<number | null>(null)
  const [error, setError] = useState<string | null>(null)
  
  // Check for upgrade success
  useEffect(() => {
    if (searchParams.get('upgraded') === 'true') {
      showToast('Welcome to your upgraded plan! 🎉', 'success')
      // Clean up URL
      window.history.replaceState({}, '', '/dashboard')
    }
  }, [searchParams])
  const [selectedDomainId, setSelectedDomainId] = useState<number | null>(null)
  const [domainHistory, setDomainHistory] = useState<DomainHistory[] | null>(null)
  const [loadingHistory, setLoadingHistory] = useState(false)
  const [portfolio, setPortfolio] = useState<PortfolioDomain[]>([])
  const [portfolioSummary, setPortfolioSummary] = useState<PortfolioSummary | null>(null)
  const [loadingPortfolio, setLoadingPortfolio] = useState(false)
  const [showAddPortfolioModal, setShowAddPortfolioModal] = useState(false)
  const [showValuationModal, setShowValuationModal] = useState(false)
  const [valuationResult, setValuationResult] = useState<DomainValuation | null>(null)
  const [valuatingDomain, setValuatingDomain] = useState<string>('')
  const [refreshingPortfolioId, setRefreshingPortfolioId] = useState<number | null>(null)
  const [portfolioForm, setPortfolioForm] = useState({
    domain: '',
    purchase_price: '',
    purchase_date: '',
    registrar: '',
    renewal_date: '',
    renewal_cost: '',
    notes: '',
  })
  const [addingPortfolio, setAddingPortfolio] = useState(false)
  const [showEditPortfolioModal, setShowEditPortfolioModal] = useState(false)
  const [editingPortfolioDomain, setEditingPortfolioDomain] = useState<PortfolioDomain | null>(null)
  const [editPortfolioForm, setEditPortfolioForm] = useState({
    purchase_price: '',
    purchase_date: '',
    registrar: '',
    renewal_date: '',
    renewal_cost: '',
    notes: '',
  })
  const [savingEdit, setSavingEdit] = useState(false)
  const [showSellModal, setShowSellModal] = useState(false)
  const [sellingDomain, setSellingDomain] = useState<PortfolioDomain | null>(null)
  const [sellForm, setSellForm] = useState({
    sale_date: new Date().toISOString().split('T')[0],
    sale_price: '',
  })
  const [processingSale, setProcessingSale] = useState(false)
  const [togglingNotifyId, setTogglingNotifyId] = useState<number | null>(null)

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

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push('/login')
    }
  }, [isLoading, isAuthenticated, router])

  // Load portfolio data on mount (so we can show count in tab)
  useEffect(() => {
    if (isAuthenticated) {
      loadPortfolio()
    }
  }, [isAuthenticated])

  const handleOpenBillingPortal = async () => {
    try {
      const { portal_url } = await api.createPortalSession()
      window.location.href = portal_url
    } catch (err: any) {
      setError(err.message || 'Failed to open billing portal')
    }
  }

  const loadPortfolio = async () => {
    setLoadingPortfolio(true)
    try {
      const [portfolioData, summaryData] = await Promise.all([
        api.getPortfolio(),
        api.getPortfolioSummary(),
      ])
      setPortfolio(portfolioData)
      setPortfolioSummary(summaryData)
    } catch (err) {
      console.error('Failed to load portfolio:', err)
    } finally {
      setLoadingPortfolio(false)
    }
  }

  const handleAddDomain = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newDomain.trim()) return
    setAdding(true)
    setError(null)
    try {
      await addDomain(newDomain)
      showToast(`Added ${newDomain} to watchlist`, 'success')
      setNewDomain('')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to add domain')
    } finally {
      setAdding(false)
    }
  }

  const handleRefresh = async (id: number) => {
    setRefreshingId(id)
    try {
      await refreshDomain(id)
    } finally {
      setRefreshingId(null)
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('Remove this domain from your watchlist?')) return
    await deleteDomain(id)
  }

  const loadDomainHistory = async (domainId: number) => {
    if (!subscription?.features?.expiration_tracking) {
      setError('Check history requires Trader or Tycoon plan')
      return
    }
    setSelectedDomainId(domainId)
    setLoadingHistory(true)
    try {
      const result = await api.getDomainHistory(domainId, 30)
      setDomainHistory(result.history)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load history')
    } finally {
      setLoadingHistory(false)
    }
  }

  const handleAddPortfolioDomain = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!portfolioForm.domain.trim()) return
    setAddingPortfolio(true)
    try {
      await api.addPortfolioDomain({
        domain: portfolioForm.domain,
        purchase_price: portfolioForm.purchase_price ? parseFloat(portfolioForm.purchase_price) : undefined,
        purchase_date: portfolioForm.purchase_date || undefined,
        registrar: portfolioForm.registrar || undefined,
        renewal_date: portfolioForm.renewal_date || undefined,
        renewal_cost: portfolioForm.renewal_cost ? parseFloat(portfolioForm.renewal_cost) : undefined,
        notes: portfolioForm.notes || undefined,
      })
      setPortfolioForm({ domain: '', purchase_price: '', purchase_date: '', registrar: '', renewal_date: '', renewal_cost: '', notes: '' })
      setShowAddPortfolioModal(false)
      showToast(`Added ${portfolioForm.domain} to portfolio`, 'success')
      loadPortfolio()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to add domain to portfolio')
    } finally {
      setAddingPortfolio(false)
    }
  }

  const handleDeletePortfolioDomain = async (id: number) => {
    if (!confirm('Remove this domain from your portfolio?')) return
    try {
      await api.deletePortfolioDomain(id)
      showToast('Domain removed from portfolio', 'success')
      loadPortfolio()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete domain')
    }
  }

  const handleRefreshPortfolioValue = async (id: number) => {
    setRefreshingPortfolioId(id)
    try {
      await api.refreshDomainValue(id)
      loadPortfolio()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to refresh value')
    } finally {
      setRefreshingPortfolioId(null)
    }
  }

  const handleGetValuation = async (domain: string) => {
    setValuatingDomain(domain)
    setShowValuationModal(true)
    try {
      const result = await api.getDomainValuation(domain)
      setValuationResult(result)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to get valuation')
      setShowValuationModal(false)
    } finally {
      setValuatingDomain('')
    }
  }

  const handleToggleNotify = async (domainId: number, currentNotify: boolean) => {
    setTogglingNotifyId(domainId)
    try {
      await api.updateDomainNotify(domainId, !currentNotify)
      const { fetchDomains } = useStore.getState()
      await fetchDomains()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update notification setting')
    } finally {
      setTogglingNotifyId(null)
    }
  }

  const handleOpenEditPortfolio = (domain: PortfolioDomain) => {
    setEditingPortfolioDomain(domain)
    setEditPortfolioForm({
      purchase_price: domain.purchase_price?.toString() || '',
      purchase_date: domain.purchase_date || '',
      registrar: domain.registrar || '',
      renewal_date: domain.renewal_date || '',
      renewal_cost: domain.renewal_cost?.toString() || '',
      notes: domain.notes || '',
    })
    setShowEditPortfolioModal(true)
  }

  const handleSaveEditPortfolio = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!editingPortfolioDomain) return
    setSavingEdit(true)
    try {
      await api.updatePortfolioDomain(editingPortfolioDomain.id, {
        purchase_price: editPortfolioForm.purchase_price ? parseFloat(editPortfolioForm.purchase_price) : undefined,
        purchase_date: editPortfolioForm.purchase_date || undefined,
        registrar: editPortfolioForm.registrar || undefined,
        renewal_date: editPortfolioForm.renewal_date || undefined,
        renewal_cost: editPortfolioForm.renewal_cost ? parseFloat(editPortfolioForm.renewal_cost) : undefined,
        notes: editPortfolioForm.notes || undefined,
      })
      setShowEditPortfolioModal(false)
      setEditingPortfolioDomain(null)
      showToast('Domain updated', 'success')
      loadPortfolio()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update domain')
    } finally {
      setSavingEdit(false)
    }
  }

  const handleOpenSellModal = (domain: PortfolioDomain) => {
    setSellingDomain(domain)
    setSellForm({ sale_date: new Date().toISOString().split('T')[0], sale_price: '' })
    setShowSellModal(true)
  }

  const handleSellDomain = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!sellingDomain || !sellForm.sale_price) return
    setProcessingSale(true)
    try {
      await api.markDomainSold(sellingDomain.id, sellForm.sale_date, parseFloat(sellForm.sale_price))
      setShowSellModal(false)
      const soldDomainName = sellingDomain.domain
      setSellingDomain(null)
      showToast(`Marked ${soldDomainName} as sold 🎉`, 'success')
      loadPortfolio()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to mark domain as sold')
    } finally {
      setProcessingSale(false)
    }
  }

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return 'Not checked'
    const date = new Date(dateStr)
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
  }

  const formatExpirationDate = (dateStr: string | null) => {
    if (!dateStr) return null
    const date = new Date(dateStr)
    const now = new Date()
    const daysUntil = Math.ceil((date.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
    if (daysUntil < 0) return { text: 'Expired', urgent: true }
    if (daysUntil <= 7) return { text: `${daysUntil}d`, urgent: true }
    if (daysUntil <= 30) return { text: `${daysUntil}d`, urgent: false }
    return { text: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), urgent: false }
  }

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

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <Loader2 className="w-6 h-6 animate-spin text-accent" />
      </div>
    )
  }

  if (!isAuthenticated) return null

  const canAddMore = subscription ? subscription.domains_used < subscription.domain_limit : true
  const availableCount = domains.filter(d => d.is_available).length
  const expiringCount = domains.filter(d => {
    if (!d.expiration_date) return false
    const daysUntil = Math.ceil((new Date(d.expiration_date).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))
    return daysUntil <= 30 && daysUntil > 0
  }).length

  const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const isProOrHigher = tierName === 'Professional' || tierName === 'Enterprise' || tierName === 'Trader' || tierName === 'Tycoon'
  const isEnterprise = tierName === 'Enterprise' || tierName === 'Tycoon'
  
  // Feature flags based on subscription
  const hasPortfolio = (subscription?.portfolio_limit ?? 0) !== 0 || subscription?.features?.domain_valuation
  const hasDomainValuation = subscription?.features?.domain_valuation ?? false
  const hasExpirationTracking = subscription?.features?.expiration_tracking ?? false
  const hasHistory = (subscription?.history_days ?? 0) > 0

  return (
    <div className="min-h-screen bg-background relative overflow-hidden">
      {/* Background Effects - matching landing page */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
        <div 
          className="absolute inset-0 opacity-[0.015]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.1) 1px, transparent 1px)`,
            backgroundSize: '64px 64px',
          }}
        />
      </div>
      
      <Header />

      <main className="relative flex-1 pt-32 sm:pt-40 pb-20 sm:pb-28 px-4 sm:px-6 lg:px-8">
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-6 mb-12 animate-fade-in">
            <div>
              <span className="text-sm font-semibold text-accent uppercase tracking-wider">Command Center</span>
              <h1 className="mt-4 font-display text-[2rem] sm:text-[2.75rem] md:text-[3.5rem] leading-[1.1] tracking-[-0.03em] text-foreground">
                Your hunting ground.
              </h1>
              <p className="mt-3 text-lg text-foreground-muted">
                Your domains. Your intel. Your edge.
              </p>
            </div>
            <div className="flex items-center gap-3">
              <span className={clsx(
                "flex items-center gap-2 text-sm px-4 py-2 rounded-xl border font-medium transition-all",
                isEnterprise ? "bg-accent/10 border-accent/20 text-accent" : "bg-background-secondary/50 border-border text-foreground-muted"
              )}>
                {isEnterprise && <Crown className="w-4 h-4" />}
                {tierName}
              </span>
              {isProOrHigher ? (
                <button onClick={handleOpenBillingPortal} className="flex items-center gap-2 px-4 py-2 text-sm text-foreground-muted hover:text-foreground border border-border rounded-xl hover:border-accent/30 hover:bg-background-secondary/50 transition-all">
                  <CreditCard className="w-4 h-4" />
                  Billing
                </button>
              ) : (
                <Link href="/pricing" className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-background bg-accent rounded-xl hover:bg-accent-hover shadow-[0_0_20px_rgba(16,185,129,0.15)] transition-all">
                  <Zap className="w-4 h-4" />
                  Upgrade
                </Link>
              )}
            </div>
          </div>

          {/* Tabs - Landing Page Style */}
          <div className="flex items-center gap-2 p-2 bg-background-secondary/50 backdrop-blur-sm border border-border rounded-2xl w-fit mb-12">
            <button
              onClick={() => setActiveTab('watchlist')}
              className={clsx(
                "flex items-center gap-2.5 px-6 py-3 text-sm font-medium rounded-xl transition-all duration-300",
                activeTab === 'watchlist' 
                  ? "bg-accent text-background shadow-lg shadow-accent/20" 
                  : "text-foreground-muted hover:text-foreground hover:bg-foreground/5"
              )}
            >
              <Eye className="w-4 h-4" />
              Watchlist
              {domains.length > 0 && (
                <span className={clsx(
                  "text-xs px-2 py-0.5 rounded-lg",
                  activeTab === 'watchlist' ? "bg-background/20" : "bg-foreground/10"
                )}>{domains.length}</span>
              )}
            </button>
            {hasPortfolio ? (
              <button
                onClick={() => setActiveTab('portfolio')}
                className={clsx(
                  "flex items-center gap-2.5 px-6 py-3 text-sm font-medium rounded-xl transition-all duration-300",
                  activeTab === 'portfolio' 
                    ? "bg-accent text-background shadow-lg shadow-accent/20" 
                    : "text-foreground-muted hover:text-foreground hover:bg-foreground/5"
                )}
              >
                <Briefcase className="w-4 h-4" />
                Portfolio
                {portfolio.length > 0 && (
                  <span className={clsx(
                    "text-xs px-2 py-0.5 rounded-lg",
                    activeTab === 'portfolio' ? "bg-background/20" : "bg-foreground/10"
                  )}>{portfolio.length}</span>
                )}
              </button>
            ) : (
              <Link
                href="/pricing"
                className="flex items-center gap-2.5 px-6 py-3 text-sm font-medium rounded-xl text-foreground-muted hover:text-foreground hover:bg-foreground/5 transition-all duration-300"
              >
                <Briefcase className="w-4 h-4" />
                Portfolio
                <span className="text-xs px-2 py-0.5 rounded-lg bg-accent/10 text-accent border border-accent/20">Pro</span>
              </Link>
            )}
          </div>

          {error && (
            <div className="mb-6 p-4 bg-danger/10 border border-danger/20 rounded-xl flex items-center gap-3">
              <AlertCircle className="w-5 h-5 text-danger shrink-0" />
              <p className="text-body-sm text-danger flex-1">{error}</p>
              <button onClick={() => setError(null)} className="text-danger hover:text-danger/80"><X className="w-4 h-4" /></button>
            </div>
          )}

          {/* Watchlist Tab */}
          {activeTab === 'watchlist' && (
            <div className="space-y-8">
              {/* Stats Row - Landing Page Style */}
              <div className={clsx("grid gap-5", hasExpirationTracking ? "grid-cols-2 sm:grid-cols-4" : "grid-cols-3")}>
                <div className="group relative p-6 bg-background-secondary/50 border border-border rounded-2xl hover:border-accent/30 hover:bg-background-secondary transition-all duration-300">
                  <div className="absolute inset-0 rounded-2xl bg-accent/5 opacity-0 group-hover:opacity-100 transition-opacity" />
                  <div className="relative">
                    <div className="w-10 h-10 bg-foreground/5 border border-border rounded-xl flex items-center justify-center mb-4 group-hover:border-accent/30 group-hover:bg-accent/5 transition-all">
                      <Globe className="w-5 h-5 text-foreground-muted group-hover:text-accent transition-colors" />
                    </div>
                    <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-1">Tracked</p>
                    <p className="text-4xl font-display text-foreground">{domains.length}</p>
                  </div>
                </div>
                <div className="group relative p-6 bg-background-secondary/50 border border-border rounded-2xl hover:border-accent/30 hover:bg-background-secondary transition-all duration-300">
                  <div className="absolute inset-0 rounded-2xl bg-accent/5 opacity-0 group-hover:opacity-100 transition-opacity" />
                  <div className="relative">
                    <div className="w-10 h-10 bg-accent/10 border border-accent/20 rounded-xl flex items-center justify-center mb-4">
                      <Check className="w-5 h-5 text-accent" />
                    </div>
                    <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-1">Available</p>
                    <p className="text-4xl font-display text-accent">{availableCount}</p>
                  </div>
                </div>
                <div className="group relative p-6 bg-background-secondary/50 border border-border rounded-2xl hover:border-accent/30 hover:bg-background-secondary transition-all duration-300">
                  <div className="absolute inset-0 rounded-2xl bg-accent/5 opacity-0 group-hover:opacity-100 transition-opacity" />
                  <div className="relative">
                    <div className="w-10 h-10 bg-foreground/5 border border-border rounded-xl flex items-center justify-center mb-4 group-hover:border-accent/30 group-hover:bg-accent/5 transition-all">
                      <Bell className="w-5 h-5 text-foreground-muted group-hover:text-accent transition-colors" />
                    </div>
                    <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-1">Monitoring</p>
                    <p className="text-4xl font-display text-foreground">{domains.filter(d => d.notify_on_available).length}</p>
                  </div>
                </div>
                {hasExpirationTracking && (
                  <div className="group relative p-6 bg-background-secondary/50 border border-border rounded-2xl hover:border-accent/30 hover:bg-background-secondary transition-all duration-300">
                    <div className="absolute inset-0 rounded-2xl bg-accent/5 opacity-0 group-hover:opacity-100 transition-opacity" />
                    <div className="relative">
                      <div className="w-10 h-10 bg-orange-500/10 border border-orange-500/20 rounded-xl flex items-center justify-center mb-4">
                        <Clock className="w-5 h-5 text-orange-500" />
                      </div>
                      <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-1">Expiring</p>
                      <p className="text-4xl font-display text-orange-500">{expiringCount}</p>
                    </div>
                  </div>
                )}
              </div>

              {/* Limit Warning */}
              {!canAddMore && (
                <div className="p-4 bg-warning/5 border border-warning/20 rounded-xl flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                  <div className="flex items-center gap-3">
                    <AlertCircle className="w-5 h-5 text-warning shrink-0" />
                    <div>
                      <p className="text-body-sm font-medium text-foreground">You've reached your domain limit</p>
                      <p className="text-body-xs text-foreground-muted">Upgrade to track more domains and unlock premium features</p>
                    </div>
                  </div>
                  <Link href="/pricing" className="flex items-center justify-center gap-2 px-4 py-2 bg-accent text-background text-ui-sm font-medium rounded-lg hover:bg-accent-hover transition-all whitespace-nowrap">
                    <Zap className="w-4 h-4" />
                    Upgrade Now
                  </Link>
                </div>
              )}

              {/* Add Domain */}
              <form onSubmit={handleAddDomain} className="flex gap-3">
                <div className="flex-1 relative">
                  <Plus className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-subtle" />
                  <input
                    type="text"
                    value={newDomain}
                    onChange={(e) => setNewDomain(e.target.value)}
                    placeholder="Add domain to watchlist..."
                    disabled={!canAddMore}
                    className="w-full pl-12 pr-4 py-3 bg-background-secondary border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 disabled:opacity-50 transition-all"
                  />
                </div>
                <button type="submit" disabled={adding || !newDomain.trim() || !canAddMore} className="px-5 py-3 bg-foreground text-background text-ui-sm font-medium rounded-xl hover:bg-foreground/90 disabled:opacity-40 transition-all flex items-center gap-2">
                  {adding ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                  Add
                </button>
              </form>

              {/* Domain Table */}
              {domains.length === 0 ? (
                <div className="text-center py-20 border border-dashed border-border/50 rounded-2xl bg-background-secondary/20">
                  <div className="w-14 h-14 bg-foreground/5 rounded-2xl flex items-center justify-center mx-auto mb-5">
                    <Eye className="w-7 h-7 text-foreground-subtle" />
                  </div>
                  <p className="text-body-lg text-foreground-muted mb-1">No domains tracked yet</p>
                  <p className="text-body-sm text-foreground-subtle">Add your first domain above to start monitoring</p>
                </div>
              ) : (
                <div className="border border-border rounded-2xl overflow-hidden bg-background-secondary/30">
                  <table className="w-full">
                    <thead className="bg-background-secondary/80 backdrop-blur-sm">
                      <tr className="border-b border-border">
                        <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4">Domain</th>
                        <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4 hidden sm:table-cell">Status</th>
                        {hasExpirationTracking && (
                          <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4 hidden lg:table-cell">Expiration</th>
                        )}
                        <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4 hidden md:table-cell">Last Check</th>
                        <th className="text-right text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border/50">
                      {domains.map((domain) => {
                        const exp = formatExpirationDate(domain.expiration_date)
                        const isMonitoring = domain.notify_on_available
                        return (
                          <tr key={domain.id} className="group hover:bg-background-secondary/60 transition-all duration-200">
                            <td className="px-5 py-4">
                              <div className="flex items-center gap-3">
                                <div className="relative">
                                  <div className={clsx(
                                    "w-2.5 h-2.5 rounded-full",
                                    domain.is_available ? "bg-accent" : isMonitoring ? "bg-accent" : "bg-foreground-subtle"
                                  )} />
                                  {isMonitoring && (
                                    <span className="absolute inset-0 rounded-full bg-accent animate-ping opacity-40" />
                                  )}
                                </div>
                                <span className="font-mono text-body-sm text-foreground">{domain.name}</span>
                              </div>
                            </td>
                            <td className="px-5 py-4 hidden sm:table-cell">
                              <span className={clsx(
                                "text-ui-xs px-2.5 py-1 rounded-full",
                                domain.is_available 
                                  ? "text-accent bg-accent/10" 
                                  : isMonitoring 
                                    ? "text-accent bg-accent/10"
                                    : "text-foreground-muted bg-foreground/5"
                              )}>
                                {domain.is_available ? 'Available' : isMonitoring ? 'Monitoring' : 'Registered'}
                              </span>
                            </td>
                            {hasExpirationTracking && (
                              <td className="px-5 py-4 hidden lg:table-cell">
                                {exp ? (
                                  <span className={clsx(
                                    "text-body-sm flex items-center gap-1.5",
                                    exp.urgent ? "text-warning font-medium" : "text-foreground-subtle"
                                  )}>
                                    <Calendar className="w-3.5 h-3.5" />{exp.text}
                                  </span>
                                ) : <span className="text-foreground-subtle/50">—</span>}
                              </td>
                            )}
                            <td className="px-5 py-4 hidden md:table-cell">
                              <span className="text-body-sm text-foreground-subtle flex items-center gap-1.5">
                                <Clock className="w-3.5 h-3.5" />{formatDate(domain.last_checked)}
                              </span>
                            </td>
                            <td className="px-5 py-4">
                              <div className="flex items-center justify-end gap-0.5 opacity-50 group-hover:opacity-100 transition-opacity">
                                {hasHistory && (
                                  <button onClick={() => loadDomainHistory(domain.id)} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/10 rounded-lg transition-all" title="History">
                                    <History className="w-4 h-4" />
                                  </button>
                                )}
                                {hasDomainValuation ? (
                                  <button onClick={() => handleGetValuation(domain.name)} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/10 rounded-lg transition-all" title="Valuation">
                                    <Sparkles className="w-4 h-4" />
                                  </button>
                                ) : (
                                  <Link href="/pricing" className="p-2 text-foreground-subtle/50 hover:text-accent hover:bg-accent/10 rounded-lg transition-all" title="Upgrade for Valuation">
                                    <Sparkles className="w-4 h-4" />
                                  </Link>
                                )}
                                <button
                                  onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                                  disabled={togglingNotifyId === domain.id}
                                  className={clsx(
                                    "p-2 rounded-lg transition-all",
                                    domain.notify_on_available 
                                      ? "text-accent hover:bg-accent/10" 
                                      : "text-foreground-subtle hover:text-foreground hover:bg-foreground/10"
                                  )}
                                  title={domain.notify_on_available ? "Monitoring active" : "Enable monitoring"}
                                >
                                  {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>
                                <button onClick={() => handleRefresh(domain.id)} disabled={refreshingId === domain.id} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/10 rounded-lg transition-all" title="Refresh">
                                  <RefreshCw className={clsx("w-4 h-4", refreshingId === domain.id && "animate-spin")} />
                                </button>
                                <button onClick={() => handleDelete(domain.id)} className="p-2 text-foreground-subtle hover:text-danger hover:bg-danger/10 rounded-lg transition-all" title="Remove">
                                  <Trash2 className="w-4 h-4" />
                                </button>
                              </div>
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

          {/* Portfolio Tab */}
          {activeTab === 'portfolio' && (
            <div className="space-y-6">
              {/* Portfolio Stats */}
              {portfolioSummary && (
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                  <div className="p-5 bg-background-secondary border border-border rounded-2xl hover:border-foreground/20 transition-colors">
                    <p className="text-ui-xs text-foreground-muted uppercase tracking-wider mb-2">Total Value</p>
                    <p className="text-2xl sm:text-3xl font-display text-foreground">{formatCurrency(portfolioSummary.total_value)}</p>
                  </div>
                  <div className="p-5 bg-background-secondary border border-border rounded-2xl hover:border-foreground/20 transition-colors">
                    <p className="text-ui-xs text-foreground-muted uppercase tracking-wider mb-2">Invested</p>
                    <p className="text-2xl sm:text-3xl font-display text-foreground">{formatCurrency(portfolioSummary.total_invested)}</p>
                  </div>
                  <div className="p-5 bg-background-secondary border border-border rounded-2xl hover:border-foreground/20 transition-colors">
                    <p className="text-ui-xs text-foreground-muted uppercase tracking-wider mb-2">P/L</p>
                    <p className={clsx("text-2xl sm:text-3xl font-display flex items-center gap-1", portfolioSummary.unrealized_profit >= 0 ? "text-accent" : "text-danger")}>
                      {portfolioSummary.unrealized_profit >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.unrealized_profit)}
                    </p>
                  </div>
                  <div className="p-5 bg-background-secondary border border-border rounded-2xl hover:border-foreground/20 transition-colors">
                    <p className="text-ui-xs text-foreground-muted uppercase tracking-wider mb-2">ROI</p>
                    <p className={clsx("text-2xl sm:text-3xl font-display", portfolioSummary.overall_roi >= 0 ? "text-accent" : "text-danger")}>
                      {portfolioSummary.overall_roi >= 0 ? '+' : ''}{portfolioSummary.overall_roi.toFixed(1)}%
                    </p>
                  </div>
                </div>
              )}

              {/* Add Domain */}
              <button onClick={() => setShowAddPortfolioModal(true)} className="flex items-center gap-2 px-5 py-3 bg-foreground text-background text-ui-sm font-medium rounded-xl hover:bg-foreground/90 transition-all">
                <Plus className="w-4 h-4" />
                Add Domain
              </button>

              {loadingPortfolio ? (
                <div className="flex justify-center py-20"><Loader2 className="w-7 h-7 animate-spin text-accent" /></div>
              ) : portfolio.length === 0 ? (
                <div className="text-center py-20 border border-dashed border-border/50 rounded-2xl bg-background-secondary/20">
                  <div className="w-14 h-14 bg-foreground/5 rounded-2xl flex items-center justify-center mx-auto mb-5">
                    <Briefcase className="w-7 h-7 text-foreground-subtle" />
                  </div>
                  <p className="text-body-lg text-foreground-muted mb-1">Your portfolio is empty</p>
                  <p className="text-body-sm text-foreground-subtle">Add domains you own to track their value and ROI</p>
                </div>
              ) : (
                <div className="border border-border rounded-2xl overflow-hidden bg-background-secondary/30">
                  <table className="w-full">
                    <thead className="bg-background-secondary/80 backdrop-blur-sm">
                      <tr className="border-b border-border">
                        <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4">Domain</th>
                        <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4 hidden sm:table-cell">Purchased</th>
                        <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4 hidden md:table-cell">Value</th>
                        <th className="text-left text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4 hidden lg:table-cell">Renewal</th>
                        <th className="text-right text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4">ROI</th>
                        <th className="text-right text-ui-xs font-medium text-foreground-muted uppercase tracking-wider px-5 py-4">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border/50">
                      {portfolio.map((domain) => {
                        const roi = domain.roi
                        const renewal = formatExpirationDate(domain.renewal_date)
                        return (
                          <tr key={domain.id} className="group hover:bg-background-secondary/60 transition-all duration-200">
                            <td className="px-5 py-4">
                              <div className="flex items-center gap-3">
                                <div className="relative">
                                  <div className={clsx(
                                    "w-2.5 h-2.5 rounded-full",
                                    domain.status === 'sold' ? "bg-accent" : "bg-foreground-subtle"
                                  )} />
                                </div>
                                <div>
                                  <span className="font-mono text-body-sm text-foreground">{domain.domain}</span>
                                  {domain.status === 'sold' && <span className="ml-2 text-ui-xs px-1.5 py-0.5 bg-accent/10 text-accent rounded">Sold</span>}
                                  {domain.registrar && <p className="text-body-xs text-foreground-subtle">{domain.registrar}</p>}
                                </div>
                              </div>
                            </td>
                            <td className="px-5 py-4 hidden sm:table-cell">
                              <span className="text-body-sm text-foreground">{domain.purchase_price ? formatCurrency(domain.purchase_price) : '—'}</span>
                              {domain.purchase_date && <p className="text-body-xs text-foreground-subtle">{new Date(domain.purchase_date).toLocaleDateString()}</p>}
                            </td>
                            <td className="px-5 py-4 hidden md:table-cell">
                              <span className="text-body-sm text-foreground">{domain.estimated_value ? formatCurrency(domain.estimated_value) : '—'}</span>
                            </td>
                            <td className="px-5 py-4 hidden lg:table-cell">
                              {renewal ? (
                                <span className={clsx("text-body-sm flex items-center gap-1.5", renewal.urgent ? "text-warning font-medium" : "text-foreground-subtle")}>
                                  <Calendar className="w-3.5 h-3.5" />{renewal.text}
                                </span>
                              ) : <span className="text-foreground-subtle/50">—</span>}
                            </td>
                            <td className="px-5 py-4 text-right">
                              {roi !== null ? (
                                <span className={clsx("text-body-sm font-medium", roi >= 0 ? "text-accent" : "text-danger")}>
                                  {roi >= 0 ? '+' : ''}{roi.toFixed(1)}%
                                </span>
                              ) : <span className="text-foreground-subtle/50">—</span>}
                            </td>
                            <td className="px-5 py-4">
                              <div className="flex items-center justify-end gap-0.5 opacity-50 group-hover:opacity-100 transition-opacity">
                                {domain.status !== 'sold' && (
                                  <button onClick={() => handleOpenSellModal(domain)} className="p-2 text-foreground-subtle hover:text-accent hover:bg-accent/10 rounded-lg transition-all" title="Mark as Sold">
                                    <DollarSign className="w-4 h-4" />
                                  </button>
                                )}
                                <button onClick={() => handleOpenEditPortfolio(domain)} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/10 rounded-lg transition-all" title="Edit">
                                  <Edit2 className="w-4 h-4" />
                                </button>
                                <button onClick={() => handleRefreshPortfolioValue(domain.id)} disabled={refreshingPortfolioId === domain.id} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/10 rounded-lg transition-all" title="Refresh Value">
                                  <RefreshCw className={clsx("w-4 h-4", refreshingPortfolioId === domain.id && "animate-spin")} />
                                </button>
                                <button onClick={() => handleDeletePortfolioDomain(domain.id)} className="p-2 text-foreground-subtle hover:text-danger hover:bg-danger/10 rounded-lg transition-all" title="Remove">
                                  <Trash2 className="w-4 h-4" />
                                </button>
                              </div>
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}
        </div>
      </main>

      {/* Modals */}
      {showAddPortfolioModal && (
        <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-background-secondary border border-border rounded-2xl max-w-lg w-full max-h-[90vh] overflow-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-body-lg font-medium text-foreground">Add to Portfolio</h3>
                <button onClick={() => setShowAddPortfolioModal(false)} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/5 rounded-lg"><X className="w-5 h-5" /></button>
              </div>
              <form onSubmit={handleAddPortfolioDomain} className="space-y-4">
                <div>
                  <label className="block text-ui-sm text-foreground-muted mb-2">Domain *</label>
                  <input type="text" value={portfolioForm.domain} onChange={(e) => setPortfolioForm({ ...portfolioForm, domain: e.target.value })} placeholder="example.com" required className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Purchase Price</label>
                    <input type="number" step="0.01" min="0" value={portfolioForm.purchase_price} onChange={(e) => setPortfolioForm({ ...portfolioForm, purchase_price: e.target.value })} placeholder="0.00" className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Purchase Date</label>
                    <input type="date" value={portfolioForm.purchase_date} onChange={(e) => setPortfolioForm({ ...portfolioForm, purchase_date: e.target.value })} className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                </div>
                <div>
                  <label className="block text-ui-sm text-foreground-muted mb-2">Registrar</label>
                  <input type="text" value={portfolioForm.registrar} onChange={(e) => setPortfolioForm({ ...portfolioForm, registrar: e.target.value })} placeholder="e.g., Porkbun" className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Renewal Date</label>
                    <input type="date" value={portfolioForm.renewal_date} onChange={(e) => setPortfolioForm({ ...portfolioForm, renewal_date: e.target.value })} className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Renewal Cost</label>
                    <input type="number" step="0.01" min="0" value={portfolioForm.renewal_cost} onChange={(e) => setPortfolioForm({ ...portfolioForm, renewal_cost: e.target.value })} placeholder="0.00" className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                </div>
                <div>
                  <label className="block text-ui-sm text-foreground-muted mb-2">Notes</label>
                  <textarea value={portfolioForm.notes} onChange={(e) => setPortfolioForm({ ...portfolioForm, notes: e.target.value })} placeholder="Add notes..." rows={3} className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all resize-none" />
                </div>
                <div className="flex gap-3 pt-2">
                  <button type="button" onClick={() => setShowAddPortfolioModal(false)} className="flex-1 py-3 bg-foreground/5 text-foreground text-ui-sm font-medium rounded-xl hover:bg-foreground/10 transition-all">Cancel</button>
                  <button type="submit" disabled={addingPortfolio || !portfolioForm.domain.trim()} className="flex-1 py-3 bg-foreground text-background text-ui-sm font-medium rounded-xl hover:bg-foreground/90 disabled:opacity-40 transition-all flex items-center justify-center gap-2">
                    {addingPortfolio ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                    Add
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {showValuationModal && (
        <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-background-secondary border border-border rounded-2xl max-w-md w-full">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-body-lg font-medium text-foreground">Domain Valuation</h3>
                <button onClick={() => { setShowValuationModal(false); setValuationResult(null) }} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/5 rounded-lg"><X className="w-5 h-5" /></button>
              </div>
              {valuatingDomain ? (
                <div className="py-12 flex flex-col items-center gap-4">
                  <Loader2 className="w-8 h-8 animate-spin text-accent" />
                  <p className="text-body-sm text-foreground-muted">Analyzing {valuatingDomain}...</p>
                </div>
              ) : valuationResult ? (
                <div className="space-y-6">
                  <div className="text-center p-6 bg-accent/5 border border-accent/20 rounded-xl">
                    <p className="font-mono text-body-lg text-foreground mb-2">{valuationResult.domain}</p>
                    <p className="text-4xl font-display text-accent">{formatCurrency(valuationResult.estimated_value)}</p>
                    <p className="text-ui-sm text-foreground-muted mt-2 capitalize">{valuationResult.confidence} confidence</p>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    {Object.entries(valuationResult.scores).map(([key, value]) => key !== 'overall' && (
                      <div key={key} className="p-3 bg-foreground/5 rounded-lg">
                        <p className="text-ui-xs text-foreground-muted capitalize mb-1">{key}</p>
                        <div className="flex items-center gap-2">
                          <div className="flex-1 h-1.5 bg-background rounded-full overflow-hidden">
                            <div className="h-full bg-accent rounded-full" style={{ width: `${value}%` }} />
                          </div>
                          <span className="text-ui-sm text-foreground font-medium">{value}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {valuationResult.factors.has_numbers && <span className="text-ui-xs px-2 py-1 bg-warning/10 text-warning rounded-full">Has numbers</span>}
                    {valuationResult.factors.has_hyphens && <span className="text-ui-xs px-2 py-1 bg-warning/10 text-warning rounded-full">Has hyphens</span>}
                    {valuationResult.factors.is_dictionary_word && <span className="text-ui-xs px-2 py-1 bg-accent/10 text-accent rounded-full">Dictionary word</span>}
                    <span className="text-ui-xs px-2 py-1 bg-foreground/5 text-foreground-muted rounded-full">{valuationResult.factors.length} chars</span>
                    <span className="text-ui-xs px-2 py-1 bg-foreground/5 text-foreground-muted rounded-full">.{valuationResult.factors.tld}</span>
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        </div>
      )}

      {selectedDomainId && domainHistory && (
        <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-background-secondary border border-border rounded-2xl max-w-md w-full max-h-[80vh] overflow-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h3 className="text-body-lg font-medium text-foreground">Check History</h3>
                  <p className="text-body-sm text-foreground-muted font-mono">{domains.find(d => d.id === selectedDomainId)?.name}</p>
                </div>
                <button onClick={() => { setSelectedDomainId(null); setDomainHistory(null) }} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/5 rounded-lg"><X className="w-5 h-5" /></button>
              </div>
              {loadingHistory ? (
                <div className="py-8 flex justify-center"><Loader2 className="w-5 h-5 animate-spin text-accent" /></div>
              ) : domainHistory.length === 0 ? (
                <p className="py-8 text-center text-body-sm text-foreground-muted">No history yet</p>
              ) : (
                <div className="space-y-2">
                  {domainHistory.map((check) => (
                    <div key={check.id} className="flex items-center justify-between p-3 bg-foreground/5 rounded-lg">
                      <div className="flex items-center gap-3">
                        <div className={clsx("w-2 h-2 rounded-full", check.is_available ? "bg-accent" : "bg-foreground-subtle")} />
                        <span className={clsx("text-body-sm", check.is_available ? "text-accent" : "text-foreground-muted")}>{check.is_available ? 'Available' : 'Registered'}</span>
                      </div>
                      <span className="text-body-xs text-foreground-subtle">{formatDate(check.checked_at)}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {showEditPortfolioModal && editingPortfolioDomain && (
        <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-background-secondary border border-border rounded-2xl max-w-lg w-full max-h-[90vh] overflow-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h3 className="text-body-lg font-medium text-foreground">Edit Domain</h3>
                  <p className="text-body-sm text-foreground-muted font-mono">{editingPortfolioDomain.domain}</p>
                </div>
                <button onClick={() => { setShowEditPortfolioModal(false); setEditingPortfolioDomain(null) }} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/5 rounded-lg"><X className="w-5 h-5" /></button>
              </div>
              <form onSubmit={handleSaveEditPortfolio} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Purchase Price</label>
                    <input type="number" step="0.01" min="0" value={editPortfolioForm.purchase_price} onChange={(e) => setEditPortfolioForm({ ...editPortfolioForm, purchase_price: e.target.value })} placeholder="0.00" className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Purchase Date</label>
                    <input type="date" value={editPortfolioForm.purchase_date} onChange={(e) => setEditPortfolioForm({ ...editPortfolioForm, purchase_date: e.target.value })} className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                </div>
                <div>
                  <label className="block text-ui-sm text-foreground-muted mb-2">Registrar</label>
                  <input type="text" value={editPortfolioForm.registrar} onChange={(e) => setEditPortfolioForm({ ...editPortfolioForm, registrar: e.target.value })} placeholder="e.g., Namecheap" className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Renewal Date</label>
                    <input type="date" value={editPortfolioForm.renewal_date} onChange={(e) => setEditPortfolioForm({ ...editPortfolioForm, renewal_date: e.target.value })} className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Renewal Cost</label>
                    <input type="number" step="0.01" min="0" value={editPortfolioForm.renewal_cost} onChange={(e) => setEditPortfolioForm({ ...editPortfolioForm, renewal_cost: e.target.value })} placeholder="0.00" className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                  </div>
                </div>
                <div>
                  <label className="block text-ui-sm text-foreground-muted mb-2">Notes</label>
                  <textarea value={editPortfolioForm.notes} onChange={(e) => setEditPortfolioForm({ ...editPortfolioForm, notes: e.target.value })} placeholder="Add notes..." rows={3} className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all resize-none" />
                </div>
                <div className="flex gap-3 pt-2">
                  <button type="button" onClick={() => { setShowEditPortfolioModal(false); setEditingPortfolioDomain(null) }} className="flex-1 py-3 bg-foreground/5 text-foreground text-ui-sm font-medium rounded-xl hover:bg-foreground/10 transition-all">Cancel</button>
                  <button type="submit" disabled={savingEdit} className="flex-1 py-3 bg-foreground text-background text-ui-sm font-medium rounded-xl hover:bg-foreground/90 disabled:opacity-40 transition-all flex items-center justify-center gap-2">
                    {savingEdit ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
                    Save
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {showSellModal && sellingDomain && (
        <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-background-secondary border border-border rounded-2xl max-w-md w-full">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h3 className="text-body-lg font-medium text-foreground">Mark as Sold</h3>
                  <p className="text-body-sm text-foreground-muted font-mono">{sellingDomain.domain}</p>
                </div>
                <button onClick={() => { setShowSellModal(false); setSellingDomain(null) }} className="p-2 text-foreground-subtle hover:text-foreground hover:bg-foreground/5 rounded-lg"><X className="w-5 h-5" /></button>
              </div>
              {sellingDomain.estimated_value && (
                <div className="mb-6 p-4 bg-foreground/5 rounded-xl">
                  <div className="flex items-center justify-between">
                    <span className="text-body-sm text-foreground-muted">Estimated Value</span>
                    <span className="text-body font-medium text-foreground">{formatCurrency(sellingDomain.estimated_value)}</span>
                  </div>
                  {sellingDomain.purchase_price && (
                    <div className="flex items-center justify-between mt-2">
                      <span className="text-body-sm text-foreground-muted">Purchase Price</span>
                      <span className="text-body text-foreground-muted">{formatCurrency(sellingDomain.purchase_price)}</span>
                    </div>
                  )}
                </div>
              )}
              <form onSubmit={handleSellDomain} className="space-y-4">
                <div>
                  <label className="block text-ui-sm text-foreground-muted mb-2">Sale Price *</label>
                  <input type="number" step="0.01" min="0" value={sellForm.sale_price} onChange={(e) => setSellForm({ ...sellForm, sale_price: e.target.value })} placeholder="Enter sale price..." required className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-all" />
                </div>
                <div>
                  <label className="block text-ui-sm text-foreground-muted mb-2">Sale Date</label>
                  <input type="date" value={sellForm.sale_date} onChange={(e) => setSellForm({ ...sellForm, sale_date: e.target.value })} className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground focus:outline-none focus:border-accent/50 transition-all" />
                </div>
                {sellForm.sale_price && sellingDomain.purchase_price && (
                  <div className={clsx("p-4 rounded-xl", parseFloat(sellForm.sale_price) - sellingDomain.purchase_price >= 0 ? "bg-accent/10" : "bg-danger/10")}>
                    <div className="flex items-center justify-between">
                      <span className="text-body-sm text-foreground-muted">Profit</span>
                      <span className={clsx("text-body-lg font-medium", parseFloat(sellForm.sale_price) - sellingDomain.purchase_price >= 0 ? "text-accent" : "text-danger")}>
                        {parseFloat(sellForm.sale_price) - sellingDomain.purchase_price >= 0 ? '+' : ''}{formatCurrency(parseFloat(sellForm.sale_price) - sellingDomain.purchase_price)}
                      </span>
                    </div>
                  </div>
                )}
                <div className="flex gap-3 pt-2">
                  <button type="button" onClick={() => { setShowSellModal(false); setSellingDomain(null) }} className="flex-1 py-3 bg-foreground/5 text-foreground text-ui-sm font-medium rounded-xl hover:bg-foreground/10 transition-all">Cancel</button>
                  <button type="submit" disabled={processingSale || !sellForm.sale_price} className="flex-1 py-3 bg-accent text-background text-ui-sm font-medium rounded-xl hover:bg-accent-hover disabled:opacity-40 transition-all flex items-center justify-center gap-2">
                    {processingSale ? <Loader2 className="w-4 h-4 animate-spin" /> : <DollarSign className="w-4 h-4" />}
                    Confirm
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      <Footer />

      {/* Toast Notification */}
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={hideToast}
        />
      )}
    </div>
  )
}

export default function DashboardPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-background">
        <Loader2 className="w-6 h-6 animate-spin text-accent" />
      </div>
    }>
      <DashboardContent />
    </Suspense>
  )
}
