import { useState, useEffect } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { api } from '@/lib/api'
import { 
  Mail, 
  Inbox, 
  Tag, 
  Clock, 
  TrendingUp, 
  Plus, 
  Settings, 
  LogOut,
  Zap,
  BarChart3,
  Users,
  Shield,
  Loader2,
  Check,
  AlertCircle,
  Sparkles,
  AlertTriangle,
  Lightbulb,
  Archive,
  Brain,
  ExternalLink
} from 'lucide-react'
import { UpgradePrompt } from '@/components/UpgradePrompt'
import { ShareResults } from '@/components/ShareResults'
import { trackSortCompleted, trackLimitReached, trackRulesApplied } from '@/lib/analytics'

interface EmailStats {
  totalSorted: number
  todaySorted: number
  weekSorted: number
  categories: Record<string, number>
  timeSaved: number
}

interface EmailAccount {
  id: string
  email: string
  provider: string
  connected: boolean
  lastSync?: string
}

interface SortResult {
  sorted: number
  inboxCleared: number
  categories: Record<string, number>
  timeSaved: { minutes: number; formatted: string }
  highlights: Array<{ type: string; count: number; message: string }>
  suggestions: Array<{ type: string; message: string }>
  provider?: string
  isDemo?: boolean
  isFirstRun?: boolean
  suggestedRules?: Array<{
    type: string
    name: string
    description: string
    confidence: number
    action?: { name?: string; email?: string; condition?: string; category?: string }
  }>
}

interface Digest {
  date: string
  totalSorted: number
  inboxCleared: number
  timeSavedMinutes: number
  stats: Record<string, number>
  highlights: Array<{ type: string; count: number; message: string }>
  suggestions: Array<{ type: string; message: string }>
  hasData: boolean
}

