'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useSearchParams } from 'next/navigation'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { TerminalLayout } from '@/components/TerminalLayout'
import {
  Plus,
  Shield,
  Eye,
  MessageSquare,
  ExternalLink,
  Loader2,
  Trash2,
  CheckCircle,
  AlertCircle,
  Copy,
  RefreshCw,
  DollarSign,
  X,
  Tag,
  Store,
  Sparkles,
  ArrowRight,
  TrendingUp,
  Globe,
  MoreHorizontal
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

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

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

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

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

interface Listing {
  id: number
  domain: string
  slug: string
  title: string | null
  description: string | null
  asking_price: number | null
  min_offer: number | null
  currency: string
  price_type: string
  pounce_score: number | null
  estimated_value: number | null
  verification_status: string
  is_verified: boolean
  status: string
  show_valuation: boolean
  allow_offers: boolean
  view_count: number
  inquiry_count: number
  public_url: string
  created_at: string
  published_at: string | null
}

interface VerificationInfo {
  verification_code: string
  dns_record_type: string
  dns_record_name: string
  dns_record_value: string
  instructions: string
  status: string
}

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

export default function MyListingsPage() {
  const { subscription } = useStore()
  const searchParams = useSearchParams()
  const prefillDomain = searchParams.get('domain')
  
  const [listings, setListings] = useState<Listing[]>([])
  const [loading, setLoading] = useState(true)
  
  // Modals
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showVerifyModal, setShowVerifyModal] = useState(false)
  const [selectedListing, setSelectedListing] = useState<Listing | null>(null)
  const [verificationInfo, setVerificationInfo] = useState<VerificationInfo | null>(null)
  const [verifying, setVerifying] = useState(false)
  const [creating, setCreating] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  
  // Create form state
  const [newListing, setNewListing] = useState({
    domain: '',
    title: '',
    description: '',
    asking_price: '',
    price_type: 'negotiable',
    allow_offers: true,
  })

  const loadListings = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api.request<Listing[]>('/listings/my')
      setListings(data)
    } catch (err: any) {
      console.error('Failed to load listings:', err)
    } finally {
      setLoading(false)
    }
  }, [])

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

  useEffect(() => {
    if (prefillDomain) {
      setNewListing(prev => ({ ...prev, domain: prefillDomain }))
      setShowCreateModal(true)
    }
  }, [prefillDomain])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    setCreating(true)
    setError(null)
    
    try {
      await api.request('/listings', {
        method: 'POST',
        body: JSON.stringify({
          domain: newListing.domain,
          title: newListing.title || null,
          description: newListing.description || null,
          asking_price: newListing.asking_price ? parseFloat(newListing.asking_price) : null,
          price_type: newListing.price_type,
          allow_offers: newListing.allow_offers,
        }),
      })
      setSuccess('Listing created! Now verify ownership to publish.')
      setShowCreateModal(false)
      setNewListing({ domain: '', title: '', description: '', asking_price: '', price_type: 'negotiable', allow_offers: true })
      loadListings()
    } catch (err: any) {
      setError(err.message)
    } finally {
      setCreating(false)
    }
  }

  const handleStartVerification = async (listing: Listing) => {
    setSelectedListing(listing)
    setVerifying(true)
    
    try {
      const info = await api.request<VerificationInfo>(`/listings/${listing.id}/verify-dns`, {
        method: 'POST',
      })
      setVerificationInfo(info)
      setShowVerifyModal(true)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setVerifying(false)
    }
  }

  const handleCheckVerification = async () => {
    if (!selectedListing) return
    setVerifying(true)
    
    try {
      const result = await api.request<{ verified: boolean; message: string }>(
        `/listings/${selectedListing.id}/verify-dns/check`
      )
      
      if (result.verified) {
        setSuccess('Domain verified! You can now publish your listing.')
        setShowVerifyModal(false)
        loadListings()
      } else {
        setError(result.message)
      }
    } catch (err: any) {
      setError(err.message)
    } finally {
      setVerifying(false)
    }
  }

  const handlePublish = async (listing: Listing) => {
    try {
      await api.request(`/listings/${listing.id}`, {
        method: 'PUT',
        body: JSON.stringify({ status: 'active' }),
      })
      setSuccess('Listing published!')
      loadListings()
    } catch (err: any) {
      setError(err.message)
    }
  }

  const handleDelete = async (listing: Listing) => {
    if (!confirm(`Delete listing for ${listing.domain}?`)) return
    
    try {
      await api.request(`/listings/${listing.id}`, { method: 'DELETE' })
      setSuccess('Listing deleted')
      loadListings()
    } catch (err: any) {
      setError(err.message)
    }
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    setSuccess('Copied to clipboard!')
    setTimeout(() => setSuccess(null), 2000)
  }

  const formatPrice = (price: number | null, currency: string) => {
    if (!price) return 'Make Offer'
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      minimumFractionDigits: 0,
    }).format(price)
  }

  // Tier limits
  const tier = subscription?.tier || 'scout'
  const limits = { scout: 0, trader: 5, tycoon: 50 }
  const maxListings = limits[tier as keyof typeof limits] || 0
  const canList = tier !== 'scout'

  const activeCount = listings.filter(l => l.status === 'active').length
  const totalViews = listings.reduce((sum, l) => sum + l.view_count, 0)
  const totalInquiries = listings.reduce((sum, l) => sum + l.inquiry_count, 0)

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

        <div className="relative z-10 max-w-[1600px] mx-auto p-4 md:p-8 space-y-8">
          
          {/* Header Section */}
          <div className="flex flex-col md:flex-row justify-between items-start md:items-end gap-6 border-b border-white/5 pb-8">
            <div className="space-y-2">
              <div className="flex items-center gap-3">
                <div className="h-8 w-1 bg-emerald-500 rounded-full shadow-[0_0_10px_rgba(16,185,129,0.5)]" />
                <h1 className="text-3xl font-bold tracking-tight text-white">Portfolio</h1>
              </div>
              <p className="text-zinc-400 max-w-lg">
                Manage your domain inventory, track performance, and process offers.
              </p>
            </div>
            
            <div className="flex gap-2">
              <Link
                href="/buy"
                className="px-4 py-2 rounded-lg bg-white/5 border border-white/10 hover:bg-white/10 text-sm font-medium text-zinc-300 transition-colors flex items-center gap-2"
              >
                <Store className="w-4 h-4" /> Marketplace
              </Link>
              <button
                onClick={() => setShowCreateModal(true)}
                disabled={listings.length >= maxListings}
                className="px-4 py-2 bg-emerald-500 text-white font-medium rounded-lg hover:bg-emerald-400 transition-all shadow-lg shadow-emerald-500/20 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <Plus className="w-4 h-4" /> New Listing
              </button>
            </div>
          </div>

          {/* Messages */}
          {error && (
            <div className="p-4 bg-rose-500/10 border border-rose-500/20 rounded-xl flex items-center gap-3 text-rose-400 animate-in fade-in slide-in-from-top-2">
              <AlertCircle className="w-5 h-5" />
              <p className="text-sm flex-1">{error}</p>
              <button onClick={() => setError(null)}><X className="w-4 h-4" /></button>
            </div>
          )}
          
          {success && (
            <div className="p-4 bg-emerald-500/10 border border-emerald-500/20 rounded-xl flex items-center gap-3 text-emerald-400 animate-in fade-in slide-in-from-top-2">
              <CheckCircle className="w-5 h-5" />
              <p className="text-sm flex-1">{success}</p>
              <button onClick={() => setSuccess(null)}><X className="w-4 h-4" /></button>
            </div>
          )}

          {/* Paywall */}
          {!canList && (
            <div className="p-8 bg-gradient-to-br from-emerald-900/20 to-black border border-emerald-500/20 rounded-2xl text-center relative overflow-hidden">
               <div className="absolute inset-0 bg-grid-white/[0.02] bg-[length:20px_20px]" />
               <div className="relative z-10">
                  <Shield className="w-12 h-12 text-emerald-400 mx-auto mb-4" />
                  <h2 className="text-2xl font-bold text-white mb-2">Unlock Portfolio Management</h2>
                  <p className="text-zinc-400 mb-6 max-w-md mx-auto">
                    List your domains, verify ownership automatically, and sell directly to buyers with 0% commission on the Pounce Marketplace.
                  </p>
                  <Link
                    href="/pricing"
                    className="inline-flex items-center gap-2 px-6 py-3 bg-emerald-500 text-white font-bold rounded-xl hover:bg-emerald-400 transition-all shadow-lg shadow-emerald-500/20"
                  >
                    Upgrade to Trader <ArrowRight className="w-4 h-4" />
                  </Link>
               </div>
            </div>
          )}

          {/* Stats Grid */}
          {canList && (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <StatCard 
                label="Inventory" 
                value={listings.length}
                subValue={`/ ${maxListings} slots`}
                icon={Tag}
                trend="neutral"
              />
              <StatCard 
                label="Active Listings" 
                value={activeCount}
                subValue="Live on market"
                icon={Store}
                trend="active"
              />
              <StatCard 
                label="Total Views" 
                value={totalViews}
                subValue="All time"
                icon={Eye}
                trend={totalViews > 0 ? 'up' : 'neutral'}
              />
              <StatCard 
                label="Inquiries" 
                value={totalInquiries}
                subValue="Pending"
                icon={MessageSquare}
                trend={totalInquiries > 0 ? 'up' : 'neutral'}
              />
            </div>
          )}

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

              {loading ? (
                <div className="flex items-center justify-center py-20">
                  <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
                </div>
              ) : listings.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-20 text-center">
                  <div className="w-16 h-16 rounded-full bg-white/5 flex items-center justify-center mb-4">
                    <Sparkles className="w-8 h-8 text-zinc-600" />
                  </div>
                  <h3 className="text-lg font-medium text-white mb-1">No listings yet</h3>
                  <p className="text-zinc-500 text-sm max-w-xs mx-auto mb-6">
                    Create your first listing to start selling.
                  </p>
                  <button
                    onClick={() => setShowCreateModal(true)}
                    className="text-emerald-400 text-sm hover:text-emerald-300 transition-colors flex items-center gap-2 font-medium"
                  >
                    Create Listing <ArrowRight className="w-4 h-4" />
                  </button>
                </div>
              ) : (
                <div className="divide-y divide-white/5">
                  {listings.map((listing) => (
                    <div key={listing.id} className="grid grid-cols-12 gap-4 px-6 py-4 items-center hover:bg-white/[0.04] transition-all group relative">
                      
                      {/* Mobile View */}
                      <div className="md:hidden col-span-12">
                         <div className="flex justify-between items-start mb-2">
                            <div>
                               <div className="font-mono font-bold text-white text-lg">{listing.domain}</div>
                               <div className="text-xs text-zinc-500 mt-0.5">{listing.title || 'No headline'}</div>
                            </div>
                            <div className="text-right">
                               <div className="font-mono text-emerald-400 font-bold">{formatPrice(listing.asking_price, listing.currency)}</div>
                            </div>
                         </div>
                         <div className="flex justify-between items-center mt-3 pt-3 border-t border-white/5">
                            <span className={clsx(
                              "text-[10px] font-bold uppercase px-2 py-0.5 rounded border",
                              listing.status === 'active' ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" :
                              listing.status === 'draft' ? "bg-zinc-800 text-zinc-400 border-zinc-700" :
                              "bg-blue-500/10 text-blue-400 border-blue-500/20"
                            )}>
                              {listing.status}
                            </span>
                            <div className="flex gap-2">
                               <button onClick={() => handleDelete(listing)} className="p-2 text-zinc-500 hover:text-rose-400"><Trash2 className="w-4 h-4" /></button>
                               {!listing.is_verified && <button onClick={() => handleStartVerification(listing)} className="p-2 text-amber-400 hover:bg-amber-500/10 rounded"><Shield className="w-4 h-4" /></button>}
                            </div>
                         </div>
                      </div>

                      {/* Desktop View */}
                      <div className="hidden md:block col-span-5">
                        <div className="flex items-center gap-3">
                           <div className={clsx(
                              "w-10 h-10 rounded-lg flex items-center justify-center text-lg font-bold",
                              listing.status === 'active' ? "bg-emerald-500/10 text-emerald-400" : "bg-zinc-800 text-zinc-500"
                           )}>
                              {listing.domain.charAt(0).toUpperCase()}
                           </div>
                           <div>
                              <div className="font-mono font-bold text-white tracking-tight">{listing.domain}</div>
                              <div className="text-xs text-zinc-500">{listing.title || 'No description provided'}</div>
                           </div>
                        </div>
                      </div>

                      <div className="hidden md:flex col-span-2 justify-center">
                         <span className={clsx(
                              "inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider border",
                              listing.status === 'active' ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" :
                              listing.status === 'draft' ? "bg-zinc-800/50 text-zinc-400 border-zinc-700" :
                              "bg-blue-500/10 text-blue-400 border-blue-500/20"
                           )}>
                              <span className={clsx("w-1.5 h-1.5 rounded-full", listing.status === 'active' ? "bg-emerald-400" : "bg-zinc-500")} />
                              {listing.status}
                           </span>
                      </div>

                      <div className="hidden md:block col-span-2 text-right">
                         <div className="font-mono font-medium text-white">{formatPrice(listing.asking_price, listing.currency)}</div>
                         {listing.pounce_score && <div className="text-[10px] text-zinc-500 mt-0.5">Score: {listing.pounce_score}</div>}
                      </div>

                      <div className="hidden md:block col-span-1 text-center">
                         <div className="text-sm text-zinc-400">{listing.view_count}</div>
                      </div>

                      <div className="hidden md:flex col-span-2 justify-end gap-2">
                         {!listing.is_verified ? (
                            <Tooltip content="Verify ownership to publish">
                               <button
                                 onClick={() => handleStartVerification(listing)}
                                 className="p-2 rounded-lg bg-amber-500/10 text-amber-400 border border-amber-500/20 hover:bg-amber-500/20 transition-all"
                               >
                                  <Shield className="w-4 h-4" />
                               </button>
                            </Tooltip>
                         ) : listing.status === 'draft' ? (
                            <Tooltip content="Publish to Marketplace">
                               <button
                                 onClick={() => handlePublish(listing)}
                                 className="p-2 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 hover:bg-emerald-500/20 transition-all"
                               >
                                  <CheckCircle className="w-4 h-4" />
                               </button>
                            </Tooltip>
                         ) : (
                            <Tooltip content="View public listing">
                               <Link
                                 href={`/buy/${listing.slug}`}
                                 target="_blank"
                                 className="p-2 rounded-lg bg-white/5 text-zinc-400 hover:text-white hover:bg-white/10 transition-all"
                               >
                                  <ExternalLink className="w-4 h-4" />
                               </Link>
                            </Tooltip>
                         )}

                         <Tooltip content="Delete listing">
                            <button
                              onClick={() => handleDelete(listing)}
                              className="p-2 rounded-lg text-zinc-600 hover:text-rose-400 hover:bg-rose-500/10 transition-all"
                            >
                               <Trash2 className="w-4 h-4" />
                            </button>
                         </Tooltip>
                      </div>

                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

        </div>

        {/* Create Modal */}
        {showCreateModal && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
            <div className="w-full max-w-lg bg-[#0A0A0A] border border-white/10 rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
               <div className="p-6 border-b border-white/5">
                  <h2 className="text-xl font-bold text-white">Create Listing</h2>
                  <p className="text-sm text-zinc-500">List your domain for sale on the marketplace</p>
               </div>
              
              <form onSubmit={handleCreate} className="p-6 space-y-5">
                <div>
                  <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Domain Name</label>
                  <input
                    type="text"
                    required
                    value={newListing.domain}
                    onChange={(e) => setNewListing({ ...newListing, domain: e.target.value })}
                    placeholder="example.com"
                    className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 focus:bg-white/10 transition-all font-mono"
                  />
                </div>
                
                <div>
                  <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Headline</label>
                  <input
                    type="text"
                    value={newListing.title}
                    onChange={(e) => setNewListing({ ...newListing, title: e.target.value })}
                    placeholder="Short, catchy title (e.g. Perfect for AI Startups)"
                    className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
                  />
                </div>
                
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Price (USD)</label>
                    <div className="relative">
                      <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" />
                      <input
                        type="number"
                        value={newListing.asking_price}
                        onChange={(e) => setNewListing({ ...newListing, asking_price: e.target.value })}
                        placeholder="Make Offer"
                        className="w-full pl-9 pr-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all font-mono"
                      />
                    </div>
                  </div>
                  
                  <div>
                    <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Type</label>
                    <select
                      value={newListing.price_type}
                      onChange={(e) => setNewListing({ ...newListing, price_type: e.target.value })}
                      className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:border-emerald-500/50 transition-all appearance-none"
                    >
                      <option value="negotiable">Negotiable</option>
                      <option value="fixed">Fixed Price</option>
                      <option value="make_offer">Make Offer</option>
                    </select>
                  </div>
                </div>
                
                <label className="flex items-center gap-3 cursor-pointer p-3 rounded-lg border border-white/5 hover:bg-white/5 transition-colors">
                  <input
                    type="checkbox"
                    checked={newListing.allow_offers}
                    onChange={(e) => setNewListing({ ...newListing, allow_offers: e.target.checked })}
                    className="w-5 h-5 rounded border-white/20 bg-black text-emerald-500 focus:ring-emerald-500 focus:ring-offset-0"
                  />
                  <span className="text-sm text-zinc-300">Allow buyers to submit offers</span>
                </label>
                
                <div className="flex gap-3 pt-4">
                  <button
                    type="button"
                    onClick={() => setShowCreateModal(false)}
                    className="flex-1 px-4 py-3 border border-white/10 text-zinc-400 rounded-xl hover:bg-white/5 hover:text-white transition-all font-medium"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={creating}
                    className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-emerald-500 text-white font-bold rounded-xl hover:bg-emerald-400 transition-all disabled:opacity-50 shadow-lg shadow-emerald-500/20"
                  >
                    {creating ? <Loader2 className="w-5 h-5 animate-spin" /> : <Plus className="w-5 h-5" />}
                    {creating ? 'Creating...' : 'Create Listing'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* Verify Modal */}
        {showVerifyModal && verificationInfo && selectedListing && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
            <div className="w-full max-w-xl bg-[#0A0A0A] border border-white/10 rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
               <div className="p-6 border-b border-white/5 bg-white/[0.02]">
                  <h2 className="text-xl font-bold text-white mb-2">Verify Ownership</h2>
                  <p className="text-sm text-zinc-400">
                    Add this DNS TXT record to <strong>{selectedListing.domain}</strong> to prove you own it.
                  </p>
               </div>
              
              <div className="p-6 space-y-6">
                <div className="grid grid-cols-3 gap-4">
                   <div className="col-span-1">
                      <div className="text-[10px] font-bold text-zinc-500 uppercase tracking-wider mb-2">Type</div>
                      <div className="p-3 bg-white/5 border border-white/10 rounded-lg font-mono text-white text-center">
                         {verificationInfo.dns_record_type}
                      </div>
                   </div>
                   <div className="col-span-2">
                      <div className="text-[10px] font-bold text-zinc-500 uppercase tracking-wider mb-2">Name / Host</div>
                      <div className="p-3 bg-white/5 border border-white/10 rounded-lg font-mono text-white flex justify-between items-center group cursor-pointer" onClick={() => copyToClipboard(verificationInfo.dns_record_name)}>
                         <span className="truncate">{verificationInfo.dns_record_name}</span>
                         <Copy className="w-4 h-4 text-zinc-500 group-hover:text-emerald-400 transition-colors" />
                      </div>
                   </div>
                </div>
                
                <div>
                   <div className="text-[10px] font-bold text-zinc-500 uppercase tracking-wider mb-2">Value</div>
                   <div className="p-3 bg-white/5 border border-white/10 rounded-lg font-mono text-sm text-zinc-300 break-all flex justify-between items-start gap-4 group cursor-pointer" onClick={() => copyToClipboard(verificationInfo.dns_record_value)}>
                      {verificationInfo.dns_record_value}
                      <Copy className="w-4 h-4 text-zinc-500 group-hover:text-emerald-400 transition-colors shrink-0 mt-0.5" />
                   </div>
                </div>
                
                <div className="p-4 bg-emerald-500/5 border border-emerald-500/10 rounded-xl">
                  <p className="text-xs text-emerald-400/80 leading-relaxed">
                    <InfoIcon className="w-4 h-4 inline mr-1.5 -mt-0.5" />
                    After adding the record, it may take up to 24 hours to propagate, though typically it's instant. Click verify below to check.
                  </p>
                </div>
              </div>
              
              <div className="flex gap-3 p-6 pt-0">
                <button
                  onClick={() => setShowVerifyModal(false)}
                  className="flex-1 px-4 py-3 border border-white/10 text-zinc-400 rounded-xl hover:bg-white/5 hover:text-white transition-all font-medium"
                >
                  Close
                </button>
                <button
                  onClick={handleCheckVerification}
                  disabled={verifying}
                  className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-emerald-500 text-white font-bold rounded-xl hover:bg-emerald-400 transition-all disabled:opacity-50 shadow-lg shadow-emerald-500/20"
                >
                  {verifying ? <Loader2 className="w-5 h-5 animate-spin" /> : <Shield className="w-5 h-5" />}
                  {verifying ? 'Verifying...' : 'Verify Now'}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </TerminalLayout>
  )
}

function InfoIcon(props: any) {
   return (
      <svg {...props} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
   )
}
