import { useState, useEffect } from 'react'
import { useNavigate, Link, useSearchParams } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { OnboardingProgress } from '@/components/OnboardingProgress'
import { api } from '@/lib/api'
import { trackOnboardingStep, trackProviderConnected, trackDemoUsed } from '@/lib/analytics'
import { 
  Mail, 
  ArrowRight, 
  ArrowLeft, 
  Check, 
  Sparkles,
  ChevronRight,
  Link2,
  Settings,
  Zap,
  Loader2,
  AlertCircle
} from 'lucide-react'

type Step = 'connect' | 'preferences' | 'categories' | 'complete'

export function Setup() {
  const [searchParams] = useSearchParams()
  const isFromCheckout = searchParams.get('subscription') === 'success'
  
  const [currentStep, setCurrentStep] = useState<Step>('connect')
  const [connectedProvider, setConnectedProvider] = useState<string | null>(null)
  const [connectedEmail, setConnectedEmail] = useState<string | null>(null)
  const [connecting, setConnecting] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [preferences, setPreferences] = useState({
    sortingStrictness: 'medium',
    historicalSync: true,
  })
  const [selectedCategories, setSelectedCategories] = useState<string[]>([
    'vip', 'customers', 'invoices', 'newsletters', 'social'
  ])
  const [saving, setSaving] = useState(false)
  const [checkingAccounts, setCheckingAccounts] = useState(isFromCheckout)
  const [onboardingState, setOnboardingState] = useState<{
    onboarding_step: string
    completedSteps: string[]
  } | null>(null)
  const [loadingOnboarding, setLoadingOnboarding] = useState(true)
  
  const { user } = useAuth()
  const navigate = useNavigate()
  const resumeOnboarding = searchParams.get('resume') === 'true'

  // Load onboarding state
  useEffect(() => {
    if (user?.$id) {
      const loadOnboarding = async () => {
        try {
          const stateRes = await api.getOnboardingStatus()
          if (stateRes.data) {
            setOnboardingState(stateRes.data)
            
            // If resuming, restore step
            if (resumeOnboarding && stateRes.data.onboarding_step !== 'completed' && stateRes.data.onboarding_step !== 'not_started') {
              const stepMap: Record<string, Step> = {
                'connect': 'connect',
                'first_rule': 'preferences',
                'see_results': 'categories',
                'auto_schedule': 'complete',
              }
              const mappedStep = stepMap[stateRes.data.onboarding_step]
              if (mappedStep) {
                setCurrentStep(mappedStep)
              }
            }
          }
        } catch (err) {
          console.error('Error loading onboarding state:', err)
        } finally {
          setLoadingOnboarding(false)
        }
      }
      loadOnboarding()
    }
  }, [user, resumeOnboarding])

  // Check if user already has connected accounts after successful checkout
  useEffect(() => {
    if (isFromCheckout && user?.$id) {
      const checkAccounts = async () => {
        try {
          const accountsRes = await api.getEmailAccounts()
          if (accountsRes.data && accountsRes.data.length > 0) {
            // User already has accounts connected - redirect to dashboard
            navigate('/dashboard?subscription=success&ready=true')
          } else {
            setCheckingAccounts(false)
          }
        } catch (err) {
          console.error('Error checking accounts:', err)
          setCheckingAccounts(false)
        }
      }
      checkAccounts()
    }
  }, [isFromCheckout, user, navigate])

  const steps: { id: Step; title: string; description: string }[] = [
    { id: 'connect', title: 'Connect email', description: 'Link your mailbox' },
    { id: 'complete', title: 'Done', description: 'Go to dashboard' },
  ]

  const stepIndex = steps.findIndex(s => s.id === currentStep)

  const handleConnectGmail = async () => {
    if (!user?.$id) return
    setConnecting('gmail')
    setError(null)
    
    try {
      const response = await api.getOAuthUrl('gmail')
      if (response.data?.url) {
        // Track onboarding step before redirect
        await api.updateOnboardingStep('connect', ['connect'])
        window.location.href = response.data.url
      } else {
        setConnectedProvider('gmail')
        setConnectedEmail(user.email)
        setCurrentStep('complete')
        await api.updateOnboardingStep('see_results', ['connect'])
        trackOnboardingStep(user.$id, 'first_rule')
        trackProviderConnected(user.$id, 'gmail')
      }
    } catch {
      setError('Gmail connection failed. Please try again.')
    } finally {
      setConnecting(null)
    }
  }

  const handleConnectOutlook = async () => {
    if (!user?.$id) return
    setConnecting('outlook')
    setError(null)
    
    try {
      const response = await api.getOAuthUrl('outlook')
      if (response.data?.url) {
        // Track onboarding step before redirect
        await api.updateOnboardingStep('connect', ['connect'])
        window.location.href = response.data.url
      } else {
        setConnectedProvider('outlook')
        setConnectedEmail(user.email)
        setCurrentStep('complete')
        await api.updateOnboardingStep('see_results', ['connect'])
      }
    } catch {
      setError('Outlook connection failed. Please try again.')
    } finally {
      setConnecting(null)
    }
  }

  const handleConnectDemo = async () => {
    if (!user?.$id) return
    setConnecting('demo')
    setError(null)
    
    try {
      const response = await api.connectDemoAccount()
      if (response.data) {
        setConnectedProvider('demo')
        setConnectedEmail(response.data.email)
        setCurrentStep('complete')
        await api.updateOnboardingStep('see_results', ['connect'])
        trackOnboardingStep(user.$id, 'first_rule')
        trackDemoUsed(user.$id)
      }
    } catch {
      setError('Demo connection failed. Please try again.')
    } finally {
      setConnecting(null)
    }
  }

  const handleNext = async () => {
    const nextIndex = stepIndex + 1
    if (nextIndex < steps.length) {
      const nextStep = steps[nextIndex].id
      setCurrentStep(nextStep)
      
      // Track onboarding progress
      if (user?.$id) {
        const stepMap: Record<Step, string> = {
          'connect': 'connect',
          'preferences': 'first_rule',
          'categories': 'see_results',
          'complete': 'auto_schedule',
        }
        const onboardingStep = stepMap[nextStep]
        const completedSteps = onboardingState?.completedSteps || []
        if (onboardingStep && !completedSteps.includes(stepMap[currentStep])) {
          const newCompleted = [...completedSteps, stepMap[currentStep]]
          await api.updateOnboardingStep(onboardingStep, newCompleted)
          setOnboardingState({
            onboarding_step: onboardingStep,
            completedSteps: newCompleted,
          })
        }
      }
    }
  }

  const handleBack = () => {
    const prevIndex = stepIndex - 1
    if (prevIndex >= 0) {
      setCurrentStep(steps[prevIndex].id)
    }
  }

  const handleComplete = async () => {
    if (!user?.$id) {
      navigate('/dashboard')
      return
    }

    setSaving(true)
    try {
      await api.saveUserPreferences({
        vipSenders: [],
        blockedSenders: [],
        customRules: [],
        priorityTopics: selectedCategories,
      })
      
      // Mark onboarding as completed
      await api.updateOnboardingStep('completed', ['connect', 'see_results'])
    } catch (err) {
      console.error('Failed to save preferences:', err)
    } finally {
      setSaving(false)
      navigate('/dashboard')
    }
  }

  const handleSkipOnboarding = async () => {
    if (!user?.$id) return
    
    try {
      await api.skipOnboarding()
      navigate('/dashboard')
    } catch (err) {
      console.error('Failed to skip onboarding:', err)
      navigate('/dashboard')
    }
  }

  const categories = [
    { id: 'vip', name: 'Important / VIP', description: 'Priority contacts', icon: '⭐', color: 'bg-amber-500' },
    { id: 'customers', name: 'Clients / Projects', description: 'Business correspondence', icon: '💼', color: 'bg-blue-500' },
    { id: 'invoices', name: 'Invoices / Receipts', description: 'Financial documents', icon: '📄', color: 'bg-green-500' },
    { id: 'newsletters', name: 'Newsletter', description: 'Subscribed newsletters', icon: '📰', color: 'bg-purple-500' },
    { id: 'social', name: 'Social / Platforms', description: 'LinkedIn, Twitter, etc.', icon: '👥', color: 'bg-pink-500' },
    { id: 'security', name: 'Security / 2FA', description: 'Security codes', icon: '🔐', color: 'bg-red-500' },
    { id: 'calendar', name: 'Calendar / Events', description: 'Appointments & invites', icon: '📅', color: 'bg-indigo-500' },
    { id: 'promotions', name: 'Promotions / Deals', description: 'Marketing emails', icon: '🏷️', color: 'bg-orange-500' },
  ]

  const toggleCategory = (id: string) => {
    setSelectedCategories(prev =>
      prev.includes(id)
        ? prev.filter(c => c !== id)
        : [...prev, id]
    )
  }

  // Show loading while checking accounts
  if (checkingAccounts) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white dark:from-slate-900 dark:to-slate-800 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin text-primary-600 dark:text-primary-400 mx-auto mb-4" />
          <p className="text-slate-600 dark:text-slate-400">Setting up your account...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white dark:from-slate-900 dark:to-slate-800">
      <header className="bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm border-b border-slate-200 dark:border-slate-700 sticky top-0 z-40">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            <Link to="/" className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center shadow-lg shadow-primary-500/20">
                <Mail className="w-5 h-5 text-white" />
              </div>
              <span className="text-lg font-bold text-slate-900 dark:text-slate-100">
                E-Mail-<span className="text-primary-600 dark:text-primary-400">Sorter</span>
              </span>
            </Link>
            <Button variant="ghost" onClick={handleSkipOnboarding}>
              Skip
            </Button>
          </div>
        </div>
      </header>

      {/* Success message after checkout */}
      {isFromCheckout && (
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pt-8">
          <div className="bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded-xl p-6 mb-6 flex items-start gap-4">
            <div className="w-10 h-10 rounded-full bg-green-500 dark:bg-green-600 flex items-center justify-center flex-shrink-0">
              <Check className="w-6 h-6 text-white" />
            </div>
            <div className="flex-1">
              <h3 className="font-semibold text-green-900 dark:text-green-200 mb-1">Payment successful!</h3>
              <p className="text-sm text-green-700 dark:text-green-300">
                Your subscription is active. Let's connect your email account to get started.
              </p>
            </div>
          </div>
        </div>
      )}

      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Onboarding Progress */}
        {!loadingOnboarding && onboardingState && onboardingState.onboarding_step !== 'completed' && (
          <div className="mb-6">
            <OnboardingProgress
              currentStep={onboardingState.onboarding_step}
              completedSteps={onboardingState.completedSteps}
              totalSteps={2}
              onSkip={handleSkipOnboarding}
            />
          </div>
        )}

        {/* Progress */}
        <div className="mb-12">
          <div className="flex items-center justify-between mb-4">
            {steps.map((step, index) => (
              <div key={step.id} className="flex items-center">
                <div className="flex flex-col items-center">
                  <div 
                    className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all duration-300 ${
                      index < stepIndex 
                        ? 'bg-green-500 dark:bg-green-600 text-white shadow-lg shadow-green-500/30' 
                        : index === stepIndex 
                          ? 'bg-primary-500 dark:bg-primary-600 text-white ring-4 ring-primary-100 dark:ring-primary-900/50 shadow-lg shadow-primary-500/30'
                          : 'bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500'
                    }`}
                  >
                    {index < stepIndex ? <Check className="w-5 h-5" /> : index + 1}
                  </div>
                  <p className={`mt-2 text-xs font-medium hidden sm:block transition-colors ${
                    index <= stepIndex ? 'text-slate-900 dark:text-slate-100' : 'text-slate-400 dark:text-slate-500'
                  }`}>
                    {step.title}
                  </p>
                </div>
                {index < steps.length - 1 && (
                  <div className={`w-16 sm:w-24 h-1 mx-2 rounded-full transition-colors duration-500 ${
                    index < stepIndex ? 'bg-green-500 dark:bg-green-600' : 'bg-slate-200 dark:bg-slate-700'
                  }`} />
                )}
              </div>
            ))}
          </div>
        </div>

        {error && (
          <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-xl flex items-center gap-3 text-red-700 dark:text-red-300">
            <AlertCircle className="w-5 h-5 flex-shrink-0" />
            <p>{error}</p>
          </div>
        )}

        <div className="mb-8">
          {currentStep === 'connect' && (
            <div className="text-center">
              <div className="w-24 h-24 mx-auto mb-6 rounded-2xl bg-gradient-to-br from-primary-100 to-primary-200 flex items-center justify-center shadow-xl shadow-primary-500/10">
                <Link2 className="w-12 h-12 text-primary-600" />
              </div>
              <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 mb-3">Connect your email account</h1>
              <p className="text-lg text-slate-600 dark:text-slate-400 mb-10 max-w-md mx-auto">
                Choose your email provider. The connection is secure and your data stays private.
              </p>

              <div className="space-y-4 max-w-lg mx-auto">
                {/* Try Demo - Prominent Option */}
                <button
                  onClick={handleConnectDemo}
                  disabled={connecting !== null}
                  className="w-full flex items-center gap-4 p-6 bg-gradient-to-r from-primary-500 to-primary-600 text-white rounded-2xl border-2 border-primary-400 hover:border-primary-300 hover:shadow-2xl hover:shadow-primary-500/30 transition-all text-left group disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {connecting === 'demo' ? (
                    <Loader2 className="w-12 h-12 animate-spin text-white" />
                  ) : (
                    <div className="w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center group-hover:bg-white/30 transition-colors">
                      <Sparkles className="w-7 h-7 text-white" />
                    </div>
                  )}
                  <div className="flex-1">
                    <p className="font-semibold text-white text-lg">Try Demo</p>
                    <p className="text-sm text-primary-100">See how it works without connecting your account</p>
                  </div>
                  <ChevronRight className="w-5 h-5 text-white/80 group-hover:text-white group-hover:translate-x-1 transition-all" />
                </button>

                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <div className="w-full border-t border-slate-300 dark:border-slate-600"></div>
                  </div>
                  <div className="relative flex justify-center text-sm">
                    <span className="px-4 bg-white dark:bg-slate-800 text-slate-500 dark:text-slate-400">Or connect your inbox</span>
                  </div>
                </div>

                <div className="grid sm:grid-cols-2 gap-4">
                  <button
                    onClick={handleConnectGmail}
                    disabled={connecting !== null}
                    className="flex items-center gap-4 p-6 bg-white dark:bg-slate-800 rounded-2xl border-2 border-slate-200 dark:border-slate-700 hover:border-red-300 dark:hover:border-red-600 hover:shadow-xl hover:shadow-red-500/10 transition-all text-left group disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {connecting === 'gmail' ? (
                      <Loader2 className="w-12 h-12 animate-spin text-red-500 dark:text-red-400" />
                    ) : (
                      <div className="w-12 h-12 rounded-xl bg-red-50 dark:bg-red-900/30 flex items-center justify-center group-hover:bg-red-100 dark:group-hover:bg-red-900/50 transition-colors">
                        <svg viewBox="0 0 24 24" className="w-7 h-7">
                          <path fill="#EA4335" d="M5.26 9.71L12 14.04l6.74-4.33-6.74-4.33z"/>
                          <path fill="#34A853" d="M12 14.04l6.74-4.33v7.65c0 .7-.57 1.26-1.26 1.26H6.52c-.7 0-1.26-.57-1.26-1.26V9.71l6.74 4.33z"/>
                          <path fill="#4285F4" d="M18.74 5.38H5.26c-.7 0-1.26.57-1.26 1.26v3.07l8 5.13 8-5.13V6.64c0-.7-.57-1.26-1.26-1.26z"/>
                          <path fill="#FBBC05" d="M4 9.71V6.64c0-.7.57-1.26 1.26-1.26h.01L12 9.71 4 13.84V9.71z"/>
                        </svg>
                      </div>
                    )}
                    <div className="flex-1">
                      <p className="font-semibold text-slate-900 dark:text-slate-100">Gmail</p>
                      <p className="text-sm text-slate-500 dark:text-slate-400">Google Workspace</p>
                    </div>
                    <ChevronRight className="w-5 h-5 text-slate-400 dark:text-slate-500 group-hover:text-red-500 dark:group-hover:text-red-400 group-hover:translate-x-1 transition-all" />
                  </button>

                  <button
                    onClick={handleConnectOutlook}
                    disabled={connecting !== null}
                    className="flex items-center gap-4 p-6 bg-white dark:bg-slate-800 rounded-2xl border-2 border-slate-200 dark:border-slate-700 hover:border-blue-300 dark:hover:border-blue-600 hover:shadow-xl hover:shadow-blue-500/10 transition-all text-left group disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {connecting === 'outlook' ? (
                      <Loader2 className="w-12 h-12 animate-spin text-blue-500 dark:text-blue-400" />
                    ) : (
                      <div className="w-12 h-12 rounded-xl bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center group-hover:bg-blue-100 dark:group-hover:bg-blue-900/50 transition-colors">
                        <svg viewBox="0 0 24 24" className="w-7 h-7">
                          <path fill="#0078D4" d="M11.5 3v8.5H3V3h8.5zm1 0H21v8.5h-8.5V3zM3 12.5h8.5V21H3v-8.5zm9.5 0H21V21h-8.5v-8.5z"/>
                        </svg>
                      </div>
                    )}
                    <div className="flex-1">
                      <p className="font-semibold text-slate-900 dark:text-slate-100">Outlook</p>
                      <p className="text-sm text-slate-500 dark:text-slate-400">Microsoft 365</p>
                    </div>
                    <ChevronRight className="w-5 h-5 text-slate-400 dark:text-slate-500 group-hover:text-blue-500 dark:group-hover:text-blue-400 group-hover:translate-x-1 transition-all" />
                  </button>
                </div>

                <p className="text-sm text-slate-500 dark:text-slate-400 mt-4">
                  Using Porkbun, Nextcloud Mail, or another IMAP provider?{' '}
                  <Link to="/settings?tab=accounts" className="text-primary-600 dark:text-primary-400 hover:underline">Add your account in Settings → Accounts</Link>.
                </p>
              </div>

              <div className="mt-10 p-4 bg-slate-50 dark:bg-slate-800/50 rounded-xl max-w-lg mx-auto">
                <p className="text-sm text-slate-500 dark:text-slate-400">
                  🔒 Your data is secure. We don't store email content and only have read access.
                </p>
              </div>
            </div>
          )}

          {currentStep === 'preferences' && (
            <div>
              <div className="text-center mb-10">
                <div className="w-24 h-24 mx-auto mb-6 rounded-2xl bg-gradient-to-br from-primary-100 to-primary-200 flex items-center justify-center shadow-xl shadow-primary-500/10">
                  <Settings className="w-12 h-12 text-primary-600" />
                </div>
                <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 mb-3">Sorting Settings</h1>
                <p className="text-lg text-slate-600 dark:text-slate-400 max-w-md mx-auto">
                  Customize how strictly the AI should sort your emails.
                </p>
              </div>

              <Card className="max-w-lg mx-auto shadow-xl border-0 dark:bg-slate-800 dark:border-slate-700">
                <CardContent className="p-8 space-y-8">
                  <div>
                    <label className="block text-sm font-semibold text-slate-900 dark:text-slate-100 mb-4">Sorting Intensity</label>
                    <div className="grid grid-cols-3 gap-3">
                      {[
                        { id: 'light', name: 'Light', desc: 'Only obvious distractions', emoji: '🌱' },
                        { id: 'medium', name: 'Medium', desc: 'Balanced sorting', emoji: '⚖️' },
                        { id: 'strict', name: 'Strict', desc: 'Inbox nearly empty', emoji: '🎯' },
                      ].map((option) => (
                        <button
                          key={option.id}
                          onClick={() => setPreferences(p => ({ ...p, sortingStrictness: option.id }))}
                          className={`p-4 rounded-xl border-2 text-center transition-all ${
                            preferences.sortingStrictness === option.id
                              ? 'border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/30 shadow-lg shadow-primary-500/10'
                              : 'border-slate-200 dark:border-slate-700 hover:border-slate-300 dark:hover:border-slate-600 bg-white dark:bg-slate-800'
                          }`}
                        >
                          <span className="text-2xl mb-2 block">{option.emoji}</span>
                          <p className="font-semibold text-slate-900 dark:text-slate-100">{option.name}</p>
                          <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">{option.desc}</p>
                        </button>
                      ))}
                    </div>
                  </div>

                  <div className="flex items-center justify-between p-5 bg-gradient-to-r from-slate-50 to-slate-100 dark:from-slate-800 dark:to-slate-700 rounded-xl">
                    <div>
                      <p className="font-semibold text-slate-900 dark:text-slate-100">Historical emails</p>
                      <p className="text-sm text-slate-500 dark:text-slate-400">Analyze and sort last 30 days</p>
                    </div>
                    <button
                      onClick={() => setPreferences(p => ({ ...p, historicalSync: !p.historicalSync }))}
                      className={`w-14 h-8 rounded-full transition-all duration-300 ${
                        preferences.historicalSync ? 'bg-primary-500 dark:bg-primary-600 shadow-lg shadow-primary-500/30' : 'bg-slate-300 dark:bg-slate-600'
                      }`}
                    >
                      <div className={`w-6 h-6 bg-white dark:bg-slate-200 rounded-full shadow-md transition-transform duration-300 ${
                        preferences.historicalSync ? 'translate-x-7' : 'translate-x-1'
                      }`} />
                    </button>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {currentStep === 'categories' && (
            <div>
              <div className="text-center mb-10">
                <div className="w-24 h-24 mx-auto mb-6 rounded-2xl bg-gradient-to-br from-primary-100 to-primary-200 flex items-center justify-center shadow-xl shadow-primary-500/10">
                  <Zap className="w-12 h-12 text-primary-600" />
                </div>
                <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 mb-3">Choose your categories</h1>
                <p className="text-lg text-slate-600 dark:text-slate-400 max-w-md mx-auto">
                  Which categories should your emails be sorted into?
                </p>
              </div>

              <div className="grid sm:grid-cols-2 gap-4 max-w-2xl mx-auto">
                {categories.map((category) => (
                  <button
                    key={category.id}
                    onClick={() => toggleCategory(category.id)}
                    className={`flex items-center gap-4 p-5 rounded-xl border-2 text-left transition-all ${
                      selectedCategories.includes(category.id)
                        ? 'border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/30 shadow-lg shadow-primary-500/10'
                        : 'border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:border-slate-300 dark:hover:border-slate-600 hover:shadow-md'
                    }`}
                  >
                    <div className={`w-12 h-12 rounded-xl ${category.color} flex items-center justify-center text-2xl shadow-lg`}>
                      {category.icon}
                    </div>
                    <div className="flex-1">
                      <p className="font-semibold text-slate-900 dark:text-slate-100">{category.name}</p>
                      <p className="text-sm text-slate-500 dark:text-slate-400">{category.description}</p>
                    </div>
                    <div className={`w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all ${
                      selectedCategories.includes(category.id)
                        ? 'border-primary-500 dark:border-primary-400 bg-primary-500 dark:bg-primary-600'
                        : 'border-slate-300 dark:border-slate-600'
                    }`}>
                      {selectedCategories.includes(category.id) && <Check className="w-4 h-4 text-white" />}
                    </div>
                  </button>
                ))}
              </div>

              <p className="text-center text-sm text-slate-500 dark:text-slate-400 mt-6">
                You can change these categories later in settings.
              </p>
            </div>
          )}

          {currentStep === 'complete' && (
            <div className="text-center">
              <div className="w-28 h-28 mx-auto mb-8 rounded-full bg-gradient-to-br from-green-100 to-green-200 dark:from-green-900/40 dark:to-green-800/40 flex items-center justify-center shadow-2xl shadow-green-500/20 animate-pulse">
                <Sparkles className="w-14 h-14 text-green-600 dark:text-green-400" />
              </div>
              <h1 className="text-4xl font-bold text-slate-900 dark:text-slate-100 mb-4">You&apos;re in 🎉</h1>
              <p className="text-xl text-slate-600 dark:text-slate-400 mb-6 max-w-md mx-auto">
                Click Sort Now on the dashboard to categorize your inbox. Takes about 30 seconds.
              </p>
              <p className="text-sm text-slate-500 dark:text-slate-500 mb-10">
                <Link to="/settings" className="underline hover:text-slate-700 dark:hover:text-slate-300">Tune categories later in Settings</Link>
              </p>

              <div className="inline-flex items-center gap-4 p-5 bg-gradient-to-r from-slate-50 to-slate-100 dark:from-slate-800 dark:to-slate-700 rounded-2xl mb-10 shadow-lg">
                <div className="w-14 h-14 rounded-xl bg-white dark:bg-slate-700 flex items-center justify-center shadow-md">
                  <Mail className="w-7 h-7 text-primary-500 dark:text-primary-400" />
                </div>
                <div className="text-left">
                  <p className="font-semibold text-slate-900 dark:text-slate-100 text-lg">
                    {connectedProvider === 'gmail' ? 'Gmail' : connectedProvider === 'outlook' ? 'Outlook' : 'Email'} connected
                  </p>
                  <p className="text-slate-500 dark:text-slate-400">{connectedEmail || user?.email}</p>
                </div>
                <Badge variant="success" className="text-sm px-3 py-1">Active</Badge>
              </div>

              <Button size="lg" onClick={handleComplete} disabled={saving} className="text-lg px-8 py-6 shadow-xl shadow-primary-500/20">
                {saving ? (
                  <>
                    <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                    Saving...
                  </>
                ) : (
                  <>
                    Go to Dashboard
                    <ArrowRight className="w-5 h-5 ml-2" />
                  </>
                )}
              </Button>
            </div>
          )}
        </div>

        {currentStep !== 'connect' && currentStep !== 'complete' && (
          <div className="flex justify-between max-w-lg mx-auto">
            <Button variant="ghost" onClick={handleBack} className="text-slate-600 dark:text-slate-400">
              <ArrowLeft className="w-5 h-5 mr-2" />
              Back
            </Button>
            <Button onClick={handleNext} className="shadow-lg shadow-primary-500/20">
              Next
              <ArrowRight className="w-5 h-5 ml-2" />
            </Button>
          </div>
        )}
      </main>
    </div>
  )
}