export function Dashboard() {
  const { user, logout } = useAuth()
  const navigate = useNavigate()
  const [stats, setStats] = useState<EmailStats | null>(null)
  const [accounts, setAccounts] = useState<EmailAccount[]>([])
  const [digest, setDigest] = useState<Digest | null>(null)
  const [subscription, setSubscription] = useState<{
    plan: string
    planDisplayName?: string
    isFreeTier: boolean
    emailsUsedThisMonth?: number
    emailsLimit?: number
  } | null>(null)
  const [referralCode, setReferralCode] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [sorting, setSorting] = useState(false)
  const [sortResult, setSortResult] = useState<SortResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  const showMessage = (type: 'success' | 'error', text: string) => {
    setMessage({ type, text })
    setTimeout(() => setMessage(null), 5000)
  }

  useEffect(() => {
    if (user?.$id) {
      loadData()
    }
  }, [user?.$id])

  const loadData = async () => {
    if (!user?.$id) return
    setLoading(true)
    setError(null)
    
    try {
      const [statsRes, accountsRes, digestRes, subscriptionRes, referralRes] = await Promise.all([
        api.getEmailStats(),
        api.getEmailAccounts(),
        api.getDigest(),
        api.getSubscriptionStatus(),
        api.getReferralCode().catch(() => ({ data: null })),
      ])
      
      if (statsRes.data) setStats(statsRes.data)
      if (accountsRes.data) setAccounts(accountsRes.data)
      if (digestRes.data) setDigest(digestRes.data)
      if (subscriptionRes.data) setSubscription(subscriptionRes.data)
      if (referralRes.data) setReferralCode(referralRes.data.referralCode)
    } catch (err) {
      console.error('Error loading dashboard data:', err)
            setError('Couldn’t load your data. Check your connection and refresh.')
    } finally {
      setLoading(false)
    }
  }

  const handleSortNow = async () => {
    if (!user?.$id || accounts.length === 0) {
      setError('Connect your inbox first, then click Sort Now.')
      return
    }
    
    setSorting(true)
    setSortResult(null)
    setError(null)
    
      try {
        const result = await api.sortEmails(accounts[0].id)
        if (result.data) {
          setSortResult(result.data)
          
          // Track sort completed
          trackSortCompleted(user.$id, result.data.sorted, result.data.isFirstRun || false)
          
          // Refresh stats, digest, and subscription
          const [statsRes, digestRes, subscriptionRes] = await Promise.all([
            api.getEmailStats(),
            api.getDigest(),
            api.getSubscriptionStatus(),
          ])
          if (statsRes.data) setStats(statsRes.data)
          if (digestRes.data) setDigest(digestRes.data)
          if (subscriptionRes.data) setSubscription(subscriptionRes.data)
        } else if (result.error) {
          // Check if it's a limit reached error
          if (result.error.code === 'LIMIT_REACHED') {
            setError(result.error.message || 'Monthly limit reached')
            trackLimitReached(user.$id, result.error.limit || 500, result.error.used || 500)
            // Refresh subscription to show updated usage
            const subscriptionRes = await api.getSubscriptionStatus()
            if (subscriptionRes.data) setSubscription(subscriptionRes.data)
          } else {
            setError(result.error.message || 'Email sorting failed. Please try again or reconnect your account.')
          }
        }
    } catch (err) {
      console.error('Error sorting emails:', err)
            setError('Something went wrong. Check your connection and try again.')
    } finally {
        setSorting(false)
      }
  }

  const handleLogout = async () => {
    await logout()
    navigate('/')
  }

  const displayStats: EmailStats = stats || {
    totalSorted: 0,
    todaySorted: 0,
    weekSorted: 0,
    categories: {},
    timeSaved: 0,
  }

  const categoryColors: Record<string, string> = {
    'vip': 'bg-amber-500',
    'Important': 'bg-amber-500',
    'customers': 'bg-blue-500',
    'Clients': 'bg-blue-500',
    'invoices': 'bg-green-500',
    'Invoices': 'bg-green-500',
    'newsletters': 'bg-purple-500',
    'Newsletter': 'bg-purple-500',
    'social': 'bg-pink-500',
    'Social': 'bg-pink-500',
    'promotions': 'bg-orange-500',
    'Promotions': 'bg-orange-500',
    'security': 'bg-red-500',
    'Security': 'bg-red-500',
    'calendar': 'bg-indigo-500',
    'Calendar': 'bg-indigo-500',
    'review': 'bg-slate-500',
    'Review': 'bg-slate-500',
  }

  const categoryLabels: Record<string, string> = {
    'vip': 'Important',
    'customers': 'Clients',
    'invoices': 'Invoices',
    'newsletters': 'Newsletter',
    'social': 'Social',
    'promotions': 'Promotions',
    'security': 'Security',
    'calendar': 'Calendar',
    'review': 'Review',
  }

  const formatCategoryName = (key: string) => categoryLabels[key] || key

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
      {/* Header */}
      <header className="bg-white/90 dark:bg-slate-900/90 backdrop-blur-md border-b border-slate-200 dark:border-slate-700 sticky top-0 z-50 shadow-sm">
        <div className="w-full px-3 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-14 sm:h-16">
            <Link to="/" className="flex items-center flex-shrink-0 leading-none">
              <img 
                src="/logo.png" 
                alt="MailFlow Logo" 
                className="w-20 h-20 sm:w-20 sm:h-20 rounded-lg shadow-lg object-contain pr-[5px] block"
                style={{ display: 'block', margin: 0, padding: 0 }}
              />
              <span className="text-base sm:text-lg font-bold text-slate-900 dark:text-slate-100 whitespace-nowrap ml-[5px]">
                Mail<span className="text-primary-600 dark:text-primary-400">Flow</span>
              </span>
            </Link>

            <div className="flex items-center gap-1.5 sm:gap-2 lg:gap-4">
              <Button 
                variant="ghost" 
                onClick={() => navigate('/settings')} 
                className="hidden lg:flex h-9"
              >
                <Settings className="w-4 h-4 mr-2" />
                Settings
              </Button>
              <Button 
                variant="ghost" 
                size="icon" 
                className="lg:hidden h-9 w-9" 
                onClick={() => navigate('/settings')}
                title="Settings"
              >
                <Settings className="w-5 h-5 text-slate-600 dark:text-slate-300" />
              </Button>
              <Button 
                variant="outline" 
                onClick={handleLogout} 
                className="hidden lg:flex h-9"
              >
                <LogOut className="w-4 h-4 mr-2" />
                Sign out
              </Button>
              <Button 
                variant="outline" 
                size="icon" 
                className="lg:hidden h-9 w-9" 
                onClick={handleLogout}
                title="Sign out"
              >
                <LogOut className="w-4 h-4 text-slate-600 dark:text-slate-300" />
              </Button>
            </div>
          </div>
        </div>
      </header>

      <main className="w-full px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
        {/* Dashboard Header */}
        <div className="mb-6 sm:mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-slate-100 mb-1">
              Dashboard
            </h1>
            <p className="text-sm text-slate-600 dark:text-slate-400">
              {accounts.length > 0 
                ? `${accounts.length} account${accounts.length > 1 ? 's' : ''} connected`
                : 'Connect Gmail or Outlook to sort your first emails.'}
            </p>
          </div>
          <div className="flex items-center gap-2 sm:gap-3">
            {accounts.length === 0 ? (
              <Button 
                onClick={() => navigate('/setup')}
                className="flex-1 sm:flex-none"
                aria-label="Connect email account"
              >
                <Plus className="w-4 h-4 mr-2" />
                Connect inbox
              </Button>
            ) : (
              <Button 
                onClick={handleSortNow}
                disabled={sorting || accounts.length === 0}
                className="flex-1 sm:flex-none"
                aria-label={sorting ? "Sorting emails" : "Sort emails now"}
              >
                {sorting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Sorting...
                  </>
                ) : (
                  <>
                    <Zap className="w-4 h-4 mr-2" />
                    Sort Now
                  </>
                )}
              </Button>
            )}
          </div>
        </div>

        {/* Success/Error messages */}
        {message && (
          <div className={`mb-3 sm:mb-4 p-2.5 sm:p-3 ${message.type === 'success' ? 'bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-300' : 'bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300'} rounded-lg flex items-start sm:items-center gap-2`}>
            {message.type === 'success' ? (
              <Check className="w-4 h-4 flex-shrink-0 mt-0.5 sm:mt-0 text-green-700 dark:text-green-300" />
            ) : (
              <AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5 sm:mt-0 text-red-700 dark:text-red-300" />
            )}
            <p className="text-xs sm:text-sm flex-1">{message.text}</p>
            <button 
              onClick={() => setMessage(null)} 
              className={`${message.type === 'success' ? 'text-green-400 hover:text-green-600 dark:text-green-500 dark:hover:text-green-400' : 'text-red-400 hover:text-red-600 dark:text-red-500 dark:hover:text-red-400'} text-base font-semibold leading-none focus:outline-none focus:ring-2 focus:ring-primary-500 rounded`}
              aria-label="Close message"
            >
              ✕
            </button>
          </div>
        )}

        {/* First-time hint: account connected, no sort yet */}
        {!loading && accounts.length > 0 && !sortResult && !error && (
          <div className="mb-4 p-4 bg-slate-100 dark:bg-slate-800/60 rounded-xl border border-slate-200 dark:border-slate-700">
            <p className="text-sm text-slate-700 dark:text-slate-300">
              Click <strong>Sort Now</strong> to categorize your inbox. Takes about 30 seconds. Nothing is deleted — we only add labels or move mail to folders.
            </p>
          </div>
        )}

        {/* Error message */}
        {error && (
          <div className="mb-3 sm:mb-4 p-2.5 sm:p-3 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg flex items-start sm:items-center gap-2 text-red-700 dark:text-red-300">
            <AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5 sm:mt-0 text-red-700 dark:text-red-300" />
            <p className="text-xs sm:text-sm flex-1">{error}</p>
            <button 
              onClick={() => setError(null)} 
              className="text-red-400 hover:text-red-600 dark:text-red-500 dark:hover:text-red-400 text-base font-semibold leading-none focus:outline-none focus:ring-2 focus:ring-primary-500 rounded"
              aria-label="Close error message"
            >
              ✕
            </button>
          </div>
        )}

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <div className="text-center">
              <Loader2 className="w-10 h-10 animate-spin text-primary-500 dark:text-primary-400 mx-auto mb-4" />
              <p className="text-slate-500 dark:text-slate-400">Loading your data...</p>
              <p className="text-slate-400 dark:text-slate-500 text-sm mt-1">One moment.</p>
            </div>
          </div>
        ) : (
          <div className="grid lg:grid-cols-[2fr_1fr] gap-6">
            {/* LEFT COLUMN - AI-Assistent Bereich */}
            <div className="space-y-6">
              {/* AI-Assistent Karte */}
              <Card className="border border-slate-200 dark:border-slate-700 shadow-sm">
                <CardHeader className="pb-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center">
                        <Sparkles className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <CardTitle className="text-lg">Email sorting</CardTitle>
                        <CardDescription className="text-sm">
                          Categorize inbox — leads, clients, newsletters
                        </CardDescription>
                      </div>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-6">
                  {/* Sort Result */}
                  {sortResult && (
                    <div className={`p-4 ${sortResult.isFirstRun ? 'bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-900/30 dark:to-emerald-900/30 border-2 border-green-300 dark:border-green-700 rounded-xl' : 'bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded-lg'}`}>
                      <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
                        <div className="flex items-center gap-2 text-green-700 dark:text-green-300">
                          <div className={`${sortResult.isFirstRun ? 'w-8 h-8' : 'w-5 h-5'} flex-shrink-0 bg-green-500 dark:bg-green-600 rounded-full flex items-center justify-center`}>
                            <Check className={`${sortResult.isFirstRun ? 'w-5 h-5' : 'w-4 h-4'} text-white`} />
                          </div>
                          <div>
                            <p className={`${sortResult.isFirstRun ? 'text-lg' : 'text-sm'} font-bold text-green-800 dark:text-green-200`}>
                              {sortResult.isFirstRun ? 'Done. Your inbox is sorted.' : 'Sort complete.'}
                            </p>
                            {sortResult.isFirstRun && (
                              <p className="text-sm text-green-700 dark:text-green-300 mt-0.5">Newsletters and promos are in folders. Check your inbox — only important mail is left.</p>
                            )}
                          </div>
                        </div>
                        {sortResult.isDemo && (
                          <Badge variant="secondary" className="bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300 text-xs">
                            Demo
                          </Badge>
                        )}
                      </div>
                      
                      <div className={`grid ${sortResult.isFirstRun ? 'grid-cols-4' : 'grid-cols-3'} gap-3 mb-4`}>
                        <div className={sortResult.isFirstRun ? 'bg-white/80 dark:bg-slate-800/80 p-3 rounded-lg' : ''}>
                          <p className="text-xs text-green-600 dark:text-green-400 mb-1">Emails categorized</p>
                          <p className={`${sortResult.isFirstRun ? 'text-2xl' : 'text-xl'} font-bold text-green-800 dark:text-green-200`}>{sortResult.sorted}</p>
                        </div>
                        <div className={sortResult.isFirstRun ? 'bg-white/80 dark:bg-slate-800/80 p-3 rounded-lg' : ''}>
                          <p className="text-xs text-green-600 dark:text-green-400 mb-1">Inbox reduced</p>
                          <p className={`${sortResult.isFirstRun ? 'text-2xl' : 'text-xl'} font-bold text-green-800 dark:text-green-200`}>{sortResult.inboxCleared}</p>
                        </div>
                        <div className={sortResult.isFirstRun ? 'bg-white/80 dark:bg-slate-800/80 p-3 rounded-lg' : ''}>
                          <p className="text-xs text-green-600 dark:text-green-400 mb-1">Time saved</p>
                          <p className={`${sortResult.isFirstRun ? 'text-2xl' : 'text-xl'} font-bold text-green-800 dark:text-green-200`}>{sortResult.timeSaved.formatted}</p>
                        </div>
                        {sortResult.isFirstRun && Object.entries(sortResult.categories).length > 0 && (
                          <div className="bg-white/80 dark:bg-slate-800/80 p-3 rounded-lg">
                            <p className="text-xs text-green-600 dark:text-green-400 mb-1">Top category</p>
                            <p className="text-xl font-bold text-green-800 dark:text-green-200">
                              {Object.entries(sortResult.categories).sort(([, a], [, b]) => b - a)[0]?.[1] || 0}
                            </p>
                            <p className="text-xs text-green-500 dark:text-green-400 mt-1">
                              {formatCategoryName(Object.entries(sortResult.categories).sort(([, a], [, b]) => b - a)[0]?.[0] || '')}
                            </p>
                          </div>
                        )}
                      </div>

                      {/* Suggested Rules */}
                      {sortResult.isFirstRun && sortResult.suggestedRules && sortResult.suggestedRules.length > 0 && (
                        <div className="mt-4 pt-4 border-t border-green-200 dark:border-green-800">
                          <div className="mb-3">
                            <p className="text-sm font-semibold text-green-900 dark:text-green-200">Suggestions for you</p>
                            <p className="text-xs text-green-600 dark:text-green-400 mt-0.5">Based on your email patterns</p>
                          </div>
                          <div className="space-y-2 mb-3">
                            {sortResult.suggestedRules.slice(0, 3).map((rule, idx) => (
                              <div key={idx} className="flex items-start gap-3 p-3 bg-white/60 dark:bg-slate-800/60 rounded-lg border border-green-200 dark:border-green-800">
                                <div className="w-6 h-6 rounded-full bg-green-100 dark:bg-green-900/50 flex items-center justify-center flex-shrink-0 mt-0.5">
                                  <Lightbulb className="w-3 h-3 text-green-600 dark:text-green-400" />
                                </div>
                                <div className="flex-1 min-w-0">
                                  <p className="text-sm font-medium text-slate-900 dark:text-slate-100">{rule.name}</p>
                                  <p className="text-xs text-slate-600 dark:text-slate-400 mt-0.5">{rule.description}</p>
                                </div>
                              </div>
                            ))}
                          </div>
                          <Button
                            onClick={async () => {
                              if (!user?.$id || !sortResult.suggestedRules) return
                              setSorting(true)
                              try {
                                const vipSenders = sortResult.suggestedRules
                                  .filter((r): r is typeof r & { action: { email: string } } => r.type === 'vip_sender' && !!r.action?.email)
                                  .map(r => ({ email: r.action.email }))
                                
                                const companyLabels = sortResult.suggestedRules
                                  .filter((r): r is typeof r & { action: { name: string; condition?: string; category?: string } } => r.type === 'company_label' && !!r.action?.name)
                                  .map(r => ({
                                    name: r.action.name,
                                    condition: r.action.condition ?? '',
                                    category: r.action.category || 'promotions',
                                    enabled: true,
                                  }))

                                const updates: { vipSenders?: Array<{ email: string; name?: string }>; companyLabels?: Array<{ name: string; condition?: string; category: string; enabled: boolean }> } = {}
                                if (vipSenders.length > 0) {
                                  updates.vipSenders = vipSenders
                                }
                                if (companyLabels.length > 0) {
                                  updates.companyLabels = companyLabels
                                }

                                if (Object.keys(updates).length > 0) {
                                  await api.saveUserPreferences(updates)
                                  trackRulesApplied(user.$id, sortResult.suggestedRules.length)
                                  showMessage('success', `${sortResult.suggestedRules.length} rules applied. Your inbox will stay organized.`)
                                  setSortResult({ ...sortResult, suggestedRules: [] })
                                }
                              } catch {
                                showMessage('error', 'Unable to apply rules right now. Please try again.')
                              } finally {
                                setSorting(false)
                              }
                            }}
                            disabled={sorting}
                            className="w-full bg-green-600 hover:bg-green-700 text-white"
                            aria-label="Apply suggested rules"
                          >
                            {sorting ? (
                              <>
                                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                Applying rules...
                              </>
                            ) : (
                              <>
                                <Sparkles className="w-4 h-4 mr-2" />
                                Apply {sortResult.suggestedRules.length} suggested rules
                              </>
                            )}
                          </Button>
                        </div>
                      )}

                      {/* Share Results */}
                      {sortResult && sortResult.sorted >= 10 && (
                        <div className="mt-4">
                          <ShareResults 
                            sortedCount={sortResult.sorted}
                            referralCode={referralCode || undefined}
                          />
                        </div>
                      )}

                      {/* Upgrade Prompt after applying rules */}
                      {sortResult && !sortResult.suggestedRules && subscription?.isFreeTier && sortResult.sorted > 0 && (
                        <div className="mt-4">
                          <UpgradePrompt
                            source="after_rules"
                            onDismiss={() => {}}
                          />
                        </div>
                      )}

                      {/* Categories breakdown (non-first-run) */}
                      {!sortResult.isFirstRun && Object.keys(sortResult.categories).length > 2 && (
                        <div className="mt-4 pt-4 border-t border-green-200 dark:border-green-800">
                          <p className="text-xs text-green-600 dark:text-green-400 mb-1.5">Categories:</p>
                          <div className="flex flex-wrap gap-1">
                            {Object.entries(sortResult.categories).map(([cat, count]) => (
                              <span 
                                key={cat} 
                                className={`px-1.5 py-0.5 rounded-full text-xs font-medium text-white ${categoryColors[cat] || 'bg-slate-500'}`}
                              >
                                {formatCategoryName(cat)}: {count}
                              </span>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  )}

                  {/* Upgrade Prompt after successful sort (free tier) */}
                  {sortResult && subscription?.isFreeTier && !sortResult.isFirstRun && (
                    <UpgradePrompt
                      source="after_sort"
                      onDismiss={() => {}}
                    />
                  )}

                  {/* Stats Cards - Kompakt */}
                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-4 bg-slate-50 dark:bg-slate-800/50 rounded-lg border border-slate-200 dark:border-slate-700">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-xs text-slate-600 dark:text-slate-400">Sorted today</p>
                        <Inbox className="w-4 h-4 text-primary-500 dark:text-primary-400" />
                      </div>
                      <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{displayStats.todaySorted}</p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">emails</p>
                    </div>
                    <div className="p-4 bg-slate-50 dark:bg-slate-800/50 rounded-lg border border-slate-200 dark:border-slate-700">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-xs text-slate-600 dark:text-slate-400">This week</p>
                        <TrendingUp className="w-4 h-4 text-accent-500 dark:text-accent-400" />
                      </div>
                      <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{displayStats.weekSorted}</p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">emails</p>
                    </div>
                    <div className="p-4 bg-slate-50 dark:bg-slate-800/50 rounded-lg border border-slate-200 dark:border-slate-700">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-xs text-slate-600 dark:text-slate-400">Time saved</p>
                        <Clock className="w-4 h-4 text-green-500 dark:text-green-400" />
                      </div>
                      <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
                        {displayStats.timeSaved > 60 
                          ? `${Math.floor(displayStats.timeSaved / 60)}h ${displayStats.timeSaved % 60}m`
                          : `${displayStats.timeSaved}m`}
                      </p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">this week</p>
                    </div>
                    <div className="p-4 bg-slate-50 dark:bg-slate-800/50 rounded-lg border border-slate-200 dark:border-slate-700">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-xs text-slate-600 dark:text-slate-400">Total sorted</p>
                        <BarChart3 className="w-4 h-4 text-violet-500 dark:text-violet-400" />
                      </div>
                      <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{displayStats.totalSorted.toLocaleString('en-US')}</p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">emails</p>
                    </div>
                  </div>

                  {/* Daily Digest */}
                  {digest?.hasData && (
                    <div className="p-4 bg-gradient-to-r from-primary-50 to-accent-50 dark:from-primary-900/30 dark:to-accent-900/30 rounded-lg border border-primary-200 dark:border-primary-800">
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <Sparkles className="w-5 h-5 text-primary-600 dark:text-primary-400" />
                          <div>
                            <h3 className="text-sm font-bold text-slate-900 dark:text-slate-100">Today's Digest</h3>
                            <p className="text-xs text-slate-600 dark:text-slate-400">{new Date(digest.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</p>
                          </div>
                        </div>
                        {digest.inboxCleared > 0 && (
                          <Badge className="bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300 border-green-200 dark:border-green-800 text-xs">
                            <Archive className="w-3 h-3 mr-0.5" />
                            {digest.inboxCleared}
                          </Badge>
                        )}
                      </div>

                      <div className="grid grid-cols-3 gap-2 mb-3">
                        <div className="bg-white/80 dark:bg-slate-800/80 rounded-lg p-2 border border-slate-200/50 dark:border-slate-700/50">
                          <p className="text-xs text-slate-500 dark:text-slate-400 mb-0.5">Processed</p>
                          <p className="text-base font-bold text-slate-900 dark:text-slate-100">{digest.totalSorted}</p>
                        </div>
                        <div className="bg-white/80 dark:bg-slate-800/80 rounded-lg p-2 border border-slate-200/50 dark:border-slate-700/50">
                          <p className="text-xs text-slate-500 dark:text-slate-400 mb-0.5">Cleared</p>
                          <p className="text-base font-bold text-green-600 dark:text-green-400">{digest.inboxCleared}</p>
                        </div>
                        <div className="bg-white/80 dark:bg-slate-800/80 rounded-lg p-2 border border-slate-200/50 dark:border-slate-700/50">
                          <p className="text-xs text-slate-500 dark:text-slate-400 mb-0.5">Saved</p>
                          <p className="text-base font-bold text-primary-600 dark:text-primary-400">
                            {digest.timeSavedMinutes > 60 
                              ? `${Math.floor(digest.timeSavedMinutes / 60)}h ${digest.timeSavedMinutes % 60}m`
                              : `${digest.timeSavedMinutes}m`}
                          </p>
                        </div>
                      </div>

                      {digest.highlights.length > 0 && (
                        <div className="mb-3">
                          <p className="text-xs font-medium text-slate-700 dark:text-slate-300 mb-1.5 flex items-center gap-1.5">
                            <AlertTriangle className="w-3.5 h-3.5 text-amber-500 dark:text-amber-400" />
                            Needs Attention
                          </p>
                          <div className="flex flex-wrap gap-1.5">
                            {digest.highlights.map((highlight, idx) => (
                              <div 
                                key={idx}
                                className={`px-2 py-1 rounded-md text-xs ${
                                  highlight.type === 'vip' ? 'bg-amber-100 dark:bg-amber-900/50 text-amber-800 dark:text-amber-300' :
                                  highlight.type === 'security' ? 'bg-red-100 dark:bg-red-900/50 text-red-800 dark:text-red-300' :
                                  highlight.type === 'invoices' ? 'bg-green-100 dark:bg-green-900/50 text-green-800 dark:text-green-300' :
                                  'bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300'
                                }`}
                              >
                                {highlight.message}
                              </div>
                            ))}
                          </div>
                        </div>
                      )}

                      {digest.suggestions.length > 0 && (
                        <div className="pt-2.5 border-t border-slate-200/50 dark:border-slate-700/50">
                          <p className="text-xs font-medium text-slate-700 dark:text-slate-300 mb-1.5 flex items-center gap-1.5">
                            <Lightbulb className="w-3.5 h-3.5 text-primary-500 dark:text-primary-400" />
                            Suggestions
                          </p>
                          <div className="space-y-1">
                            {digest.suggestions.map((suggestion, idx) => (
                              <p key={idx} className="text-xs text-slate-600 dark:text-slate-400 bg-white/60 dark:bg-slate-800/60 rounded-md px-2 py-1">
                                {suggestion.message}
                              </p>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  )}

                  {/* Categories Overview */}
                  <div>
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <Tag className="w-4 h-4 text-primary-500 dark:text-primary-400" />
                        <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-100">Categories Overview</h3>
                      </div>
                      <p className="text-xs text-slate-500 dark:text-slate-400">This week</p>
                    </div>
                    {Object.keys(displayStats.categories).length > 0 ? (
                      <div className="space-y-2.5">
                        {Object.entries(displayStats.categories).map(([category, count]) => {
                          const total = Object.values(displayStats.categories).reduce((a, b) => a + b, 0)
                          const percentage = total > 0 ? Math.round((count / total) * 100) : 0
                          
                          return (
                            <div key={category}>
                              <div className="flex items-center justify-between mb-1">
                                <div className="flex items-center gap-1.5 min-w-0 flex-1">
                                  <div className={`w-2 h-2 rounded-full flex-shrink-0 ${categoryColors[category] || 'bg-slate-400 dark:bg-slate-500'}`} />
                                  <span className="text-xs font-medium text-slate-700 dark:text-slate-300 truncate">{formatCategoryName(category)}</span>
                                </div>
                                <div className="flex items-center gap-1 flex-shrink-0">
                                  <span className="text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">{count}</span>
                                  <span className="text-xs text-slate-400 dark:text-slate-500 whitespace-nowrap">({percentage}%)</span>
                                </div>
                              </div>
                              <div className="h-1.5 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden">
                                <div 
                                  className={`h-full rounded-full transition-all duration-500 ${categoryColors[category] || 'bg-slate-400 dark:bg-slate-500'}`}
                                  style={{ width: `${percentage}%` }}
                                />
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    ) : (
                      <div className="text-center py-8">
                        <Tag className="w-10 h-10 text-slate-300 dark:text-slate-600 mx-auto mb-3" />
                        <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">No category statistics yet</p>
                        <p className="text-xs text-slate-400 dark:text-slate-500">Start a sort to see statistics</p>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* RIGHT COLUMN - Control Panel, Einstellungen, Account */}
            <div className="space-y-6">
              {/* Control Panel Karte */}
              <Card className="border border-slate-200 dark:border-slate-700 shadow-sm">
                <CardHeader className="pb-3">
                  <div className="flex items-center gap-2">
                    <Brain className="w-5 h-5 text-primary-500 dark:text-primary-400" />
                    <CardTitle className="text-base">Control Panel</CardTitle>
                  </div>
                  <CardDescription className="text-xs">
                    Categories and rules
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Button 
                    onClick={() => navigate('/settings?tab=ai-control')}
                    variant="outline"
                    className="w-full"
                    aria-label="Open Control Panel settings"
                  >
                    <Settings className="w-4 h-4 mr-2" />
                    Open Control Panel
                    <ExternalLink className="w-3 h-3 ml-2" />
                  </Button>
                </CardContent>
              </Card>

              {/* Einstellungen Karte */}
              <Card className="border border-slate-200 dark:border-slate-700 shadow-sm">
                <CardHeader className="pb-3">
                  <div className="flex items-center gap-2">
                    <Settings className="w-5 h-5 text-primary-500 dark:text-primary-400" />
                    <CardTitle className="text-base">Settings</CardTitle>
                  </div>
                  <CardDescription className="text-xs">
                    Quick access
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-2">
                  <Button 
                    onClick={() => navigate('/settings?tab=vip')}
                    variant="ghost"
                    className="w-full justify-start"
                    aria-label="Manage VIP list"
                  >
                    <Shield className="w-4 h-4 mr-2" />
                    VIP List
                  </Button>
                  <Button 
                    onClick={() => navigate('/settings?tab=accounts')}
                    variant="ghost"
                    className="w-full justify-start"
                    aria-label="Manage email accounts"
                  >
                    <Users className="w-4 h-4 mr-2" />
                    Email Accounts
                  </Button>
                  <Button 
                    onClick={() => navigate('/settings')}
                    variant="ghost"
                    className="w-full justify-start"
                    aria-label="Open all settings"
                  >
                    <Settings className="w-4 h-4 mr-2" />
                    All settings
                    <ExternalLink className="w-3 h-3 ml-auto" />
                  </Button>
                </CardContent>
              </Card>

              {/* Account/System Karte */}
              <Card className="border border-slate-200 dark:border-slate-700 shadow-sm">
                <CardHeader className="pb-3">
                  <CardTitle className="text-base">Account</CardTitle>
                  <CardDescription className="text-xs">
                    Subscription and accounts
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Subscription Status */}
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs font-medium text-slate-700 dark:text-slate-300">Subscription</p>
                      <Badge variant={subscription?.isFreeTier ? 'secondary' : 'default'} className="text-xs">
                        {subscription?.isFreeTier
                          ? 'Free Tier'
                          : subscription?.planDisplayName ||
                            (subscription?.plan
                              ? subscription.plan.charAt(0).toUpperCase() + subscription.plan.slice(1)
                              : 'Business')}
                      </Badge>
                    </div>
                    {subscription?.isFreeTier && subscription.emailsLimit && (
                      <div className="mt-2">
                        <div className="flex items-center justify-between text-xs text-slate-600 dark:text-slate-400 mb-1">
                          <span>{subscription.emailsUsedThisMonth || 0} / {subscription.emailsLimit}</span>
                          <span>{Math.round(((subscription.emailsUsedThisMonth || 0) / subscription.emailsLimit) * 100)}%</span>
                        </div>
                        <div className="w-full h-1.5 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
                          <div 
                            className={`h-full transition-all duration-300 ${
                              (subscription.emailsUsedThisMonth || 0) >= subscription.emailsLimit
                                ? 'bg-red-500 dark:bg-red-600'
                                : (subscription.emailsUsedThisMonth || 0) >= subscription.emailsLimit * 0.8
                                  ? 'bg-amber-500 dark:bg-amber-600'
                                  : 'bg-primary-500 dark:bg-primary-600'
                            }`}
                            style={{ 
                              width: `${Math.min(100, ((subscription.emailsUsedThisMonth || 0) / subscription.emailsLimit) * 100)}%` 
                            }}
                          />
                        </div>
                        {(subscription.emailsUsedThisMonth || 0) >= subscription.emailsLimit && (
                          <div className="mt-2">
                            <UpgradePrompt
                              source="limit_reached"
                              onDismiss={() => {}}
                            />
                          </div>
                        )}
                        {(subscription.emailsUsedThisMonth || 0) < subscription.emailsLimit && (
                          <Button
                            onClick={() => navigate('/settings?tab=subscription')}
                            variant="ghost"
                            size="sm"
                            className="w-full mt-2 text-xs"
                            aria-label="Upgrade subscription"
                          >
                            Upgrade
                          </Button>
                        )}
                      </div>
                    )}
                    {!subscription?.isFreeTier && (
                      <Button
                        onClick={() => navigate('/settings?tab=subscription')}
                        variant="ghost"
                        size="sm"
                        className="w-full mt-2 text-xs"
                        aria-label="Manage subscription"
                      >
                        Manage Subscription
                      </Button>
                    )}
                  </div>

                  {/* Email Accounts - Kompakt */}
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs font-medium text-slate-700 dark:text-slate-300">Email Accounts</p>
                      <Badge variant="secondary" className="text-xs">
                        {accounts.length} {accounts.length === 1 ? 'account' : 'accounts'}
                      </Badge>
                    </div>
                    {accounts.length > 0 ? (
                      <div className="space-y-2">
                        {accounts.slice(0, 2).map((account) => (
                          <div 
                            key={account.id}
                            className="flex items-center justify-between p-2 bg-slate-50 dark:bg-slate-800/50 rounded-lg"
                          >
                            <div className="flex items-center gap-2 min-w-0 flex-1">
                              <div className={`w-6 h-6 rounded flex items-center justify-center flex-shrink-0 ${
                                account.provider === 'gmail' ? 'bg-red-100 dark:bg-red-900/50' : account.provider === 'outlook' ? 'bg-blue-100 dark:bg-blue-900/50' : 'bg-slate-100 dark:bg-slate-700/50'
                              }`}>
                                <Mail className={`w-3 h-3 ${
                                  account.provider === 'gmail' ? 'text-red-600 dark:text-red-400' : account.provider === 'outlook' ? 'text-blue-600 dark:text-blue-400' : 'text-slate-600 dark:text-slate-400'
                                }`} />
                              </div>
                              <p className="text-xs font-medium text-slate-700 dark:text-slate-300 truncate">{account.email}</p>
                            </div>
                            <Badge variant={account.connected ? 'success' : 'secondary'} className="text-xs px-1.5 py-0.5">
                              {account.connected ? 'Active' : 'Off'}
                            </Badge>
                          </div>
                        ))}
                        {accounts.length > 2 && (
                          <Button
                            onClick={() => navigate('/settings?tab=accounts')}
                            variant="ghost"
                            size="sm"
                            className="w-full text-xs"
                            aria-label="View all email accounts"
                          >
                            View all {accounts.length} accounts
                          </Button>
                        )}
                      </div>
                    ) : (
                      <div className="text-center py-4">
                        <Mail className="w-8 h-8 text-slate-300 dark:text-slate-600 mx-auto mb-2" />
                        <p className="text-xs text-slate-500 dark:text-slate-400 mb-2">No inbox connected yet</p>
                        <Button
                          onClick={() => navigate('/setup')}
                          variant="outline"
                          size="sm"
                          className="w-full text-xs"
                          aria-label="Connect email account"
                        >
                          <Plus className="w-3 h-3 mr-1.5" />
                          Connect inbox
                        </Button>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )}
      </main>
    </div>
  )
}


