'use client'

import { useState, useEffect, useCallback } from 'react'
import { useSearchParams } from 'next/navigation'
import { 
  TrendingUp, DollarSign, Zap, Plus, CheckCircle2, Clock, AlertCircle,
  MousePointer, Target, Wallet, RefreshCw, ChevronRight, Copy, Check,
  XCircle, Sparkles, Loader2, Eye, Gavel, Menu, Settings, Shield, LogOut,
  Crown, Coins, Tag, X, Briefcase, Trash2
} from 'lucide-react'
import { api, YieldDomain, YieldTransaction } from '@/lib/api'
import { useStore } from '@/lib/store'
import { Sidebar } from '@/components/Sidebar'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

// ============================================================================
// STATUS BADGE
// ============================================================================

function StatusBadge({ status }: { status: string }) {
  const config: Record<string, { color: string; icon: any }> = {
    active: { color: 'bg-accent/10 text-accent border-accent/20', icon: CheckCircle2 },
    pending: { color: 'bg-amber-400/10 text-amber-400 border-amber-400/20', icon: Clock },
    verifying: { color: 'bg-blue-400/10 text-blue-400 border-blue-400/20', icon: RefreshCw },
    paused: { color: 'bg-white/5 text-white/40 border-white/10', icon: AlertCircle },
    error: { color: 'bg-red-400/10 text-red-400 border-red-400/20', icon: XCircle },
  }
  const { color, icon: Icon } = config[status] || config.pending
  return (
    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 text-[9px] font-mono border ${color}`}>
      <Icon className="w-3 h-3" />{status}
    </span>
  )
}

// ============================================================================
// ACTIVATE MODAL - Simple 3-step wizard
// ============================================================================

const YIELD_SERVER_IP = '46.235.147.194'

function ActivateModal({
  isOpen,
  onClose,
  onSuccess,
  prefillDomain,
}: {
  isOpen: boolean
  onClose: () => void
  onSuccess: () => void
  prefillDomain?: string | null
}) {
  const subscription = useStore((s) => s.subscription)
  const tier = (subscription?.tier || 'scout').toLowerCase()
  const isTycoon = tier === 'tycoon'
  const canPreview = tier === 'trader' || tier === 'tycoon'

  const [selectedDomain, setSelectedDomain] = useState('')
  const [verifiedDomains, setVerifiedDomains] = useState<{ id: number; domain: string }[]>([])
  const [loadingDomains, setLoadingDomains] = useState(true)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [step, setStep] = useState<1 | 2 | 3>(1)
  const [activatedDomainId, setActivatedDomainId] = useState<number | null>(null)
  const [landing, setLanding] = useState<null | {
    headline: string
    seo_intro: string
    cta_label: string
  }>(null)
  const [dnsChecking, setDnsChecking] = useState(false)
  const [dnsVerified, setDnsVerified] = useState(false)
  const [copied, setCopied] = useState(false)

  const [previewLoading, setPreviewLoading] = useState(false)
  const [previewError, setPreviewError] = useState<string | null>(null)
  const [preview, setPreview] = useState<null | {
    headline: string
    seo_intro: string
    cta_label: string
  }>(null)
  
  useEffect(() => {
    if (!isOpen) return
    if (prefillDomain) {
      setSelectedDomain(prefillDomain)
    }
    const fetchVerifiedDomains = async () => {
      setLoadingDomains(true)
      try {
        const domains = await api.getVerifiedPortfolioDomains()
        setVerifiedDomains(domains.map(d => ({ id: d.id, domain: d.domain })))
      } catch (err) {
        console.error('Failed to load verified domains:', err)
      } finally {
        setLoadingDomains(false)
      }
    }
    fetchVerifiedDomains()
  }, [isOpen, prefillDomain])

  useEffect(() => {
    if (!isOpen) return
    setStep(1)
    setActivatedDomainId(null)
    setLanding(null)
    setDnsChecking(false)
    setDnsVerified(false)
    setError(null)
    setSelectedDomain(prefillDomain || '')
    setPreview(null)
    setPreviewError(null)
    setPreviewLoading(false)
    setCopied(false)
  }, [isOpen, prefillDomain])

  const copyIP = async () => {
    try {
      await navigator.clipboard.writeText(YIELD_SERVER_IP)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch {
      // ignore
    }
  }
  
  const handleActivate = async () => {
    if (!selectedDomain) return
    setLoading(true)
    setError(null)
    try {
      const res = await api.activateYieldDomain(selectedDomain, true)
      setActivatedDomainId(res.domain_id)
      if (res.landing) {
        setLanding({
          headline: res.landing.headline,
          seo_intro: res.landing.seo_intro,
          cta_label: res.landing.cta_label,
        })
      }
      setStep(2)
    } catch (err: any) {
      setError(err.message || 'Failed to activate')
    } finally {
      setLoading(false)
    }
  }

  const handlePreview = async () => {
    if (!selectedDomain || !canPreview) return
    setPreviewLoading(true)
    setPreviewError(null)
    setPreview(null)
    try {
      const res = await api.getYieldLandingPreview(selectedDomain, false)
      setPreview({
        headline: res.result.headline,
        seo_intro: res.result.seo_intro,
        cta_label: res.result.cta_label,
      })
    } catch (err: any) {
      setPreviewError(err.message || 'Preview failed')
    } finally {
      setPreviewLoading(false)
    }
  }

  const checkDNS = async () => {
    if (!activatedDomainId) return
    setDnsChecking(true)
    setError(null)
    try {
      const res = await api.verifyYieldDomainDNS(activatedDomainId)
      if (res.verified) {
        setDnsVerified(true)
        setStep(3)
        onSuccess()
      } else {
        setError('DNS not yet propagated. This can take up to 15 minutes. Try again shortly.')
      }
    } catch (err: any) {
      setError(err.message || 'DNS check failed')
    } finally {
      setDnsChecking(false)
    }
  }
  
  if (!isOpen) return null
  
  return (
    <div className="fixed inset-0 z-[110] bg-black/80 flex items-center justify-center p-4" onClick={onClose}>
      <div className="w-full max-w-lg bg-[#0A0A0A] border border-white/[0.08]" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-white/[0.08]">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-accent/10 border border-accent/20 flex items-center justify-center">
              <Sparkles className="w-5 h-5 text-accent" />
            </div>
            <div>
              <h2 className="text-base font-bold text-white">
                {isTycoon ? 'Activate Yield' : 'Preview Yield Landing'}
              </h2>
              <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider">
                Step {step} of {isTycoon ? 3 : 1}
              </p>
            </div>
          </div>
          <button onClick={onClose} className="w-9 h-9 flex items-center justify-center border border-white/10 text-white/40 hover:text-white hover:border-white/20 transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>
        
        {/* Content */}
        <div className="p-5">
          {/* STEP 1: Select Domain */}
          {step === 1 && (
            <div className="space-y-5">
              {loadingDomains ? (
                <div className="flex items-center justify-center py-10">
                  <Loader2 className="w-6 h-6 text-accent animate-spin" />
                </div>
              ) : verifiedDomains.length === 0 ? (
                <div className="text-center py-8">
                  <AlertCircle className="w-12 h-12 text-amber-400/50 mx-auto mb-4" />
                  <h3 className="text-lg font-bold text-white mb-2">No Verified Domains</h3>
                  <p className="text-sm text-white/50 mb-6 max-w-xs mx-auto">
                    First, add domains to your portfolio and verify DNS ownership.
                  </p>
                  <a href="/terminal/portfolio" className="inline-flex items-center gap-2 px-5 py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider">
                    Go to Portfolio
                    <ChevronRight className="w-4 h-4" />
                  </a>
                </div>
              ) : (
                <>
                  <div>
                    <label className="block text-xs font-medium text-white mb-2">
                      Which domain do you want to monetize?
                    </label>
                    <select 
                      value={selectedDomain} 
                      onChange={(e) => { setSelectedDomain(e.target.value); setPreview(null); setPreviewError(null) }}
                      className="w-full px-4 py-3 bg-white/5 border border-white/10 text-white text-sm font-mono outline-none focus:border-accent/50 transition-colors"
                    >
                      <option value="">Select a domain...</option>
                      {verifiedDomains.map(d => (
                        <option key={d.id} value={d.domain}>{d.domain}</option>
                      ))}
                    </select>
                    <p className="text-[10px] text-white/30 mt-2">
                      Only DNS-verified domains from your portfolio are shown.
                    </p>
                  </div>

                  {/* Info Box */}
                  <div className={clsx(
                    "p-4 border",
                    isTycoon ? "bg-accent/5 border-accent/20" : "bg-white/[0.02] border-white/[0.08]"
                  )}>
                    <div className="flex gap-3">
                      <div className="shrink-0 w-8 h-8 bg-white/5 flex items-center justify-center">
                        <Zap className={clsx("w-4 h-4", isTycoon ? "text-accent" : "text-white/40")} />
                      </div>
                      <div>
                        <h4 className="text-sm font-bold text-white mb-1">
                          {isTycoon ? 'How Yield Works' : 'Yield is Tycoon-Only'}
                        </h4>
                        <p className="text-xs text-white/50 leading-relaxed">
                          {isTycoon 
                            ? 'We generate an AI-powered landing page for your domain. When visitors click, you earn revenue through our affiliate network.'
                            : 'You can preview the AI-generated landing page, but activation requires a Tycoon subscription.'}
                        </p>
                      </div>
                    </div>
                  </div>

                  {error && (
                    <div className="p-3 bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs font-mono">
                      {error}
                    </div>
                  )}

                  {/* Preview for non-Tycoon */}
                  {!isTycoon && (
                    <>
                      <button
                        onClick={handlePreview}
                        disabled={previewLoading || !selectedDomain}
                        className="w-full py-3 bg-white/10 text-white text-sm font-bold uppercase flex items-center justify-center gap-2 disabled:opacity-50 hover:bg-white/15 transition-colors"
                      >
                        {previewLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
                        Preview Landing Page
                      </button>

                      {previewError && (
                        <div className="p-3 bg-rose-500/10 border border-rose-500/20 text-rose-300 text-xs">
                          {previewError}
                        </div>
                      )}

                      {preview && (
                        <div className="p-4 bg-[#050505] border border-white/[0.08] space-y-3">
                          <div className="text-[9px] font-mono text-accent uppercase tracking-wider">Generated Landing Page</div>
                          <h3 className="text-base font-bold text-white">{preview.headline}</h3>
                          <p className="text-sm text-white/50 leading-relaxed">{preview.seo_intro}</p>
                          <div className="pt-3 border-t border-white/10">
                            <span className="inline-flex items-center gap-2 px-4 py-2 bg-accent/20 text-accent text-xs font-bold">
                              {preview.cta_label}
                            </span>
                          </div>
                        </div>
                      )}

                      <Link
                        href="/pricing"
                        className="w-full py-3 bg-accent text-black text-sm font-bold uppercase flex items-center justify-center gap-2 hover:bg-white transition-colors"
                      >
                        <Crown className="w-4 h-4" />
                        Upgrade to Tycoon to Activate
                      </Link>
                    </>
                  )}

                  {/* Activate for Tycoon */}
                  {isTycoon && (
                    <button 
                      onClick={handleActivate} 
                      disabled={loading || !selectedDomain}
                      className="w-full py-3.5 bg-accent text-black text-sm font-bold uppercase flex items-center justify-center gap-2 disabled:opacity-50 hover:bg-white transition-colors"
                    >
                      {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
                      Generate Landing & Continue
                    </button>
                  )}
                </>
              )}
            </div>
          )}

          {/* STEP 2: DNS Setup Instructions */}
          {step === 2 && (
            <div className="space-y-5">
              {/* Success Message */}
              <div className="p-4 bg-accent/5 border border-accent/20">
                <div className="flex gap-3">
                  <CheckCircle2 className="w-5 h-5 text-accent shrink-0 mt-0.5" />
                  <div>
                    <h4 className="text-sm font-bold text-white mb-1">Landing Page Generated!</h4>
                    <p className="text-xs text-white/50">
                      Now point your domain to our server to start earning.
                    </p>
                  </div>
                </div>
              </div>

              {/* Landing Preview */}
              {landing && (
                <div className="p-4 bg-[#050505] border border-white/[0.08] space-y-2">
                  <div className="text-[9px] font-mono text-white/40 uppercase tracking-wider">Your Landing Page</div>
                  <h3 className="text-sm font-bold text-white">{landing.headline}</h3>
                  <p className="text-xs text-white/50">{landing.seo_intro}</p>
                </div>
              )}

              {/* DNS Instructions */}
              <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>
                  Set up DNS at your registrar
                </h3>
                
                <div className="p-4 bg-[#020202] border border-white/[0.08] space-y-4">
                  <p className="text-sm text-white/70">
                    Go to your domain registrar (where you bought <span className="text-white font-bold">{selectedDomain}</span>) and add this DNS record:
                  </p>
                  
                  <div className="grid grid-cols-3 gap-2 text-center">
                    <div className="p-3 bg-white/5 border border-white/10">
                      <div className="text-[9px] font-mono text-white/40 uppercase mb-1">Type</div>
                      <div className="text-lg font-bold text-white font-mono">A</div>
                    </div>
                    <div className="p-3 bg-white/5 border border-white/10">
                      <div className="text-[9px] font-mono text-white/40 uppercase mb-1">Name</div>
                      <div className="text-lg font-bold text-white font-mono">@</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</div>
                      <div className="text-sm font-bold text-accent font-mono">{YIELD_SERVER_IP}</div>
                    </div>
                  </div>

                  <button
                    onClick={copyIP}
                    className="w-full py-2.5 border border-white/10 text-white/70 text-xs font-mono flex items-center justify-center gap-2 hover:bg-white/5 transition-colors"
                  >
                    {copied ? <Check className="w-4 h-4 text-accent" /> : <Copy className="w-4 h-4" />}
                    {copied ? 'Copied!' : `Copy IP: ${YIELD_SERVER_IP}`}
                  </button>

                  <div className="text-[10px] text-white/30 leading-relaxed">
                    <strong className="text-white/50">Tip:</strong> The "@" symbol means the root domain. Some registrars use "empty" or the domain name itself instead.
                  </div>
                </div>
              </div>

              {/* Verify Button */}
              <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 connection
                </h3>
                
                <p className="text-xs text-white/50">
                  After saving your DNS settings, click verify. DNS changes can take 5-15 minutes to propagate.
                </p>

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

                <div className="flex gap-2">
                  <button
                    onClick={() => setStep(1)}
                    className="flex-1 py-3 border border-white/10 text-white/60 text-xs font-bold uppercase hover:bg-white/5 transition-colors"
                  >
                    Back
                  </button>
                  <button
                    onClick={checkDNS}
                    disabled={dnsChecking}
                    className="flex-[2] py-3 bg-accent text-black text-sm font-bold uppercase flex items-center justify-center gap-2 disabled:opacity-50 hover:bg-white transition-colors"
                  >
                    {dnsChecking ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                    Verify DNS
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* STEP 3: Success */}
          {step === 3 && (
            <div className="text-center py-6 space-y-5">
              <div className="w-16 h-16 bg-accent/10 border border-accent/20 flex items-center justify-center mx-auto">
                <CheckCircle2 className="w-8 h-8 text-accent" />
              </div>
              
              <div>
                <h3 className="text-xl font-bold text-white mb-2">Yield Activated!</h3>
                <p className="text-sm text-white/50">
                  <span className="text-white font-bold">{selectedDomain}</span> is now earning passive income.
                </p>
              </div>

              <div className="p-4 bg-[#050505] border border-white/[0.08] text-left space-y-2">
                <div className="text-[9px] font-mono text-white/40 uppercase tracking-wider">What happens now?</div>
                <ul className="text-xs text-white/60 space-y-1.5">
                  <li className="flex items-start gap-2">
                    <span className="text-accent">•</span>
                    Visitors to {selectedDomain} see your AI-generated landing page
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="text-accent">•</span>
                    When they click the CTA, you earn revenue
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="text-accent">•</span>
                    Track clicks and earnings in your Yield dashboard
                  </li>
                </ul>
              </div>

              <button
                onClick={onClose}
                className="w-full py-3.5 bg-accent text-black text-sm font-bold uppercase flex items-center justify-center gap-2 hover:bg-white transition-colors"
              >
                View Dashboard
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

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

export default function YieldPage() {
  const { subscription, user, logout, checkAuth } = useStore()
  const searchParams = useSearchParams()
  const [loading, setLoading] = useState(true)
  const [dashboard, setDashboard] = useState<any>(null)
  const [showActivateModal, setShowActivateModal] = useState(false)
  const [prefillDomain, setPrefillDomain] = useState<string | null>(null)
  const [refreshing, setRefreshing] = useState(false)
  const [menuOpen, setMenuOpen] = useState(false)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [verifyingId, setVerifyingId] = useState<number | null>(null)

  const tier = (subscription?.tier || 'scout').toLowerCase()
  const tierName = subscription?.tier_name || (tier.charAt(0).toUpperCase() + tier.slice(1))
  const isTycoon = tier === 'tycoon'
  
  useEffect(() => { checkAuth() }, [checkAuth])
  
  const fetchDashboard = useCallback(async () => {
    try {
      const data = await api.getYieldDashboard()
      setDashboard(data)
    } catch (err) { console.error(err) }
    finally { setLoading(false); setRefreshing(false) }
  }, [])
  
  const handleDeleteYield = useCallback(async (domainId: number, domainName: string) => {
    if (!confirm(`Remove ${domainName} from Yield? This will stop all revenue tracking.`)) return
    setDeletingId(domainId)
    try {
      await api.deleteYieldDomain(domainId)
      fetchDashboard()
    } catch (err) { 
      console.error('Failed to remove yield domain:', err) 
    } finally { 
      setDeletingId(null) 
    }
  }, [fetchDashboard])
  
  const handleVerifyDNS = useCallback(async (domainId: number, domainName: string) => {
    setVerifyingId(domainId)
    try {
      const res = await api.verifyYieldDomainDNS(domainId)
      if (res.verified) {
        alert(`✅ ${domainName} is now active! Your landing page is live.`)
        fetchDashboard()
      } else {
        alert(`⏳ DNS not yet propagated for ${domainName}. Please wait 5-15 minutes and try again.`)
      }
    } catch (err: any) { 
      alert(`❌ DNS verification failed: ${err.message || 'Unknown error'}`)
    } finally { 
      setVerifyingId(null) 
    }
  }, [fetchDashboard])
  
  useEffect(() => { fetchDashboard() }, [fetchDashboard])

  useEffect(() => {
    const activate = searchParams.get('activate')
    if (activate) {
      setPrefillDomain(activate)
      setShowActivateModal(true)
    }
  }, [searchParams])
  
  const stats = dashboard?.stats
  
  const mobileNavItems = [
    { href: '/terminal/hunt', label: 'Radar', icon: Target, active: false },
    { href: '/terminal/market', label: 'Market', icon: Gavel, active: false },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: false },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: false },
  ]
  
  const tierLabelForDrawer = subscription?.tier_name || subscription?.tier || 'Scout'
  const TierIcon = tierLabelForDrawer === 'Tycoon' ? Crown : tierLabelForDrawer === 'Trader' ? TrendingUp : Zap
  
  const drawerNavSections = [
    { title: 'Discover', items: [
      { href: '/terminal/hunt', label: 'Radar', icon: Target },
      { href: '/terminal/market', label: 'Market', icon: Gavel },
      { href: '/terminal/intel', label: 'Intel', icon: TrendingUp },
    ]},
    { title: 'Manage', items: [
      { href: '/terminal/watchlist', label: 'Watchlist', icon: Eye },
      { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase },
      { href: '/terminal/sniper', label: 'Sniper', icon: Target },
    ]},
    { title: 'Monetize', items: [
      { href: '/terminal/yield', label: 'Yield', icon: Coins, active: true },
      { href: '/terminal/listing', label: 'For Sale', icon: Tag },
    ]}
  ]

  return (
    <div className="min-h-screen bg-[#020202]">
      <div className="hidden lg:block"><Sidebar /></div>
      
      <main className="lg:pl-[240px]">
        {/* MOBILE HEADER */}
        <header className="lg:hidden sticky top-0 z-40 bg-[#020202]/95 backdrop-blur-md border-b border-white/[0.08]" style={{ paddingTop: 'env(safe-area-inset-top)' }}>
          <div className="px-4 py-3">
            <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">Yield</span>
              </div>
              <span className="text-[10px] font-mono text-white/40">{stats?.active_domains || 0} active</span>
            </div>
            <div className="grid grid-cols-3 gap-2">
              <div className="bg-accent/[0.05] border border-accent/20 p-2">
                <div className="text-lg font-bold text-accent tabular-nums font-mono">${stats?.monthly_revenue || 0}</div>
                <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Monthly</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{stats?.monthly_clicks || 0}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Clicks</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">${stats?.pending_payout || 0}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Pending</div>
              </div>
            </div>
          </div>
        </header>

        {/* DESKTOP HEADER */}
        <section className="hidden lg:block px-10 pt-10 pb-6">
          <div className="flex items-end justify-between gap-6">
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Yield</span>
              </div>
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em] text-white">Yield</h1>
              <p className="text-sm text-white/40 font-mono mt-2 max-w-lg">
                Monetize your parked domains. Route visitor intent to earn passive income.
              </p>
              {!isTycoon && (
                <div className="inline-flex items-center gap-2 px-3 py-2 border border-white/10 bg-white/[0.02] text-xs text-white/50 font-mono">
                  <Sparkles className="w-4 h-4 text-accent" />
                  Yield activation is <span className="text-white/70 font-bold">Tycoon-only</span>. You can preview the landing page on Trader.
                </div>
              )}
            </div>
            <div className="flex items-center gap-6">
              {stats && (
                <div className="flex gap-8">
                  <div className="text-right">
                    <div className="text-2xl font-bold text-accent font-mono">${stats.monthly_revenue}</div>
                    <div className="text-[9px] font-mono text-white/30 uppercase">Monthly</div>
                  </div>
                  <div className="text-right">
                    <div className="text-2xl font-bold text-white font-mono">{stats.active_domains}</div>
                    <div className="text-[9px] font-mono text-white/30 uppercase">Active</div>
                  </div>
                </div>
              )}
              <div className="flex gap-2">
                <button onClick={() => { setRefreshing(true); fetchDashboard() }} disabled={refreshing}
                  className="w-9 h-9 flex items-center justify-center border border-white/10 text-white/40 hover:text-white">
                  <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
                </button>
                <button onClick={() => setShowActivateModal(true)}
                  className="flex items-center gap-2 px-4 py-2.5 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white">
                  <Plus className="w-4 h-4" />{isTycoon ? 'Activate Domain' : 'Preview Landing'}
                </button>
              </div>
            </div>
          </div>
        </section>

        {/* ADD BUTTON MOBILE */}
        <section className="lg:hidden px-4 py-3 border-b border-white/[0.08]">
          <button onClick={() => setShowActivateModal(true)}
            className="w-full flex items-center justify-center gap-2 py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider">
            <Plus className="w-4 h-4" />{isTycoon ? 'Activate Domain' : 'Preview Landing'}
          </button>
        </section>

        {/* CONTENT */}
        <section className="px-4 lg:px-10 py-4 pb-28 lg:pb-10">
          {loading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="w-6 h-6 text-accent animate-spin" />
            </div>
          ) : !dashboard?.domains?.length ? (
            <div className="text-center py-24 border border-dashed border-white/[0.08] bg-white/[0.01]">
              <TrendingUp 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 yield domains yet</p>
              <p className="text-white/20 text-xs font-mono mt-3 uppercase tracking-wider max-w-sm mx-auto leading-relaxed">
                Activate domains to earn passive income from parked traffic
              </p>
            </div>
          ) : (
            <div className="border border-white/[0.08] bg-[#020202] overflow-hidden">
              {/* Header */}
              <div className="hidden lg:grid grid-cols-[1fr_80px_140px_120px_70px_60px_80px_90px] 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]">
                <div>Domain</div>
                <div className="text-center">Status</div>
                <div>Intent</div>
                <div>Landing</div>
                <div className="text-right">Clicks</div>
                <div className="text-right">Conv.</div>
                <div className="text-right">Revenue</div>
                <div></div>
              </div>
              
              {/* Table Body */}
              <div className="divide-y divide-white/[0.04]">
              
              {dashboard.domains.map((domain: YieldDomain) => (
                <div key={domain.id} className="group transition-all">
                  {/* Mobile */}
                  <div className="lg:hidden p-3">
                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center gap-3">
                        <span className="text-sm font-bold text-white font-mono">{domain.domain}</span>
                      </div>
                      <StatusBadge status={domain.status} />
                    </div>
                    <div className="mb-2">
                      <details className="group">
                        <summary className="cursor-pointer text-[10px] font-mono text-white/50 hover:text-white/70 flex items-center justify-between">
                          <span>
                            Landing:{' '}
                            {domain.landing_headline ? (
                              <span className="text-accent font-bold">Ready</span>
                            ) : (
                              <span className="text-amber-400 font-bold">Missing</span>
                            )}
                          </span>
                          <span className="text-white/30 group-open:text-white/50">expand</span>
                        </summary>
                        <div className="mt-2 p-2 bg-[#050505] border border-white/[0.08]">
                          {domain.landing_headline ? (
                            <div className="space-y-2">
                              <div className="text-xs font-bold text-white">{domain.landing_headline}</div>
                              {domain.landing_intro && <div className="text-[10px] text-white/50">{domain.landing_intro}</div>}
                              <div className="text-[10px] font-mono text-white/40">
                                CTA: <span className="text-white/70">{domain.landing_cta_label || '—'}</span>
                              </div>
                              <div className="text-[10px] font-mono text-white/30">
                                {domain.landing_generated_at ? new Date(domain.landing_generated_at).toLocaleString() : '—'}
                                {domain.landing_model ? <span className="text-white/20"> • {domain.landing_model}</span> : null}
                              </div>
                            </div>
                          ) : (
                            <div className="text-[10px] text-white/40">
                              No landing config stored yet. (Older activation) Remove + re-activate on Tycoon to regenerate.
                            </div>
                          )}
                        </div>
                      </details>
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex gap-4 text-[10px] font-mono text-white/40">
                      <span>{domain.total_clicks} clicks</span>
                      <span className="text-accent font-bold">${domain.total_revenue}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        {/* Verify DNS Button - only for pending domains (mobile) */}
                        {domain.status === 'pending' && (
                          <button
                            onClick={() => handleVerifyDNS(domain.id, domain.domain)}
                            disabled={verifyingId === domain.id}
                            className="px-2 py-1 flex items-center gap-1 text-amber-400 text-[10px] font-mono border border-amber-400/20 hover:border-accent/30 hover:bg-accent/10 transition-all"
                          >
                            {verifyingId === domain.id ? (
                              <Loader2 className="w-3 h-3 animate-spin" />
                            ) : (
                              <>
                                <Shield className="w-3 h-3" />
                                <span>Verify</span>
                              </>
                            )}
                          </button>
                        )}
                        <button
                          onClick={() => handleDeleteYield(domain.id, domain.domain)}
                          disabled={deletingId === domain.id}
                          className="p-1.5 text-white/30 hover:text-rose-400 disabled:opacity-50 transition-colors"
                        >
                          {deletingId === domain.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>
                  </div>
                  
                  {/* Desktop */}
                  <div className="hidden lg:grid grid-cols-[1fr_80px_140px_120px_70px_60px_80px_90px] gap-4 items-center px-5 py-3 group-hover:bg-white/[0.02]">
                    <div className="flex items-center gap-3 min-w-0">
                      <span className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors">{domain.domain}</span>
                    </div>
                    <div className="flex justify-center"><StatusBadge status={domain.status} /></div>
                    <span className="text-sm text-white/50 capitalize font-mono truncate">{domain.detected_intent?.replace('_', ' ') || '—'}</span>
                    <div>
                      <details className="group/details">
                        <summary
                          className="cursor-pointer text-xs font-mono text-white/50 hover:text-white/70 flex items-center gap-2"
                          title="View landing page details"
                        >
                          {domain.landing_headline ? (
                            <span className="text-accent">Ready</span>
                          ) : (
                            <span className="text-amber-400">Missing</span>
                          )}
                        </summary>
                        <div className="absolute mt-2 p-3 bg-[#050505] border border-white/[0.08] space-y-2 z-10 w-80">
                          {domain.landing_headline ? (
                            <>
                              <div className="text-xs font-bold text-white">{domain.landing_headline}</div>
                              {domain.landing_intro && <div className="text-[10px] text-white/50">{domain.landing_intro}</div>}
                              <div className="text-[10px] font-mono text-white/40">
                                CTA: <span className="text-white/70">{domain.landing_cta_label || '—'}</span>
                              </div>
                            </>
                          ) : (
                            <div className="text-[10px] text-white/40">
                              No landing config. Re-activate on Tycoon to generate.
                            </div>
                          )}
                        </div>
                      </details>
                    </div>
                    <div className="text-right text-sm font-mono text-white/50">{domain.total_clicks}</div>
                    <div className="text-right text-sm font-mono text-white/50">{domain.total_conversions}</div>
                    <div className="text-right text-sm font-bold font-mono text-accent">${domain.total_revenue}</div>
                    <div className="flex justify-end gap-1 opacity-40 group-hover:opacity-100 transition-all">
                      {/* Verify DNS Button - only for pending domains */}
                      {domain.status === 'pending' && (
                        <button
                          onClick={() => handleVerifyDNS(domain.id, domain.domain)}
                          disabled={verifyingId === domain.id}
                          className="h-8 px-2 flex items-center justify-center gap-1 text-amber-400 hover:text-accent text-[10px] font-mono border border-amber-400/20 hover:border-accent/30 hover:bg-accent/10 transition-all"
                          title="Verify DNS to activate"
                        >
                          {verifyingId === domain.id ? (
                            <Loader2 className="w-3 h-3 animate-spin" />
                          ) : (
                            <>
                              <Shield className="w-3 h-3" />
                              <span>Verify</span>
                            </>
                          )}
                        </button>
                      )}
                      <button
                        onClick={() => handleDeleteYield(domain.id, domain.domain)}
                        disabled={deletingId === domain.id}
                        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"
                        title="Remove from Yield"
                      >
                        {deletingId === domain.id ? (
                          <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        ) : (
                          <Trash2 className="w-3.5 h-3.5" />
                        )}
                      </button>
                    </div>
                  </div>
                </div>
              ))}
              </div>
            </div>
          )}
        </section>

        {/* MOBILE BOTTOM NAV */}
        <nav className="lg:hidden fixed bottom-0 left-0 right-0 z-50 bg-[#020202] border-t border-white/[0.08]" style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}>
          <div className="flex items-stretch h-14">
            {mobileNavItems.map((item) => (
              <Link key={item.href} href={item.href} className={clsx("flex-1 flex flex-col items-center justify-center gap-0.5 relative", item.active ? "text-accent" : "text-white/40")}>
                {item.active && <div className="absolute top-0 left-1/2 -translate-x-1/2 w-10 h-0.5 bg-accent" />}
                <item.icon className="w-5 h-5" />
                <span className="text-[9px] font-mono uppercase tracking-wider">{item.label}</span>
              </Link>
            ))}
            <button onClick={() => setMenuOpen(true)} className="flex-1 flex flex-col items-center justify-center gap-0.5 text-white/40">
              <Menu className="w-5 h-5" /><span className="text-[9px] font-mono uppercase tracking-wider">Menu</span>
            </button>
          </div>
        </nav>

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

              <ActivateModal
                isOpen={showActivateModal}
                prefillDomain={prefillDomain}
                onClose={() => { setShowActivateModal(false); setPrefillDomain(null) }}
                onSuccess={fetchDashboard}
              />
    </div>
  )
}
