'use client'

import { useEffect, useState, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { Sidebar } from '@/components/Sidebar'
import { useStore } from '@/lib/store'
import { api, PriceAlert } from '@/lib/api'
import {
  User,
  Bell,
  CreditCard,
  Shield,
  ChevronRight,
  Loader2,
  Check,
  AlertCircle,
  Trash2,
  ExternalLink,
  Crown,
  Zap,
  Key,
  TrendingUp,
  X,
  Settings,
  ArrowUp,
  ArrowDown,
  Sparkles,
  Clock,
  Target,
  BarChart3,
  MessageSquare,
  Database,
  Menu,
  Eye,
  Gavel,
  Tag,
  Coins,
  LogOut,
  Briefcase
} from 'lucide-react'
import Link from 'next/link'
import Image from 'next/image'
import clsx from 'clsx'

type SettingsTab = 'profile' | 'notifications' | 'billing' | 'security'

// Plan definitions
const PLANS = [
  {
    id: 'scout',
    name: 'Scout',
    icon: Zap,
    price: 0,
    period: 'forever',
    description: 'Perfect for getting started',
    features: [
      { icon: Target, text: '5 Watchlist Domains' },
      { icon: Clock, text: 'Daily Checks' },
      { icon: Bell, text: '2 Sniper Alerts' },
      { icon: BarChart3, text: 'Basic Market Data' },
    ],
  },
  {
    id: 'trader',
    name: 'Trader',
    icon: TrendingUp,
    price: 9,
    period: '/month',
    description: 'For serious investors',
    badge: 'Popular',
    features: [
      { icon: Target, text: '50 Watchlist Domains' },
      { icon: Clock, text: 'Hourly Checks' },
      { icon: Bell, text: '10 Sniper Alerts' },
      { icon: Sparkles, text: 'Domain Valuation' },
      { icon: Database, text: '25 Portfolio' },
      { icon: MessageSquare, text: '5 Listings' },
    ],
  },
  {
    id: 'tycoon',
    name: 'Tycoon',
    icon: Crown,
    price: 29,
    period: '/month',
    description: 'Maximum power',
    badge: 'Full Power',
    features: [
      { icon: Target, text: '500 Domains' },
      { icon: Clock, text: '10-Min Checks' },
      { icon: Bell, text: '50 Sniper Alerts' },
      { icon: Sparkles, text: 'Full SEO' },
      { icon: Database, text: 'Unlimited Portfolio' },
      { icon: MessageSquare, text: '50 Featured' },
    ],
  },
]

export default function SettingsPage() {
  const router = useRouter()
  const { user, isAuthenticated, isLoading, checkAuth, subscription, logout } = useStore()
  
  const [activeTab, setActiveTab] = useState<SettingsTab>('profile')
  const [saving, setSaving] = useState(false)
  const [success, setSuccess] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [menuOpen, setMenuOpen] = useState(false)
  const [changingPlan, setChangingPlan] = useState<string | null>(null)
  const [showCancelModal, setShowCancelModal] = useState(false)
  const [cancelling, setCancelling] = useState(false)
  
  const [profileForm, setProfileForm] = useState({ name: '', email: '' })
  const [inviteLink, setInviteLink] = useState<string | null>(null)
  const [inviteStats, setInviteStats] = useState<{
    window_days: number
    referred_users_total: number
    qualified_referrals_total: number
    referral_link_views_window: number
    bonus_domains: number
    next_reward_at: number
    badge: string | null
    cooldown_days?: number
    disqualified_cooldown_total?: number
    disqualified_missing_ip_total?: number
    disqualified_shared_ip_total?: number
    disqualified_duplicate_ip_total?: number
  } | null>(null)
  const [inviteLoading, setInviteLoading] = useState(false)
  const [inviteCopied, setInviteCopied] = useState(false)
  const [notificationPrefs, setNotificationPrefs] = useState({
    domain_availability: true,
    price_alerts: true,
    weekly_digest: false,
  })
  const [savingNotifications, setSavingNotifications] = useState(false)
  const [priceAlerts, setPriceAlerts] = useState<PriceAlert[]>([])
  const [loadingAlerts, setLoadingAlerts] = useState(false)
  const [deletingAlertId, setDeletingAlertId] = useState<number | null>(null)

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

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

  useEffect(() => {
    if (user) setProfileForm({ name: user.name || '', email: user.email || '' })
  }, [user])

  const loadInviteLink = useCallback(async () => {
    if (!isAuthenticated) return
    setInviteLoading(true)
    try {
      const res = await api.getReferralLink()
      setInviteLink(res.url)
      setInviteStats(res.stats ?? null)
    } catch {
      // don't block settings if it fails
    } finally {
      setInviteLoading(false)
    }
  }, [isAuthenticated])

  useEffect(() => {
    if (isAuthenticated && activeTab === 'profile') {
      void loadInviteLink()
    }
  }, [isAuthenticated, activeTab, loadInviteLink])

  useEffect(() => {
    if (isAuthenticated && activeTab === 'notifications') loadPriceAlerts()
  }, [isAuthenticated, activeTab])

  useEffect(() => {
    const saved = localStorage.getItem('notification_prefs')
    if (saved) try { setNotificationPrefs(JSON.parse(saved)) } catch {}
  }, [])

  // Handle URL params for upgrade success/cancel
  useEffect(() => {
    const params = new URLSearchParams(window.location.search)
    const upgraded = params.get('upgraded')
    const cancelled = params.get('cancelled')
    if (upgraded) {
      setSuccess(`Upgrade complete: ${upgraded.charAt(0).toUpperCase() + upgraded.slice(1)}`)
      setActiveTab('billing')
      window.history.replaceState({}, '', '/terminal/settings')
      checkAuth()
    }
    if (cancelled) {
      setError('Checkout cancelled.')
      setActiveTab('billing')
      window.history.replaceState({}, '', '/terminal/settings')
    }
  }, [checkAuth])

  const loadPriceAlerts = async () => {
    setLoadingAlerts(true)
    try { setPriceAlerts(await api.getPriceAlerts()) } catch {}
    finally { setLoadingAlerts(false) }
  }

  const handleSaveProfile = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true); setError(null); setSuccess(null)
    try {
      await api.updateMe({ name: profileForm.name || undefined })
      await checkAuth()
      setSuccess('Profile updated')
    } catch (err) { setError(err instanceof Error ? err.message : 'Failed') }
    finally { setSaving(false) }
  }

  const handleSaveNotifications = async () => {
    setSavingNotifications(true); setError(null); setSuccess(null)
    try { localStorage.setItem('notification_prefs', JSON.stringify(notificationPrefs)); setSuccess('Saved') }
    catch (err) { setError('Failed') }
    finally { setSavingNotifications(false) }
  }

  const handleDeletePriceAlert = async (tld: string, alertId: number) => {
    setDeletingAlertId(alertId)
    try { await api.deletePriceAlert(tld); setPriceAlerts(prev => prev.filter(a => a.id !== alertId)) }
    catch (err) { setError('Failed') }
    finally { setDeletingAlertId(null) }
  }

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

  const handlePlanChange = async (planId: string) => {
    setChangingPlan(planId); setError(null)
    try {
      if (planId === 'scout') {
        // Use the cancel modal instead of direct downgrade
        setShowCancelModal(true)
        setChangingPlan(null)
        return
      } else {
        const { checkout_url } = await api.createCheckoutSession(
          planId,
          `${window.location.origin}/terminal/settings?upgraded=${planId}`,
          `${window.location.origin}/terminal/settings?cancelled=true`
        )
        window.location.href = checkout_url
      }
    } catch (err) { setError(err instanceof Error ? err.message : 'Failed') }
    finally { setChangingPlan(null) }
  }

  const handleCancelSubscription = async () => {
    setCancelling(true); setError(null)
    try {
      await api.cancelSubscription()
      setSuccess('Your subscription has been cancelled. You are now on the Scout plan.')
      setShowCancelModal(false)
      await checkAuth()
    } catch (err) { 
      setError(err instanceof Error ? err.message : 'Failed to cancel') 
    }
    finally { setCancelling(false) }
  }

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

  if (!isAuthenticated || !user) return null

  const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const isProOrHigher = ['Trader', 'Tycoon'].includes(tierName)
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap

  const tabs = [
    { id: 'profile' as const, label: 'Profile', icon: User },
    { id: 'notifications' as const, label: 'Alerts', icon: Bell },
    { id: 'billing' as const, label: 'Plans', icon: CreditCard },
    { id: 'security' as const, label: 'Security', icon: Shield },
  ]

  // Mobile Nav - same as Intel page
  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 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, isNew: true },
      { href: '/terminal/listing', label: 'For Sale', icon: Tag },
    ]},
  ]

  return (
    <div className="min-h-screen bg-[#020202]">
      {/* Desktop Sidebar */}
      <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">
            {/* Top Row */}
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Settings</span>
              </div>
              <div className="flex items-center gap-2 text-[10px] font-mono text-white/40">
                <TierIcon className={clsx("w-3.5 h-3.5", tierName === 'Tycoon' ? "text-amber-400" : "text-accent")} />
                <span>{tierName}</span>
              </div>
            </div>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-3 gap-2">
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{subscription?.domains_used || 0}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Domains</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">
                  {subscription?.check_frequency === 'realtime' ? '10m' : subscription?.check_frequency === 'hourly' ? '1h' : '24h'}
                </div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Interval</div>
              </div>
              <div className="bg-accent/[0.05] border border-accent/20 p-2">
                <div className="text-lg font-bold text-accent tabular-nums capitalize">{subscription?.status || 'active'}</div>
                <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Status</div>
              </div>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DESKTOP HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="hidden lg:block px-10 pt-10 pb-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
            <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Settings</span>
          </div>
          <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em] text-white mb-2">Settings</h1>
          <p className="text-sm text-white/40 font-mono max-w-lg">
            Manage your account, subscription, alerts, and security preferences.
          </p>
        </section>

        {/* Messages */}
        {(error || success) && (
          <div className="px-4 lg:px-10 mb-4">
            {error && (
              <div className="p-3 bg-red-500/10 border border-red-500/20 flex items-center gap-3 text-red-400">
                <AlertCircle className="w-4 h-4 shrink-0" />
                <p className="text-xs flex-1">{error}</p>
                <button onClick={() => setError(null)}><X className="w-4 h-4" /></button>
              </div>
            )}
            {success && (
              <div className="p-3 bg-accent/10 border border-accent/20 flex items-center gap-3 text-accent">
                <Check className="w-4 h-4 shrink-0" />
                <p className="text-xs flex-1">{success}</p>
                <button onClick={() => setSuccess(null)}><X className="w-4 h-4" /></button>
              </div>
            )}
          </div>
        )}

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* TABS */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 mb-4">
          <div className="flex gap-1 overflow-x-auto scrollbar-hide pb-1">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={clsx(
                  "flex items-center gap-2 px-4 py-2.5 text-xs font-mono whitespace-nowrap transition-all border",
                  activeTab === tab.id
                    ? "bg-accent text-black border-accent"
                    : "bg-white/[0.02] border-white/[0.08] text-white/50 hover:text-white hover:border-white/20"
                )}
              >
                <tab.icon className="w-4 h-4" />
                {tab.label}
              </button>
            ))}
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* CONTENT */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 pb-24 lg:pb-10">
          
          {/* Profile Tab */}
          {activeTab === 'profile' && (
            <div className="space-y-4">
              <div className="bg-[#0A0A0A] border border-white/[0.08]">
                <div className="px-4 py-2 border-b border-white/[0.06] bg-black/40">
                  <span className="text-[10px] font-mono text-white/40">Profile Information</span>
                </div>
                <form onSubmit={handleSaveProfile} className="p-4 lg:p-6 space-y-4 max-w-md">
                  <div>
                    <label className="block text-[10px] font-mono text-white/40 uppercase tracking-wider mb-2">Name</label>
                    <input
                      type="text"
                      value={profileForm.name}
                      onChange={(e) => setProfileForm({ ...profileForm, name: e.target.value })}
                      className="w-full px-4 py-3 bg-white/[0.02] border border-white/[0.08] text-white placeholder:text-white/20 outline-none focus:border-accent/50"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-mono text-white/40 uppercase tracking-wider mb-2">Email</label>
                    <input
                      type="email"
                      value={profileForm.email}
                      disabled
                      className="w-full px-4 py-3 bg-white/[0.01] border border-white/[0.06] text-white/40 cursor-not-allowed"
                    />
                  </div>
                  <button
                    type="submit"
                    disabled={saving}
                    className="flex items-center gap-2 px-5 py-2.5 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white disabled:opacity-50"
                  >
                    {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
                    Save
                  </button>
                </form>
              </div>

              <div className="bg-[#0A0A0A] border border-white/[0.08]">
                <div className="px-4 py-2 border-b border-white/[0.06] bg-black/40 flex items-center justify-between">
                  <span className="text-[10px] font-mono text-white/40">Invite</span>
                  <span className="text-[10px] font-mono text-white/30">Earn trust by inviting operators</span>
                </div>
                <div className="p-4 lg:p-6">
                  <p className="text-sm text-white/60 mb-4">
                    Share your invite link. If someone signs up through it, we attribute the referral securely.
                  </p>
                  <div className="flex items-center gap-2">
                    <input
                      value={inviteLink || (inviteLoading ? 'Loading…' : '')}
                      readOnly
                      className="flex-1 px-4 py-3 bg-white/[0.02] border border-white/[0.08] text-white/70 outline-none"
                    />
                    <button
                      type="button"
                      disabled={!inviteLink || inviteLoading}
                      onClick={async () => {
                        if (!inviteLink) return
                        await navigator.clipboard.writeText(inviteLink)
                        setInviteCopied(true)
                        setTimeout(() => setInviteCopied(false), 1500)
                      }}
                      className="px-4 py-3 bg-white text-black text-xs font-bold uppercase tracking-wider disabled:opacity-50"
                    >
                      {inviteCopied ? 'Copied' : 'Copy'}
                    </button>
                  </div>
                  <p className="mt-2 text-[10px] font-mono text-white/30">
                    Link expires: never. Stored as a cookie on first visit (30 days).
                  </p>

                  {inviteStats ? (
                    <div className="mt-4 grid grid-cols-2 lg:grid-cols-4 gap-2">
                      <div className="p-3 bg-white/[0.02] border border-white/[0.06]">
                        <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Qualified</p>
                        <p className="text-lg text-white font-semibold">{inviteStats.qualified_referrals_total}</p>
                        <p className="text-[10px] text-white/30">Verified + active plan</p>
                      </div>
                      <div className="p-3 bg-white/[0.02] border border-white/[0.06]">
                        <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider">All-time</p>
                        <p className="text-lg text-white font-semibold">{inviteStats.referred_users_total}</p>
                        <p className="text-[10px] text-white/30">Referred signups</p>
                      </div>
                      <div className="p-3 bg-white/[0.02] border border-white/[0.06]">
                        <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Views</p>
                        <p className="text-lg text-white font-semibold">{inviteStats.referral_link_views_window}</p>
                        <p className="text-[10px] text-white/30">{inviteStats.window_days}d window</p>
                      </div>
                      <div className="p-3 bg-white/[0.02] border border-white/[0.06]">
                        <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Bonus</p>
                        <p className="text-lg text-white font-semibold">+{inviteStats.bonus_domains}</p>
                        <p className="text-[10px] text-white/30">Watchlist slots</p>
                      </div>
                      <div className="col-span-2 lg:col-span-4 p-3 bg-black/40 border border-white/[0.06] flex flex-wrap items-center justify-between gap-2">
                        <div className="flex items-center gap-2">
                          <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Badge</span>
                          <span className={clsx(
                            "px-2 py-1 text-[10px] font-mono uppercase tracking-wider border",
                            inviteStats.badge === 'elite_referrer'
                              ? "bg-accent/10 text-accent border-accent/30"
                              : inviteStats.badge === 'verified_referrer'
                              ? "bg-white/5 text-white border-white/15"
                              : "bg-white/[0.02] text-white/40 border-white/[0.06]"
                          )}>
                            {inviteStats.badge === 'elite_referrer'
                              ? 'Elite Referrer'
                              : inviteStats.badge === 'verified_referrer'
                              ? 'Verified Referrer'
                              : '—'}
                          </span>
                        </div>
                        <p className="text-[10px] font-mono text-white/30">
                          Next reward at {inviteStats.next_reward_at} qualified referrals
                        </p>
                      </div>
                      {(inviteStats.cooldown_days || inviteStats.disqualified_cooldown_total || inviteStats.disqualified_shared_ip_total || inviteStats.disqualified_duplicate_ip_total || inviteStats.disqualified_missing_ip_total) ? (
                        <div className="col-span-2 lg:col-span-4 px-1">
                          <p className="text-[10px] font-mono text-white/30">
                            Rules: cooldown {inviteStats.cooldown_days ?? 7}d. Disqualified — cooldown: {inviteStats.disqualified_cooldown_total ?? 0}, shared‑IP: {inviteStats.disqualified_shared_ip_total ?? 0}, duplicate‑IP: {inviteStats.disqualified_duplicate_ip_total ?? 0}, missing‑IP: {inviteStats.disqualified_missing_ip_total ?? 0}.
                          </p>
                        </div>
                      ) : null}
                    </div>
                  ) : null}
                </div>
              </div>
            </div>
          )}

          {/* Notifications Tab */}
          {activeTab === 'notifications' && (
            <div className="space-y-4">
              <div className="bg-[#0A0A0A] border border-white/[0.08]">
                <div className="px-4 py-2 border-b border-white/[0.06] bg-black/40">
                  <span className="text-[10px] font-mono text-white/40">Email Preferences</span>
                </div>
                <div className="p-4 space-y-2">
                  {[
                    { key: 'domain_availability', label: 'Domain Available', desc: 'When domains become available' },
                    { key: 'price_alerts', label: 'Price Changes', desc: 'TLD price updates' },
                    { key: 'weekly_digest', label: 'Weekly Digest', desc: 'Weekly summary' },
                  ].map((item) => (
                    <label key={item.key} className="flex items-center justify-between p-3 bg-white/[0.02] border border-white/[0.06] cursor-pointer hover:border-white/[0.12]">
                      <div>
                        <p className="text-sm text-white">{item.label}</p>
                        <p className="text-[10px] text-white/40">{item.desc}</p>
                      </div>
                      <input 
                        type="checkbox" 
                        checked={notificationPrefs[item.key as keyof typeof notificationPrefs]}
                        onChange={(e) => setNotificationPrefs({ ...notificationPrefs, [item.key]: e.target.checked })}
                        className="w-4 h-4 accent-accent"
                      />
                    </label>
                  ))}
                  <button
                    onClick={handleSaveNotifications}
                    disabled={savingNotifications}
                    className="mt-3 flex items-center gap-2 px-5 py-2.5 bg-accent text-black text-xs font-bold uppercase tracking-wider hover:bg-white disabled:opacity-50"
                  >
                    {savingNotifications ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
                    Save
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Billing Tab */}
          {activeTab === 'billing' && (
            <div className="space-y-4">
              {/* Plan Cards */}
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
                {PLANS.map((plan) => {
                  const isCurrent = tierName.toLowerCase() === plan.id
                  const isUpgrade = (tierName === 'Scout' && plan.id !== 'scout') || (tierName === 'Trader' && plan.id === 'tycoon')
                  const isDowngrade = (tierName === 'Tycoon' && plan.id !== 'tycoon') || (tierName === 'Trader' && plan.id === 'scout')
                  
                  return (
                    <div
                      key={plan.id}
                      className={clsx(
                        "relative p-4 border transition-all",
                        isCurrent ? "border-accent bg-accent/5" : "border-white/[0.08] bg-[#0A0A0A]"
                      )}
                    >
                      {plan.badge && (
                        <div className={clsx(
                          "absolute -top-2 left-3 px-2 py-0.5 text-[9px] font-mono uppercase",
                          plan.id === 'trader' ? "bg-accent text-black" : "bg-amber-500 text-black"
                        )}>{plan.badge}</div>
                      )}
                      {isCurrent && (
                        <div className="absolute -top-2 right-3 px-2 py-0.5 text-[9px] font-mono uppercase bg-white text-black">Current</div>
                      )}
                      
                      <div className="flex items-center gap-2 mb-3 mt-1">
                        <plan.icon className={clsx(
                          "w-5 h-5",
                          plan.id === 'tycoon' ? "text-amber-400" : plan.id === 'trader' ? "text-accent" : "text-white/50"
                        )} />
                        <span className="text-lg font-display text-white">{plan.name}</span>
                      </div>
                      
                      <div className="flex items-baseline gap-1 mb-3">
                        {plan.price === 0 ? (
                          <span className="text-2xl font-mono text-white">Free</span>
                        ) : (
                          <>
                            <span className="text-2xl font-mono text-white">${plan.price}</span>
                            <span className="text-xs text-white/40">{plan.period}</span>
                          </>
                        )}
                      </div>
                      
                      <ul className="space-y-1.5 mb-4">
                        {plan.features.slice(0, 4).map((f, i) => (
                          <li key={i} className="flex items-center gap-2 text-[11px] text-white/60">
                            <f.icon className="w-3 h-3 text-accent shrink-0" />
                            {f.text}
                          </li>
                        ))}
                      </ul>
                      
                      {isCurrent ? (
                        <div className="w-full py-2 text-center text-[10px] font-mono text-accent border border-accent/30 bg-accent/5">
                          <Check className="w-3 h-3 inline mr-1" /> Active
                        </div>
                      ) : isUpgrade ? (
                        <button
                          onClick={() => handlePlanChange(plan.id)}
                          disabled={changingPlan === plan.id}
                          className="w-full py-2 bg-accent text-black text-[10px] font-bold uppercase tracking-wider hover:bg-white disabled:opacity-50 flex items-center justify-center gap-1"
                        >
                          {changingPlan === plan.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <ArrowUp className="w-3 h-3" />}
                          Upgrade
                        </button>
                      ) : isDowngrade ? (
                        <button
                          onClick={() => handlePlanChange(plan.id)}
                          disabled={changingPlan === plan.id}
                          className="w-full py-2 text-white/40 text-[10px] font-mono border border-white/[0.08] hover:border-white/20 hover:text-white disabled:opacity-50 flex items-center justify-center gap-1"
                        >
                          {changingPlan === plan.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <ArrowDown className="w-3 h-3" />}
                          Downgrade
                        </button>
                      ) : null}
                    </div>
                  )
                })}
              </div>
              
              {/* Billing Portal Link */}
              {isProOrHigher && (
                <button
                  onClick={handleOpenBillingPortal}
                  className="w-full p-3 bg-white/[0.02] border border-white/[0.08] flex items-center justify-center gap-2 text-xs font-mono text-white/60 hover:text-white hover:border-white/20"
                >
                  <ExternalLink className="w-4 h-4" />
                  Manage Billing & Invoices
                </button>
              )}

              {/* Simple Cancel Section - Only for paid users */}
              {isProOrHigher && (
                <div className="bg-[#0A0A0A] border border-white/[0.08] mt-6">
                  <div className="px-4 py-2 border-b border-white/[0.06] bg-black/40">
                    <span className="text-[10px] font-mono text-white/40">Cancel Subscription</span>
                  </div>
                  <div className="p-4 lg:p-6">
                    <p className="text-sm text-white/60 mb-4">
                      Not what you need right now? No problem. Cancel anytime — no hidden fees, no questions asked.
                    </p>
                    <div className="space-y-2 mb-4">
                      <div className="flex items-center gap-2 text-xs text-white/40">
                        <Check className="w-3.5 h-3.5 text-accent" />
                        You won't be charged again
                      </div>
                      <div className="flex items-center gap-2 text-xs text-white/40">
                        <Check className="w-3.5 h-3.5 text-accent" />
                        Keep access until current period ends
                      </div>
                      <div className="flex items-center gap-2 text-xs text-white/40">
                        <Check className="w-3.5 h-3.5 text-accent" />
                        Switch back to Scout (free forever)
                      </div>
                      <div className="flex items-center gap-2 text-xs text-white/40">
                        <Check className="w-3.5 h-3.5 text-accent" />
                        Re-subscribe anytime if you change your mind
                      </div>
                    </div>
                    <button
                      onClick={() => setShowCancelModal(true)}
                      className="px-4 py-2.5 border border-white/10 text-white/60 text-xs font-mono hover:border-white/20 hover:text-white transition-colors"
                    >
                      Cancel my subscription
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Security Tab */}
          {activeTab === 'security' && (
            <div className="space-y-4">
              <div className="bg-[#0A0A0A] border border-white/[0.08]">
                <div className="px-4 py-2 border-b border-white/[0.06] bg-black/40">
                  <span className="text-[10px] font-mono text-white/40">Password</span>
                </div>
                <div className="p-4">
                  <p className="text-xs text-white/40 mb-4">Change or reset your password</p>
                  <Link
                    href="/forgot-password"
                    className="inline-flex items-center gap-2 px-4 py-2.5 bg-white/[0.02] border border-white/[0.08] text-white text-xs font-mono hover:border-white/20"
                  >
                    <Key className="w-4 h-4" />
                    Change Password
                  </Link>
                </div>
              </div>
              
              <div className="bg-[#0A0A0A] border border-white/[0.08]">
                <div className="px-4 py-2 border-b border-white/[0.06] bg-black/40">
                  <span className="text-[10px] font-mono text-white/40">Account Status</span>
                </div>
                <div className="p-4 space-y-2">
                  <div className="flex items-center justify-between p-3 bg-white/[0.02] border border-white/[0.06]">
                    <div>
                      <p className="text-sm text-white">Email Verified</p>
                      <p className="text-[10px] text-white/40">Your email is verified</p>
                    </div>
                    <Check className="w-4 h-4 text-accent" />
                  </div>
                  <div className="flex items-center justify-between p-3 bg-white/[0.02] border border-white/[0.06]">
                    <div>
                      <p className="text-sm text-white">2FA</p>
                      <p className="text-[10px] text-white/40">Coming soon</p>
                    </div>
                    <span className="text-[9px] px-2 py-0.5 bg-white/5 text-white/40 font-mono">Soon</span>
                  </div>
                </div>
              </div>
              
              <div className="bg-red-500/5 border border-red-500/20 p-4">
                <p className="text-xs font-mono text-red-400 mb-2">Danger Zone</p>
                <p className="text-[10px] text-white/40 mb-4">Permanently delete your account</p>
                <button className="px-4 py-2 bg-red-500 text-white text-xs font-bold hover:bg-red-400">
                  Delete Account
                </button>
              </div>
            </div>
          )}
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE BOTTOM NAV */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <nav 
          className="lg:hidden fixed bottom-0 left-0 right-0 z-50 bg-[#020202] border-t border-white/[0.08]"
          style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
        >
          <div className="flex items-stretch h-14">
            {mobileNavItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={clsx(
                  "flex-1 flex flex-col items-center justify-center gap-0.5 relative transition-colors",
                  item.active ? "text-accent" : "text-white/40 active:text-white/80"
                )}
              >
                {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 active:text-white/80 transition-all"
            >
              <Menu className="w-5 h-5" />
              <span className="text-[9px] font-mono uppercase tracking-wider">Menu</span>
            </button>
          </div>
        </nav>
        
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* CANCEL SUBSCRIPTION MODAL */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {showCancelModal && (
          <div className="fixed inset-0 z-[110] bg-black/80 flex items-center justify-center p-4" onClick={() => !cancelling && setShowCancelModal(false)}>
            <div 
              className="w-full max-w-md bg-[#0A0A0A] border border-white/[0.08]"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="p-6 text-center">
                <div className="w-12 h-12 mx-auto mb-4 border border-white/10 flex items-center justify-center">
                  <Zap className="w-6 h-6 text-white/30" />
                </div>
                <h3 className="text-lg font-display text-white mb-2">Cancel Subscription?</h3>
                <p className="text-sm text-white/50 mb-6">
                  You'll be moved to the free Scout plan. You can re-subscribe anytime.
                </p>
                
                <div className="space-y-2 text-left mb-6 p-4 bg-white/[0.02] border border-white/[0.06]">
                  <p className="text-[10px] font-mono text-white/40 uppercase tracking-wider mb-2">What happens next:</p>
                  <div className="flex items-start gap-2 text-xs text-white/60">
                    <Check className="w-3.5 h-3.5 text-accent shrink-0 mt-0.5" />
                    <span>Your subscription ends immediately</span>
                  </div>
                  <div className="flex items-start gap-2 text-xs text-white/60">
                    <Check className="w-3.5 h-3.5 text-accent shrink-0 mt-0.5" />
                    <span>No more charges — guaranteed</span>
                  </div>
                  <div className="flex items-start gap-2 text-xs text-white/60">
                    <Check className="w-3.5 h-3.5 text-accent shrink-0 mt-0.5" />
                    <span>Your data stays safe — nothing is deleted</span>
                  </div>
                  <div className="flex items-start gap-2 text-xs text-white/60">
                    <Check className="w-3.5 h-3.5 text-accent shrink-0 mt-0.5" />
                    <span>Come back anytime to upgrade again</span>
                  </div>
                </div>

                <div className="flex gap-3">
                  <button
                    onClick={() => setShowCancelModal(false)}
                    disabled={cancelling}
                    className="flex-1 py-3 border border-white/10 text-white text-xs font-bold uppercase tracking-wider hover:bg-white/5 disabled:opacity-50"
                  >
                    Keep Plan
                  </button>
                  <button
                    onClick={handleCancelSubscription}
                    disabled={cancelling}
                    className="flex-1 py-3 bg-white/10 text-white/60 text-xs font-mono hover:bg-white/20 hover:text-white disabled:opacity-50 flex items-center justify-center gap-2"
                  >
                    {cancelling ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      'Yes, cancel'
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE DRAWER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {menuOpen && (
          <div className="lg:hidden fixed inset-0 z-[100]">
            <div 
              className="absolute inset-0 bg-black/80 animate-in fade-in duration-200"
              onClick={() => setMenuOpen(false)}
            />
            
            <div 
              className="absolute top-0 right-0 bottom-0 w-[80%] max-w-[300px] bg-[#0A0A0A] border-l border-white/[0.08] animate-in slide-in-from-right duration-300 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>
                    <p className="text-sm font-bold text-white">Pounce</p>
                    <p className="text-[9px] text-white/40 font-mono uppercase tracking-widest">Terminal v1.0</p>
                  </div>
                </div>
                <button
                  onClick={() => setMenuOpen(false)}
                  className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/60 hover:text-white active:bg-white/5 transition-all"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>
              
              <div className="flex-1 overflow-y-auto py-4">
                {drawerNavSections.map((section) => (
                  <div key={section.title} className="mb-4">
                    <div className="flex items-center gap-2 px-4 mb-2">
                      <div className="w-1 h-3 bg-accent" />
                      <span className="text-[9px] font-bold text-white/30 uppercase tracking-[0.2em]">{section.title}</span>
                    </div>
                    <div>
                      {section.items.map((item: any) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={() => setMenuOpen(false)}
                          className="flex items-center gap-3 px-4 py-2.5 text-white/60 active:text-white active:bg-white/[0.03] transition-colors border-l-2 border-transparent active:border-accent"
                        >
                          <item.icon className="w-4 h-4 text-white/30" />
                          <span className="text-sm font-medium flex-1">{item.label}</span>
                          {item.isNew && (
                            <span className="px-1.5 py-0.5 text-[8px] font-bold bg-accent text-black">NEW</span>
                          )}
                        </Link>
                      ))}
                    </div>
                  </div>
                ))}
                
                <div className="pt-3 border-t border-white/[0.08] mx-4">
                  <Link
                    href="/terminal/settings"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center gap-3 py-2.5 text-accent transition-colors"
                  >
                    <Settings className="w-4 h-4" />
                    <span className="text-sm font-medium">Settings</span>
                  </Link>
                  
                  {user?.is_admin && (
                    <Link
                      href="/admin"
                      onClick={() => setMenuOpen(false)}
                      className="flex items-center gap-3 py-2.5 text-amber-500/70 active:text-amber-400 transition-colors"
                    >
                      <Shield className="w-4 h-4" />
                      <span className="text-sm font-medium">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 tracking-wider">{tierName}</p>
                  </div>
                </div>
                
                {tierName === 'Scout' && (
                  <Link 
                    href="/pricing"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center justify-center gap-2 w-full py-2.5 bg-accent text-black text-xs font-bold uppercase tracking-wider active:scale-[0.98] transition-all mb-2"
                  >
                    <Sparkles className="w-3 h-3" />
                    Upgrade
                  </Link>
                )}
                
                <button
                  onClick={() => { logout(); setMenuOpen(false) }}
                  className="flex items-center justify-center gap-2 w-full py-2 border border-white/10 text-white/40 text-[10px] font-mono uppercase tracking-wider active:bg-white/5 transition-all"
                >
                  <LogOut className="w-3 h-3" />
                  Sign out
                </button>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  )
}
