'use client'

import { useEffect, useState, useCallback } from 'react'
import { useSearchParams } from 'next/navigation'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Sidebar } from '@/components/Sidebar'
import {
  Plus, Shield, Eye, ExternalLink, Loader2, Trash2,
  CheckCircle, AlertCircle, Copy, X, Tag, Sparkles,
  TrendingUp, Gavel, Target, Menu, Settings, LogOut, Crown, Zap, Coins,
  ArrowRight, RefreshCw, Globe, Lock, Briefcase, MessageSquare, Mail, Phone, Building, Send
} from 'lucide-react'
import Link from 'next/link'
import Image from 'next/image'
import clsx from 'clsx'

// ============================================================================
// 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
  verification_status: string
  is_verified: boolean
  status: string
  sold_at?: string | null
  sold_reason?: string | null
  sold_price?: number | null
  sold_currency?: string | null
  view_count: number
  inquiry_count: number
  public_url: string
  created_at: string
}

interface ListingInquiry {
  id: number
  name: string
  email: string
  phone: string | null
  company: string | null
  message: string
  offer_amount: number | null
  status: string
  created_at: string
  read_at: string | null
}

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

export default function MyListingsPage() {
  const { subscription, user, logout, checkAuth } = useStore()
  const searchParams = useSearchParams()
  const prefillDomain = searchParams.get('domain')
  
  const [listings, setListings] = useState<Listing[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreateWizard, setShowCreateWizard] = useState(false)
  const [selectedListing, setSelectedListing] = useState<Listing | null>(null)
  const [leadsListing, setLeadsListing] = useState<Listing | null>(null)
  const [soldListing, setSoldListing] = useState<Listing | null>(null)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [menuOpen, setMenuOpen] = useState(false)
  
  const tier = subscription?.tier || 'scout'
  const listingLimits: Record<string, number> = { scout: 0, trader: 10, tycoon: Infinity }
  const maxListings = listingLimits[tier] || 0
  const canAddMore = listings.length < maxListings
  const isTycoon = tier === 'tycoon'
  const isUnlimited = tier === 'tycoon'
  const formatLimit = (limit: number) => limit === Infinity ? '∞' : String(limit)

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

  useEffect(() => { checkAuth() }, [checkAuth])
  useEffect(() => { if (prefillDomain) setShowCreateWizard(true) }, [prefillDomain])

  const loadListings = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api.getMyListings()
      setListings(data)
    } catch (err) { console.error(err) }
    finally { setLoading(false) }
  }, [])

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

  const handleDelete = async (id: number, domain: string) => {
    if (!confirm(`Delete listing for ${domain}?`)) return
    setDeletingId(id)
    try {
      await api.deleteListing(id)
      await loadListings()
    } catch (err: any) { alert(err.message || 'Failed') }
    finally { setDeletingId(null) }
  }

  const handlePublish = async (listing: Listing) => {
    if (!listing.is_verified) {
      setSelectedListing(listing)
      return
    }
    try {
      await api.updateListing(listing.id, { status: 'active' })
      await loadListings()
    } catch (err: any) { alert(err.message || 'Failed to publish') }
  }

  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 tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === '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 },
      { href: '/terminal/listing', label: 'For Sale', icon: Tag, active: true },
    ]}
  ]

  // ============================================================================
  // MAIN LISTING VIEW (All tiers - Scout has 1 listing, Trader 10, Tycoon unlimited)
  // ============================================================================
  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">For Sale</span>
              </div>
              <span className="text-[10px] font-mono text-white/40">{listings.length}/{formatLimit(maxListings)}</span>
            </div>
            <div className="grid grid-cols-4 gap-2">
              <div className="bg-accent/[0.05] border border-accent/20 p-2">
                <div className="text-lg font-bold text-accent tabular-nums">{activeListings}</div>
                <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Live</div>
              </div>
              <div className="bg-amber-400/[0.05] border border-amber-400/20 p-2">
                <div className="text-lg font-bold text-amber-400 tabular-nums">{draftListings}</div>
                <div className="text-[9px] font-mono text-amber-400/60 uppercase tracking-wider">Draft</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">{totalViews}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Views</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">{totalInquiries}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Leads</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">For Sale</span>
              </div>
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em]">
                <span className="text-white">For Sale</span>
                <span className="text-white/30 ml-3 font-mono text-[2rem]">{listings.length}/{formatLimit(maxListings)}</span>
              </h1>
              <p className="text-sm text-white/40 font-mono mt-2 max-w-lg">
                List your domains for sale. 0% commission, verified ownership, direct buyer contact.
              </p>
            </div>
            <div className="flex items-center gap-6">
              <div className="flex gap-8">
                <div className="text-right">
                  <div className="text-2xl font-bold text-accent font-mono">{activeListings}</div>
                  <div className="text-[9px] font-mono text-white/30 uppercase">Live</div>
                </div>
                <div className="text-right">
                  <div className="text-2xl font-bold text-amber-400 font-mono">{draftListings}</div>
                  <div className="text-[9px] font-mono text-white/30 uppercase">Draft</div>
                </div>
                <div className="text-right">
                  <div className="text-2xl font-bold text-white font-mono">{totalViews}</div>
                  <div className="text-[9px] font-mono text-white/30 uppercase">Views</div>
                </div>
                <div className="text-right">
                  <div className="text-2xl font-bold text-white font-mono">{totalInquiries}</div>
                  <div className="text-[9px] font-mono text-white/30 uppercase">Leads</div>
                </div>
              </div>
              <button onClick={() => setShowCreateWizard(true)} disabled={!canAddMore}
                className={clsx("flex items-center gap-2 px-4 py-2.5 text-xs font-bold uppercase tracking-wider transition-colors", 
                  canAddMore ? "bg-accent text-black hover:bg-white" : "bg-white/10 text-white/40 cursor-not-allowed")}>
                <Plus className="w-4 h-4" />New Listing
              </button>
            </div>
          </div>
        </section>

        {/* ADD BUTTON MOBILE */}
        <section className="lg:hidden px-4 py-3 border-b border-white/[0.08]">
          <button onClick={() => setShowCreateWizard(true)} disabled={!canAddMore}
            className={clsx("w-full flex items-center justify-center gap-2 py-3 text-xs font-bold uppercase tracking-wider", 
              canAddMore ? "bg-accent text-black" : "bg-white/10 text-white/40")}>
            <Plus className="w-4 h-4" />New Listing
          </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>
          ) : listings.length === 0 ? (
            <div className="text-center py-24 border border-dashed border-white/[0.08] bg-white/[0.01]">
              <Tag 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 listings yet</p>
              <p className="text-white/20 text-xs font-mono mt-3 uppercase tracking-wider max-w-sm mx-auto leading-relaxed">
                Create your first listing to start selling domains
              </p>
              <button onClick={() => setShowCreateWizard(true)} className="mt-6 inline-flex items-center gap-2 px-5 py-3 bg-accent text-black text-xs font-black uppercase tracking-widest hover:bg-white transition-colors">
                <Plus className="w-4 h-4" />Create Listing
              </button>
            </div>
          ) : (
            <div className="border border-white/[0.08] bg-[#020202] overflow-hidden">
              {/* Header */}
              <div className="hidden lg:grid grid-cols-[1fr_100px_90px_70px_70px_140px] 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-right">Price</div>
                <div className="text-center">Status</div>
                <div className="text-center">Views</div>
                <div className="text-center">Leads</div>
                <div className="text-right">Actions</div>
              </div>
              
              {/* Table Body */}
              <div className="divide-y divide-white/[0.04]">
              {listings.map((listing) => (
                <ListingRow
                  key={listing.id}
                  listing={listing}
                  isTycoon={isTycoon}
                  onDelete={() => handleDelete(listing.id, listing.domain)}
                  onVerify={() => setSelectedListing(listing)}
                  onPublish={() => handlePublish(listing)}
                  onLeads={() => setLeadsListing(listing)}
                  onMarkSold={() => setSoldListing(listing)}
                  isDeleting={deletingId === listing.id}
                />
              ))}
              </div>
            </div>
          )}

          {!canAddMore && listings.length >= maxListings && (
            <div className="mt-6 p-6 border border-white/[0.08] bg-white/[0.02] text-center">
              <Crown className="w-6 h-6 text-amber-400 mx-auto mb-3" />
              <h3 className="text-sm font-bold text-white mb-1">Listing Limit Reached</h3>
              <p className="text-xs font-mono text-white/40 mb-4">
                {tier === 'trader' ? 'Upgrade to Tycoon for 50 listings' : 'Contact us for enterprise plans'}
              </p>
              {tier === 'trader' && (
              <Link href="/pricing" className="inline-flex items-center gap-2 px-4 py-2 bg-amber-400 text-black text-xs font-bold uppercase tracking-wider">
                  <Sparkles className="w-3 h-3" />Upgrade to Tycoon
              </Link>
              )}
            </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 && (
          <MobileDrawer
            user={user}
            tierName={tierName}
            TierIcon={TierIcon}
            drawerNavSections={drawerNavSections}
            onClose={() => setMenuOpen(false)}
            onLogout={() => { logout(); setMenuOpen(false) }}
          />
        )}
      </main>

      {/* CREATE WIZARD (3-Step) */}
      {showCreateWizard && (
        <CreateListingWizard
          onClose={() => setShowCreateWizard(false)}
          onSuccess={() => { loadListings(); setShowCreateWizard(false) }}
          prefillDomain={prefillDomain || ''}
        />
      )}

      {/* DNS VERIFICATION MODAL */}
      {selectedListing && (
        <DnsVerificationModal
          listing={selectedListing}
          onClose={() => setSelectedListing(null)}
          onVerified={() => { loadListings(); setSelectedListing(null) }}
        />
      )}

      {/* LEADS MODAL */}
      {leadsListing && (
        <LeadsModal
          listing={leadsListing}
          onClose={() => setLeadsListing(null)}
        />
      )}

      {soldListing && (
        <MarkSoldModal
          listing={soldListing}
          onClose={() => setSoldListing(null)}
          onDone={() => { loadListings(); setSoldListing(null) }}
        />
      )}
    </div>
  )
}

// ============================================================================
// LISTING ROW COMPONENT
// ============================================================================

function ListingRow({ 
  listing, 
  isTycoon, 
  onDelete, 
  onVerify, 
  onPublish, 
  onLeads,
  onMarkSold,
  isDeleting 
}: { 
  listing: Listing
  isTycoon: boolean
  onDelete: () => void
  onVerify: () => void
  onPublish: () => void
  onLeads: () => void
  onMarkSold: () => void
  isDeleting: boolean
}) {
  const isDraft = listing.status === 'draft'
  const isActive = listing.status === 'active'
  const needsVerification = !listing.is_verified

  return (
    <div 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">
            <div>
                        <span className="text-sm font-bold text-white font-mono">{listing.domain}</span>
              {isTycoon && <span className="ml-2 px-1 py-0.5 text-[8px] font-mono bg-amber-400/10 text-amber-400 border border-amber-400/20">Featured</span>}
            </div>
                      </div>
                      <span className={clsx("px-1.5 py-0.5 text-[9px] font-mono border",
            isActive ? "bg-accent/10 text-accent border-accent/20" : 
            isDraft ? "bg-amber-400/10 text-amber-400 border-amber-400/20" : 
            "bg-white/5 text-white/40 border-white/10"
                      )}>{listing.status}</span>
                    </div>
        <div className="flex justify-between text-[10px] font-mono text-white/40 mb-2">
          <span>${listing.asking_price?.toLocaleString() || 'Make Offer'}</span>
                      <span>{listing.view_count} views · {listing.inquiry_count} leads</span>
                    </div>
        <div className="flex gap-2">
          {isDraft && needsVerification && (
            <button onClick={onVerify} className="flex-1 py-2 bg-amber-400/10 border border-amber-400/20 text-amber-400 text-[10px] font-mono uppercase flex items-center justify-center gap-1">
              <Shield className="w-3 h-3" />Verify DNS
            </button>
          )}
          {isDraft && !needsVerification && (
            <button onClick={onPublish} className="flex-1 py-2 bg-accent text-black text-[10px] font-bold uppercase flex items-center justify-center gap-1">
              <Globe className="w-3 h-3" />Publish
            </button>
          )}
          {isActive && (
                      <a href={listing.public_url} target="_blank" className="flex-1 py-2 border border-white/[0.08] text-[10px] font-mono text-white/40 flex items-center justify-center gap-1">
                        <ExternalLink className="w-3 h-3" />View
                      </a>
          )}
          {isActive && (
            <button
              type="button"
              onClick={onMarkSold}
              className="px-4 py-2 border border-white/[0.08] text-white/40 hover:text-accent"
              title="Mark as sold"
            >
              <CheckCircle className="w-4 h-4" />
            </button>
          )}
          {listing.inquiry_count > 0 && (
            <button
              type="button"
              onClick={onLeads}
              className="px-4 py-2 border border-white/[0.08] text-white/40 hover:text-accent"
              title="View buyer inquiries"
            >
              <MessageSquare className="w-4 h-4" />
            </button>
          )}
          <button onClick={onDelete} disabled={isDeleting}
                        className="px-4 py-2 border border-white/[0.08] text-white/40 hover:text-rose-400">
            {isDeleting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                  
                  {/* Desktop */}
      <div className="hidden lg:grid grid-cols-[1fr_100px_90px_70px_70px_140px] 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">{listing.domain}</span>
                      <div className="flex items-center gap-2 text-[9px] font-mono text-white/20 uppercase tracking-wider opacity-0 group-hover:opacity-100 transition-opacity">
                        {isTycoon && <span className="px-1 py-0.5 bg-amber-400/10 text-amber-400 border border-amber-400/20">Featured</span>}
                        {!listing.is_verified && <span className="text-amber-400/60">Unverified</span>}
                      </div>
                    </div>
                    <div className="text-right text-sm font-bold font-mono text-accent">${listing.asking_price?.toLocaleString() || '—'}</div>
                    <div className="flex justify-center">
          <span className={clsx("px-2.5 py-1.5 text-[10px] font-mono font-bold uppercase border",
            isActive ? "bg-accent/10 text-accent border-accent/20" : 
            isDraft ? "bg-amber-400/10 text-amber-400 border-amber-400/20" : 
            "bg-white/5 text-white/40 border-white/10"
                      )}>{listing.status}</span>
                    </div>
                    <div className="text-center text-sm font-mono text-white/50">{listing.view_count}</div>
                    <div className="text-center text-sm font-mono text-white/50">{listing.inquiry_count}</div>
        <div className="flex items-center justify-end gap-1 opacity-40 group-hover:opacity-100 transition-all">
          {isDraft && needsVerification && (
            <button onClick={onVerify} className="h-8 px-3 bg-amber-400/10 border border-amber-400/20 text-amber-400 text-[9px] font-mono uppercase hover:bg-amber-400/20 transition-colors">
              Verify
            </button>
          )}
          {isDraft && !needsVerification && (
            <button onClick={onPublish} className="h-8 px-3 bg-accent text-black text-[9px] font-bold uppercase hover:bg-white transition-colors">
              Publish
            </button>
          )}
          {isActive && (
                      <a href={listing.public_url} target="_blank" className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40 hover:text-accent hover:border-accent/20 hover:bg-accent/10 transition-all">
                        <ExternalLink className="w-3.5 h-3.5" />
                      </a>
          )}
          {isActive && (
            <button
              type="button"
              onClick={onMarkSold}
              className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40 hover:text-accent hover:border-accent/20 hover:bg-accent/10 transition-all"
              title="Mark as sold"
            >
              <CheckCircle className="w-3.5 h-3.5" />
            </button>
          )}
          {listing.inquiry_count > 0 && (
            <button
              type="button"
              onClick={onLeads}
              className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40 hover:text-accent hover:border-accent/20 hover:bg-accent/10 transition-all"
              title="View buyer inquiries"
            >
              <MessageSquare className="w-3.5 h-3.5" />
            </button>
          )}
          <button onClick={onDelete} disabled={isDeleting}
                        className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40 hover:text-rose-400 hover:border-rose-400/20 hover:bg-rose-500/10 transition-all">
            {isDeleting ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Trash2 className="w-3.5 h-3.5" />}
                      </button>
                    </div>
                  </div>
                </div>
  )
}

// ============================================================================
// MARK SOLD MODAL (GMV tracking)
// ============================================================================

function MarkSoldModal({ listing, onClose, onDone }: { listing: Listing; onClose: () => void; onDone: () => void }) {
  const [reason, setReason] = useState<'sold_on_pounce' | 'sold_off_platform' | 'removed' | 'other'>('sold_on_pounce')
  const [price, setPrice] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSave = async () => {
    setSaving(true)
    setError(null)
    try {
      const soldPrice = price.trim() ? Number(price) : null
      if (soldPrice !== null && !Number.isFinite(soldPrice)) {
        throw new Error('Invalid price')
      }
      await api.updateListing(listing.id, {
        status: 'sold',
        sold_reason: reason,
        sold_price: soldPrice,
        sold_currency: listing.currency || 'USD',
      })
      onDone()
    } catch (err: any) {
      setError(err?.message || 'Failed')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <button type="button" onClick={onClose} className="absolute inset-0 bg-black/70" aria-label="Close" />
      <div className="relative w-full max-w-md border border-white/[0.10] bg-[#020202] shadow-2xl">
        <div className="flex items-start justify-between gap-4 p-4 border-b border-white/[0.08]">
          <div>
            <div className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Mark Sold</div>
            <h3 className="mt-1 text-lg font-display text-white">{listing.domain}</h3>
            <p className="mt-1 text-xs font-mono text-white/40">Close the deal and capture GMV (optional).</p>
            </div>
          <button type="button" onClick={onClose} className="p-1 text-white/40 hover:text-white" aria-label="Close">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-4 space-y-3">
          {error && <div className="p-3 border border-rose-400/20 bg-rose-400/5 text-rose-300 text-xs font-mono">{error}</div>}

          <div>
            <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Reason</label>
            <select
              value={reason}
              onChange={(e) => setReason(e.target.value as any)}
              className="w-full px-3 py-2 bg-[#0A0A0A] border border-white/10 text-white font-mono text-sm focus:outline-none focus:border-accent"
            >
              <option value="sold_on_pounce">Sold on Pounce</option>
              <option value="sold_off_platform">Sold off-platform</option>
              <option value="removed">Removed</option>
              <option value="other">Other</option>
            </select>
            </div>

          <div>
            <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Deal Value (optional)</label>
            <input
              type="number"
              value={price}
              onChange={(e) => setPrice(e.target.value)}
              placeholder="e.g. 2500"
              className="w-full px-3 py-2 bg-[#0A0A0A] border border-white/10 text-white font-mono text-sm placeholder:text-white/20 focus:outline-none focus:border-accent"
            />
            <div className="mt-1 text-[10px] font-mono text-white/30">Currency: {listing.currency || 'USD'}</div>
          </div>

          <div className="flex gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 py-2 border border-white/10 text-white/60 text-[10px] font-mono uppercase hover:text-white hover:bg-white/[0.03]"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={handleSave}
              disabled={saving}
              className="flex-1 py-2 bg-accent text-black text-[10px] font-bold uppercase disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
              Confirm
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

// ============================================================================
// LEADS MODAL
// ============================================================================

function LeadsModal({ listing, onClose }: { listing: Listing; onClose: () => void }) {
  const { user } = useStore()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [inquiries, setInquiries] = useState<ListingInquiry[]>([])
  const [updatingId, setUpdatingId] = useState<number | null>(null)
  const [closingId, setClosingId] = useState<number | null>(null)
  const [closeReason, setCloseReason] = useState('')
  const [threadInquiry, setThreadInquiry] = useState<ListingInquiry | null>(null)
  const [threadMessages, setThreadMessages] = useState<any[]>([])
  const [loadingThread, setLoadingThread] = useState(false)
  const [sendingThread, setSendingThread] = useState(false)
  const [threadDraft, setThreadDraft] = useState('')

  useEffect(() => {
    let mounted = true
    setLoading(true)
    setError(null)
    api.getListingInquiries(listing.id)
      .then((data) => {
        if (!mounted) return
        setInquiries(data as ListingInquiry[])
      })
      .catch((err: any) => {
        if (!mounted) return
        setError(err?.message || 'Failed to load inquiries')
      })
      .finally(() => {
        if (!mounted) return
        setLoading(false)
      })
    return () => { mounted = false }
  }, [listing.id])

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

  const updateInquiryStatus = async (
    inquiryId: number,
    data: { status: 'new' | 'read' | 'replied' | 'closed' | 'spam'; reason?: string | null }
  ) => {
    setUpdatingId(inquiryId)
    try {
      const updated = await api.updateListingInquiry(listing.id, inquiryId, data) as ListingInquiry
      setInquiries(prev => prev.map(i => i.id === inquiryId ? { ...i, ...updated } : i))
    } catch (err: any) {
      setError(err?.message || 'Failed to update inquiry')
    } finally {
      setUpdatingId(null)
    }
  }

  const openThread = async (inq: ListingInquiry) => {
    setThreadInquiry(inq)
    setLoadingThread(true)
    setError(null)
    try {
      const msgs = await api.getInquiryMessagesAsSeller(listing.id, inq.id)
      setThreadMessages(msgs)
      if (!inq.read_at) {
        await updateInquiryStatus(inq.id, { status: 'read' })
      }
    } catch (err: any) {
      setError(err?.message || 'Failed to load thread')
    } finally {
      setLoadingThread(false)
    }
  }

  const sendThreadMessage = async () => {
    if (!threadInquiry) return
    const body = threadDraft.trim()
    if (!body) return
    setSendingThread(true)
    setError(null)
    try {
      const created = await api.sendInquiryMessageAsSeller(listing.id, threadInquiry.id, body)
      setThreadDraft('')
      setThreadMessages(prev => [...prev, created])
      await updateInquiryStatus(threadInquiry.id, { status: 'replied' })
    } catch (err: any) {
      setError(err?.message || 'Failed to send message')
    } finally {
      setSendingThread(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <button type="button" onClick={onClose} className="absolute inset-0 bg-black/70" aria-label="Close" />
      <div className="relative w-full max-w-2xl border border-white/[0.10] bg-[#020202] shadow-2xl">
        <div className="flex items-start justify-between gap-4 p-4 border-b border-white/[0.08]">
          <div>
            <div className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Leads</div>
            <h3 className="mt-1 text-lg font-display text-white">{listing.domain}</h3>
            <p className="mt-1 text-xs font-mono text-white/40">
              Buyer inquiries sent through Pounce.
            </p>
          </div>
          <button type="button" onClick={onClose} className="p-1 text-white/40 hover:text-white" aria-label="Close">
            <X className="w-5 h-5" />
          </button>
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-6 h-6 text-accent animate-spin" />
          </div>
        ) : error ? (
          <div className="p-6 text-sm font-mono text-rose-400">{error}</div>
        ) : inquiries.length === 0 ? (
          <div className="p-6 text-sm font-mono text-white/40">No inquiries yet.</div>
        ) : (
          <div className="max-h-[70vh] overflow-auto">
            <div className="space-y-px">
              {inquiries.map((inq) => (
                <div key={inq.id} className="p-4 border-b border-white/[0.06] bg-white/[0.02]">
                  <div className="flex items-start justify-between gap-4">
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-bold text-white">{inq.name}</span>
                        {inq.offer_amount ? (
                          <span className="px-2 py-0.5 text-[10px] font-mono uppercase border border-accent/20 bg-accent/10 text-accent">
                            Offer {formatOffer(inq.offer_amount)}
                          </span>
                        ) : (
                          <span className="px-2 py-0.5 text-[10px] font-mono uppercase border border-white/[0.10] bg-white/[0.03] text-white/50">
                            Inquiry
                          </span>
                        )}
                        {!inq.read_at && (
                          <span className="px-2 py-0.5 text-[10px] font-mono uppercase border border-amber-400/20 bg-amber-400/10 text-amber-400">
                            New
                          </span>
                        )}
                      </div>
                      <div className="mt-1 flex flex-wrap items-center gap-3 text-[11px] font-mono text-white/40">
                        <span className="flex items-center gap-1">
                          <Mail className="w-3.5 h-3.5" />
                          {inq.email}
                        </span>
                        {inq.phone && (
                          <span className="flex items-center gap-1">
                            <Phone className="w-3.5 h-3.5" />
                            {inq.phone}
                          </span>
                        )}
                        {inq.company && (
                          <span className="flex items-center gap-1">
                            <Building className="w-3.5 h-3.5" />
                            {inq.company}
                          </span>
                        )}
                      </div>
                </div>
                    <div className="text-right text-[10px] font-mono text-white/30 shrink-0">
                      {new Date(inq.created_at).toLocaleString('en-US')}
              </div>
                  </div>

                  <div className="mt-3 whitespace-pre-line text-sm text-white/70 leading-relaxed">
                    {inq.message}
                </div>

                  <div className="mt-3 flex flex-wrap justify-end gap-2">
                    {!inq.read_at && (
                      <button
                        type="button"
                        onClick={() => updateInquiryStatus(inq.id, { status: 'read' })}
                        disabled={updatingId === inq.id}
                        className="inline-flex items-center gap-2 px-3 py-2 bg-white/[0.03] border border-white/[0.10] text-white/60 hover:text-white hover:bg-white/[0.06] text-[10px] font-mono uppercase tracking-wider transition-colors disabled:opacity-50"
                        title="Mark as read"
                      >
                        {updatingId === inq.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
                        Read
            </button>
                    )}
                    <button
                      type="button"
                      onClick={() => openThread(inq)}
                      className="inline-flex items-center gap-2 px-3 py-2 bg-accent/10 border border-accent/20 text-accent hover:bg-accent/20 text-[10px] font-mono uppercase tracking-wider transition-colors"
                      title="Open thread"
                    >
                      <MessageSquare className="w-4 h-4" />
                      Thread
                    </button>
                    {inq.status !== 'closed' && (
                      <button
                        type="button"
                        onClick={() => { setClosingId(inq.id); setCloseReason('') }}
                        disabled={updatingId === inq.id}
                        className="inline-flex items-center gap-2 px-3 py-2 bg-white/[0.03] border border-white/[0.10] text-white/60 hover:text-white hover:bg-white/[0.06] text-[10px] font-mono uppercase tracking-wider transition-colors disabled:opacity-50"
                        title="Close inquiry"
                      >
                        <CheckCircle className="w-4 h-4" />
                        Close
                      </button>
                    )}
                    <button
                      type="button"
                      onClick={() => updateInquiryStatus(inq.id, { status: 'spam', reason: 'spam' })}
                      disabled={updatingId === inq.id}
                      className="inline-flex items-center gap-2 px-3 py-2 bg-white/[0.03] border border-white/[0.10] text-white/60 hover:text-rose-300 hover:border-rose-400/30 hover:bg-rose-400/10 text-[10px] font-mono uppercase tracking-wider transition-colors disabled:opacity-50"
                      title="Mark as spam"
                    >
                      {updatingId === inq.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <AlertCircle className="w-4 h-4" />}
                      Spam
                    </button>
                    <a
                      href={`mailto:${encodeURIComponent(inq.email)}?subject=${encodeURIComponent(`Re: ${listing.domain}`)}`}
                      className="inline-flex items-center gap-2 px-3 py-2 bg-white/[0.03] border border-white/[0.10] text-white/50 hover:text-white hover:bg-white/[0.06] text-[10px] font-mono uppercase tracking-wider transition-colors"
                      title="Fallback: reply via email"
                    >
                      Email
                      <Mail className="w-4 h-4" />
                    </a>
          </div>

                  {closingId === inq.id && (
                    <div className="mt-3 p-3 border border-white/[0.10] bg-white/[0.02]">
                      <div className="text-[10px] font-mono text-white/40 uppercase tracking-wider mb-2">Close reason</div>
                      <div className="flex flex-col sm:flex-row gap-2">
                        <select
                          value={closeReason}
                          onChange={(e) => setCloseReason(e.target.value)}
                          className="flex-1 px-3 py-2 bg-[#0A0A0A] border border-white/10 text-white font-mono text-xs focus:outline-none focus:border-accent"
                        >
                          <option value="">Select reason</option>
                          <option value="sold_on_pounce">Sold on Pounce</option>
                          <option value="sold_off_platform">Sold off-platform</option>
                          <option value="low_offer">Low offer</option>
                          <option value="no_fit">No fit</option>
                          <option value="other">Other</option>
                        </select>
                        <div className="flex gap-2">
                          <button
                            type="button"
                            onClick={() => setClosingId(null)}
                            className="px-3 py-2 border border-white/10 text-white/60 text-[10px] font-mono uppercase hover:text-white hover:bg-white/[0.03]"
                          >
                            Cancel
                          </button>
                          <button
                            type="button"
                            disabled={!closeReason || updatingId === inq.id}
                            onClick={async () => {
                              await updateInquiryStatus(inq.id, { status: 'closed', reason: closeReason })
                              setClosingId(null)
                            }}
                            className="px-3 py-2 bg-accent text-black text-[10px] font-bold uppercase disabled:opacity-50"
                          >
                            {updatingId === inq.id ? 'Closing…' : 'Confirm'}
                          </button>
                </div>
              </div>
                    </div>
                  )}
                  </div>
                ))}
                </div>
              </div>
        )}

        {/* THREAD MODAL (nested) */}
        {threadInquiry && (
          <div className="absolute inset-0 bg-black/80 flex items-center justify-center p-4">
            <div className="w-full max-w-xl border border-white/[0.10] bg-[#020202] shadow-2xl">
              <div className="flex items-start justify-between gap-4 p-4 border-b border-white/[0.08]">
                <div>
                  <div className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Thread</div>
                  <div className="text-sm font-bold text-white">{threadInquiry.name}</div>
                  <div className="text-[10px] font-mono text-white/40 mt-1">{threadInquiry.email}</div>
                </div>
                <button
                  type="button"
                  onClick={() => setThreadInquiry(null)}
                  className="p-1 text-white/40 hover:text-white"
                  aria-label="Close thread"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="p-4 space-y-3 max-h-[50vh] overflow-auto">
                {loadingThread ? (
                  <div className="flex items-center justify-center py-10">
                    <Loader2 className="w-6 h-6 text-accent animate-spin" />
            </div>
                ) : threadMessages.length === 0 ? (
                  <div className="text-sm font-mono text-white/40">No messages yet.</div>
                ) : (
                  threadMessages.map((m: any) => (
                    <div
                      key={m.id}
                      className={clsx(
                        "p-3 border",
                        m.sender_user_id === user?.id ? "bg-accent/10 border-accent/20" : "bg-white/[0.02] border-white/[0.08]"
                      )}
                    >
                      <div className="flex items-center justify-between text-[10px] font-mono text-white/40 mb-1">
                        <span>{m.sender_user_id === user?.id ? 'You' : 'Buyer'}</span>
                        <span>{new Date(m.created_at).toLocaleString('en-US')}</span>
          </div>
                      <div className="text-sm text-white/80 whitespace-pre-line">{m.body}</div>
                    </div>
                  ))
                )}
              </div>

              <div className="p-4 border-t border-white/[0.08]">
                {threadInquiry.status === 'closed' || threadInquiry.status === 'spam' ? (
                  <div className="flex items-center gap-2 text-[11px] font-mono text-white/40">
                    <Lock className="w-4 h-4" /> Thread is closed.
                  </div>
                ) : (
                  <div className="flex gap-2">
                    <textarea
                      value={threadDraft}
                      onChange={(e) => setThreadDraft(e.target.value)}
                      placeholder="Write a message..."
                      rows={2}
                      className="flex-1 px-3 py-2 bg-[#0A0A0A] border border-white/10 text-white font-mono text-sm placeholder:text-white/20 focus:outline-none focus:border-accent"
                    />
                    <button
                      type="button"
                      onClick={sendThreadMessage}
                      disabled={sendingThread || !threadDraft.trim()}
                      className="px-4 py-2 bg-accent text-black text-xs font-bold uppercase disabled:opacity-50 flex items-center gap-2"
                    >
                      {sendingThread ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                      Send
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

// ============================================================================
// CREATE LISTING WIZARD (3-Step Process)
// ============================================================================

function CreateListingWizard({ onClose, onSuccess, prefillDomain }: { 
  onClose: () => void
  onSuccess: () => void
  prefillDomain: string 
}) {
  const [step, setStep] = useState(1)
  const [domain, setDomain] = useState(prefillDomain)
  const [price, setPrice] = useState('')
  const [priceType, setPriceType] = useState<'fixed' | 'negotiable'>('negotiable')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [createdListing, setCreatedListing] = useState<any>(null)
  const [verificationData, setVerificationData] = useState<any>(null)
  const [verifying, setVerifying] = useState(false)
  const [verified, setVerified] = useState(false)
  
  // Portfolio domains (for dropdown selection)
  const [portfolioDomains, setPortfolioDomains] = useState<{ id: number; domain: string }[]>([])
  const [loadingDomains, setLoadingDomains] = useState(true)
  
  useEffect(() => {
    const fetchPortfolioDomains = async () => {
      setLoadingDomains(true)
      try {
        const domains = await api.getPortfolio()
        // Filter out sold domains
        setPortfolioDomains(domains.filter(d => !d.is_sold).map(d => ({ id: d.id, domain: d.domain })))
      } catch (err) {
        console.error('Failed to load portfolio domains:', err)
      } finally {
        setLoadingDomains(false)
      }
    }
    fetchPortfolioDomains()
  }, [])

  // Step 1: Create listing
  const handleCreateListing = async () => {
    if (!domain.trim()) return
    setLoading(true)
    setError(null)
    try {
      const listing = await api.createListing({ 
        domain: domain.trim(), 
        asking_price: price ? parseFloat(price) : null, 
        currency: 'USD', 
        price_type: priceType 
      })
      setCreatedListing(listing)
      
      // Check if domain was already verified in portfolio
      if (listing.is_verified) {
        // Skip verification step, go directly to publish
        setVerified(true)
        setStep(3)
      } else {
        // Start DNS verification
        const verification = await api.startDnsVerification(listing.id)
        setVerificationData(verification)
        setStep(2)
      }
    } catch (err: any) { 
      setError(err.message || 'Failed to create listing') 
    } finally { 
      setLoading(false) 
    }
  }

  // Step 2: Check DNS verification
  const handleCheckVerification = async () => {
    if (!createdListing) return
    setVerifying(true)
    try {
      const result = await api.checkDnsVerification(createdListing.id)
      if (result.verified) {
        setVerified(true)
        setStep(3)
      } else {
        setError(result.message || 'DNS record not found yet. Please wait for propagation.')
      }
    } catch (err: any) { 
      setError(err.message || 'Verification check failed') 
    } finally { 
      setVerifying(false) 
    }
  }

  // Step 3: Publish
  const handlePublish = async () => {
    if (!createdListing) return
    setLoading(true)
    try {
      await api.updateListing(createdListing.id, { status: 'active' })
      onSuccess()
    } catch (err: any) { 
      setError(err.message || 'Failed to publish') 
    } finally { 
      setLoading(false) 
    }
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
  }

  return (
    <div className="fixed inset-0 z-[110] bg-black/90 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-4 border-b border-white/[0.08]">
          <div className="flex items-center gap-3">
            <Tag className="w-4 h-4 text-accent" />
            <span className="text-xs font-mono text-accent uppercase tracking-wider">New Listing</span>
        </div>
          <div className="flex items-center gap-4">
            {/* Step Indicators */}
            <div className="flex items-center gap-2">
              {[1, 2, 3].map((s) => (
                <div key={s} className={clsx(
                  "w-6 h-6 flex items-center justify-center text-[10px] font-mono border",
                  step === s ? "bg-accent text-black border-accent" :
                  step > s ? "bg-accent/20 text-accent border-accent/40" :
                  "bg-white/5 text-white/30 border-white/10"
                )}>
                  {step > s ? <CheckCircle className="w-3 h-3" /> : s}
                </div>
              ))}
            </div>
            <button onClick={onClose} className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40">
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

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

          {/* STEP 1: Domain & Price */}
          {step === 1 && (
            <div className="space-y-6">
              <div className="text-center mb-6">
                <h2 className="text-xl font-display text-white mb-2">Enter Domain Details</h2>
                <p className="text-xs font-mono text-white/40">Step 1 of 3: Set your domain and price</p>
              </div>

          <div>
                <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Select Domain from Portfolio *</label>
                {loadingDomains ? (
                  <div className="flex items-center justify-center py-4">
                    <Loader2 className="w-5 h-5 text-accent animate-spin" />
          </div>
                ) : portfolioDomains.length === 0 ? (
                  <div className="p-4 bg-amber-400/5 border border-amber-400/20 text-center">
                    <AlertCircle className="w-6 h-6 text-amber-400 mx-auto mb-2" />
                    <p className="text-xs text-amber-400 font-mono mb-3">No domains in your portfolio</p>
                    <a href="/terminal/portfolio" className="inline-flex items-center gap-2 px-4 py-2 bg-accent text-black text-xs font-bold uppercase">
                      Add Domains to Portfolio
                    </a>
                  </div>
                ) : (
                  <select 
                    value={domain} 
                    onChange={(e) => setDomain(e.target.value)}
                    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"
                  >
                    <option value="">— Select a domain —</option>
                    {portfolioDomains.map(d => (
                      <option key={d.id} value={d.domain}>{d.domain}</option>
                    ))}
                  </select>
                )}
                <p className="text-[9px] font-mono text-white/30 mt-2">
                  Only domains from your portfolio can be listed. DNS verification required after listing.
                </p>
              </div>

          <div>
                <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Price Type</label>
                <div className="grid grid-cols-2 gap-3">
                  <button 
                    type="button" 
                    onClick={() => setPriceType('fixed')}
                    className={clsx("py-3 border text-xs font-mono uppercase transition-colors",
                      priceType === 'fixed' ? "bg-accent/10 border-accent text-accent" : "border-white/10 text-white/40 hover:border-white/30"
                    )}>
                    Fixed Price
                  </button>
                  <button 
                    type="button" 
                    onClick={() => setPriceType('negotiable')}
                    className={clsx("py-3 border text-xs font-mono uppercase transition-colors",
                      priceType === 'negotiable' ? "bg-accent/10 border-accent text-accent" : "border-white/10 text-white/40 hover:border-white/30"
                    )}>
                    Make Offer
                  </button>
          </div>
              </div>

              {priceType === 'fixed' && (
                <div>
                  <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Asking Price (USD)</label>
                  <input 
                    type="number" 
                    value={price} 
                    onChange={(e) => setPrice(e.target.value)} 
                    min="0"
                    className="w-full px-4 py-3 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/20 outline-none focus:border-accent/50" 
                    placeholder="Enter price" 
                  />
                </div>
              )}

              <button 
                onClick={handleCreateListing}
                disabled={loading || !domain.trim()}
                className="w-full py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-2 disabled:opacity-50 hover:bg-white transition-colors"
              >
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <>Next: Verify Ownership <ArrowRight className="w-4 h-4" /></>}
            </button>
          </div>
          )}

          {/* STEP 2: DNS Verification */}
          {step === 2 && verificationData && (
            <div className="space-y-6">
              <div className="text-center mb-6">
                <h2 className="text-xl font-display text-white mb-2">Verify Ownership</h2>
                <p className="text-xs font-mono text-white/40">Step 2 of 3: Add a DNS TXT record to prove you own this domain</p>
              </div>

              <div className="p-4 bg-amber-400/5 border border-amber-400/20">
                <div className="flex items-start gap-3">
                  <Shield className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" />
                  <div className="text-xs text-white/60 leading-relaxed">
                    Add this TXT record to your domain&apos;s DNS settings. This proves you control the domain.
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div>
                  <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Record Type</label>
                  <div className="px-4 py-3 bg-white/5 border border-white/10 text-white text-sm font-mono">
                    TXT
                  </div>
                </div>

                <div>
                  <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Host / Name</label>
                  <div className="flex items-center gap-2">
                    <div className="flex-1 px-4 py-3 bg-white/5 border border-white/10 text-white text-sm font-mono overflow-x-auto">
                      {verificationData.dns_record_name}
                    </div>
                    <button onClick={() => copyToClipboard(verificationData.dns_record_name)} className="p-3 border border-white/10 text-white/40 hover:text-white">
                      <Copy className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                <div>
                  <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Value</label>
                  <div className="flex items-center gap-2">
                    <div className="flex-1 px-4 py-3 bg-white/5 border border-white/10 text-accent text-sm font-mono overflow-x-auto">
                      {verificationData.verification_code}
                    </div>
                    <button onClick={() => copyToClipboard(verificationData.verification_code)} className="p-3 border border-white/10 text-white/40 hover:text-white">
                      <Copy className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>

              <div className="p-3 bg-white/[0.02] border border-white/[0.08] text-[11px] font-mono text-white/40 leading-relaxed">
                💡 DNS changes can take 1-5 minutes to propagate. If verification fails, wait a moment and try again.
              </div>

              <button 
                onClick={handleCheckVerification}
                disabled={verifying}
                className="w-full py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-2 disabled:opacity-50 hover:bg-white transition-colors"
              >
                {verifying ? <Loader2 className="w-4 h-4 animate-spin" /> : <><RefreshCw className="w-4 h-4" /> Check Verification</>}
              </button>
            </div>
          )}

          {/* STEP 3: Publish */}
          {step === 3 && (
            <div className="space-y-6 text-center">
              <div className="w-16 h-16 bg-accent/10 border border-accent/20 flex items-center justify-center mx-auto">
                <CheckCircle className="w-8 h-8 text-accent" />
              </div>

          <div>
                <h2 className="text-xl font-display text-white mb-2">Ownership Verified!</h2>
                <p className="text-xs font-mono text-white/40">Step 3 of 3: Publish your listing to the Pounce Market</p>
              </div>

              <div className="p-4 bg-white/[0.02] border border-white/[0.08]">
                <div className="text-lg font-bold font-mono text-white mb-1">{domain}</div>
                <div className="text-sm text-accent font-mono">
                  {price ? `$${parseFloat(price).toLocaleString()}` : 'Make Offer'}
                </div>
              </div>

              <div className="p-3 bg-accent/5 border border-accent/20 text-[11px] font-mono text-white/60 leading-relaxed">
                Your listing will appear in the <strong>Market Feed</strong> with the <span className="text-accent">Pounce Direct</span> badge.
              </div>

              <button 
                onClick={handlePublish}
                disabled={loading}
                className="w-full py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-2 disabled:opacity-50 hover:bg-white transition-colors"
              >
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <><Globe className="w-4 h-4" /> Publish to Market</>}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

// ============================================================================
// DNS VERIFICATION MODAL (For existing drafts)
// ============================================================================

function DnsVerificationModal({ listing, onClose, onVerified }: { 
  listing: Listing
  onClose: () => void
  onVerified: () => void 
}) {
  const [verificationData, setVerificationData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [verifying, setVerifying] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    loadVerificationData()
  }, [listing.id])

  const loadVerificationData = async () => {
    try {
      const data = await api.startDnsVerification(listing.id)
      setVerificationData(data)
    } catch (err: any) {
      setError(err.message || 'Failed to load verification data')
    } finally {
      setLoading(false)
    }
  }

  const handleCheck = async () => {
    setVerifying(true)
    setError(null)
    try {
      const result = await api.checkDnsVerification(listing.id)
      if (result.verified) {
        onVerified()
      } else {
        setError(result.message || 'DNS record not found yet')
      }
    } catch (err: any) {
      setError(err.message || 'Check failed')
    } finally {
      setVerifying(false)
    }
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
  }

  return (
    <div className="fixed inset-0 z-[110] bg-black/90 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()}>
        <div className="flex items-center justify-between p-4 border-b border-white/[0.08]">
          <div className="flex items-center gap-2">
            <Shield className="w-4 h-4 text-amber-400" />
            <span className="text-xs font-mono text-amber-400 uppercase tracking-wider">DNS Verification</span>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40">
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="p-6">
          {loading ? (
            <div className="flex items-center justify-center py-10">
              <Loader2 className="w-6 h-6 text-accent animate-spin" />
            </div>
          ) : verificationData ? (
            <div className="space-y-4">
              {error && (
                <div className="p-3 bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs font-mono">
                  {error}
                </div>
              )}

              <div className="text-center mb-4">
                <h3 className="text-lg font-display text-white mb-1">{listing.domain}</h3>
                <p className="text-xs font-mono text-white/40">Add this TXT record to verify ownership</p>
              </div>

              <div>
                <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">Host / Name</label>
                <div className="flex items-center gap-2">
                  <div className="flex-1 px-4 py-3 bg-white/5 border border-white/10 text-white text-sm font-mono overflow-x-auto">
                    {verificationData.dns_record_name}
                  </div>
                  <button onClick={() => copyToClipboard(verificationData.dns_record_name)} className="p-3 border border-white/10 text-white/40 hover:text-white">
                    <Copy className="w-4 h-4" />
                  </button>
                </div>
              </div>

          <div>
                <label className="block text-[10px] font-mono text-white/40 uppercase mb-2">TXT Value</label>
                <div className="flex items-center gap-2">
                  <div className="flex-1 px-4 py-3 bg-white/5 border border-white/10 text-accent text-sm font-mono overflow-x-auto">
                    {verificationData.verification_code}
                  </div>
                  <button onClick={() => copyToClipboard(verificationData.verification_code)} className="p-3 border border-white/10 text-white/40 hover:text-white">
                    <Copy className="w-4 h-4" />
                  </button>
                </div>
              </div>

              <button 
                onClick={handleCheck}
                disabled={verifying}
                className="w-full py-3 bg-accent text-black text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {verifying ? <Loader2 className="w-4 h-4 animate-spin" /> : <><RefreshCw className="w-4 h-4" /> Check Verification</>}
              </button>
            </div>
          ) : (
            <div className="text-center py-10 text-white/40">Failed to load verification data</div>
          )}
        </div>
      </div>
    </div>
  )
}

// ============================================================================
// MOBILE DRAWER
// ============================================================================

function MobileDrawer({ user, tierName, TierIcon, drawerNavSections, onClose, onLogout }: any) {
  return (
    <div className="lg:hidden fixed inset-0 z-[100]">
      <div className="absolute inset-0 bg-black/80" onClick={onClose} />
      <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={onClose} 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: any) => (
            <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={onClose} 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={onClose} 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={onClose} 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">{tierName}</p></div>
          </div>
          {tierName === 'Scout' && <Link href="/pricing" onClick={onClose} 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={onLogout} 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>
  )
}
