'use client'

/**
 * Unified Inbox - User Frontend
 *
 * Main email interface for users with:
 * - Unified inbox view (all accounts)
 * - Email detail view with AI analysis
 * - Quick actions and response suggestions
 *
 * See: docs/klausur-modul/UNIFIED-INBOX-SPECIFICATION.md
 */

import { useState, useEffect, useCallback } from 'react'

// API Base URL
const API_BASE = process.env.NEXT_PUBLIC_KLAUSUR_SERVICE_URL || 'http://localhost:8086'

// Types
interface Email {
  id: string
  accountId: string
  accountEmail: string
  messageId: string
  subject: string
  senderName: string
  senderEmail: string
  recipients: string[]
  date: string
  bodyPreview: string
  bodyHtml?: string
  bodyText?: string
  isRead: boolean
  hasAttachments: boolean
  attachmentCount: number
  // AI Analysis
  senderType?: string
  category?: string
  priority?: string
  deadlines?: Deadline[]
  aiAnalyzed: boolean
}

interface Deadline {
  date: string
  description: string
  isFirm: boolean
  confidence: number
}

interface Account {
  id: string
  email: string
  displayName: string
  unreadCount: number
}

interface Folder {
  name: string
  icon: JSX.Element
  count?: number
}

export default function MailPage() {
  const [emails, setEmails] = useState<Email[]>([])
  const [accounts, setAccounts] = useState<Account[]>([])
  const [selectedEmail, setSelectedEmail] = useState<Email | null>(null)
  const [selectedAccount, setSelectedAccount] = useState<string>('all')
  const [selectedFolder, setSelectedFolder] = useState('inbox')
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')

  const folders: Folder[] = [
    {
      name: 'inbox',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
        </svg>
      ),
    },
    {
      name: 'unread',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
        </svg>
      ),
    },
    {
      name: 'tasks',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
        </svg>
      ),
    },
    {
      name: 'sent',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
        </svg>
      ),
    },
  ]

  const folderLabels: Record<string, string> = {
    inbox: 'Posteingang',
    unread: 'Ungelesen',
    tasks: 'Aufgaben',
    sent: 'Gesendet',
  }

  const fetchEmails = useCallback(async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      if (selectedAccount !== 'all') {
        params.append('account_id', selectedAccount)
      }
      if (selectedFolder === 'unread') {
        params.append('unread_only', 'true')
      }
      if (searchQuery) {
        params.append('search', searchQuery)
      }

      const res = await fetch(`${API_BASE}/api/v1/mail/inbox?${params}`)
      if (res.ok) {
        const data = await res.json()
        setEmails(data.emails || [])
      }
    } catch (err) {
      console.error('Failed to fetch emails:', err)
    } finally {
      setLoading(false)
    }
  }, [selectedAccount, selectedFolder, searchQuery])

  const fetchAccounts = useCallback(async () => {
    try {
      const res = await fetch(`${API_BASE}/api/v1/mail/accounts`)
      if (res.ok) {
        const data = await res.json()
        setAccounts(data.accounts || [])
      }
    } catch (err) {
      console.error('Failed to fetch accounts:', err)
    }
  }, [])

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

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

  const analyzeEmail = async (emailId: string) => {
    try {
      const res = await fetch(`${API_BASE}/api/v1/mail/analyze/${emailId}`, {
        method: 'POST',
      })
      if (res.ok) {
        const data = await res.json()
        // Update the selected email with analysis results
        setSelectedEmail((prev) => prev ? { ...prev, ...data, aiAnalyzed: true } : null)
        // Update the email in the list
        setEmails((prev) =>
          prev.map((e) => (e.id === emailId ? { ...e, ...data, aiAnalyzed: true } : e))
        )
      }
    } catch (err) {
      console.error('Failed to analyze email:', err)
    }
  }

  const markAsRead = async (emailId: string) => {
    try {
      await fetch(`${API_BASE}/api/v1/mail/inbox/${emailId}/read`, {
        method: 'POST',
      })
      setEmails((prev) =>
        prev.map((e) => (e.id === emailId ? { ...e, isRead: true } : e))
      )
    } catch (err) {
      console.error('Failed to mark as read:', err)
    }
  }

  const handleEmailClick = (email: Email) => {
    setSelectedEmail(email)
    if (!email.isRead) {
      markAsRead(email.id)
    }
  }

  const totalUnread = accounts.reduce((sum, acc) => sum + acc.unreadCount, 0)

  return (
    <div className="h-screen flex flex-col bg-slate-100">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-semibold text-slate-900">Unified Inbox</h1>
          {totalUnread > 0 && (
            <span className="px-2 py-1 bg-primary-100 text-primary-700 text-sm font-medium rounded-full">
              {totalUnread} ungelesen
            </span>
          )}
        </div>
        <div className="flex items-center gap-4">
          {/* Search */}
          <div className="relative">
            <input
              type="text"
              placeholder="E-Mails durchsuchen..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-64 pl-10 pr-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            />
            <svg className="absolute left-3 top-2.5 w-5 h-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
          {/* Compose Button */}
          <a
            href="/mail/compose"
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 flex items-center gap-2"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Verfassen
          </a>
        </div>
      </header>

      {/* Main Content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Sidebar */}
        <aside className="w-64 bg-white border-r border-slate-200 flex flex-col">
          {/* Folders */}
          <nav className="p-4 space-y-1">
            {folders.map((folder) => (
              <button
                key={folder.name}
                onClick={() => setSelectedFolder(folder.name)}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${
                  selectedFolder === folder.name
                    ? 'bg-primary-50 text-primary-700'
                    : 'text-slate-600 hover:bg-slate-50'
                }`}
              >
                {folder.icon}
                <span className="font-medium">{folderLabels[folder.name]}</span>
                {folder.count !== undefined && (
                  <span className="ml-auto text-sm text-slate-500">{folder.count}</span>
                )}
              </button>
            ))}
          </nav>

          <div className="border-t border-slate-200 my-2"></div>

          {/* Accounts */}
          <div className="p-4">
            <h3 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">
              Konten
            </h3>
            <div className="space-y-1">
              <button
                onClick={() => setSelectedAccount('all')}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${
                  selectedAccount === 'all'
                    ? 'bg-primary-50 text-primary-700'
                    : 'text-slate-600 hover:bg-slate-50'
                }`}
              >
                <div className="w-2 h-2 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full"></div>
                <span className="font-medium text-sm">Alle Konten</span>
                <span className="ml-auto text-xs text-slate-500">{totalUnread}</span>
              </button>
              {accounts.map((account) => (
                <button
                  key={account.id}
                  onClick={() => setSelectedAccount(account.id)}
                  className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${
                    selectedAccount === account.id
                      ? 'bg-primary-50 text-primary-700'
                      : 'text-slate-600 hover:bg-slate-50'
                  }`}
                >
                  <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                  <span className="font-medium text-sm truncate flex-1">
                    {account.displayName || account.email.split('@')[0]}
                  </span>
                  {account.unreadCount > 0 && (
                    <span className="text-xs bg-primary-100 text-primary-700 px-1.5 py-0.5 rounded">
                      {account.unreadCount}
                    </span>
                  )}
                </button>
              ))}
            </div>
          </div>

          {/* Quick Links */}
          <div className="mt-auto p-4 border-t border-slate-200">
            <a
              href="/mail/tasks"
              className="flex items-center gap-3 px-3 py-2 text-slate-600 hover:bg-slate-50 rounded-lg"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
              <span className="font-medium text-sm">Arbeitsvorrat</span>
            </a>
          </div>
        </aside>

        {/* Email List */}
        <div className="w-96 bg-white border-r border-slate-200 overflow-y-auto">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
            </div>
          ) : emails.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-center px-4">
              <svg className="w-12 h-12 text-slate-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
              <p className="text-slate-500">Keine E-Mails gefunden</p>
            </div>
          ) : (
            <div className="divide-y divide-slate-100">
              {emails.map((email) => (
                <EmailListItem
                  key={email.id}
                  email={email}
                  isSelected={selectedEmail?.id === email.id}
                  onClick={() => handleEmailClick(email)}
                />
              ))}
            </div>
          )}
        </div>

        {/* Email Detail / AI Panel */}
        <div className="flex-1 bg-white overflow-y-auto">
          {selectedEmail ? (
            <EmailDetail
              email={selectedEmail}
              onAnalyze={() => analyzeEmail(selectedEmail.id)}
            />
          ) : (
            <div className="flex flex-col items-center justify-center h-full text-center px-4">
              <svg className="w-16 h-16 text-slate-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
              <p className="text-slate-500 text-lg">Wählen Sie eine E-Mail aus</p>
              <p className="text-slate-400 text-sm mt-1">
                Klicken Sie auf eine E-Mail, um sie zu lesen
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

// ============================================================================
// Email List Item
// ============================================================================

function EmailListItem({
  email,
  isSelected,
  onClick
}: {
  email: Email
  isSelected: boolean
  onClick: () => void
}) {
  const priorityColors: Record<string, string> = {
    urgent: 'bg-red-500',
    high: 'bg-orange-500',
    medium: 'bg-yellow-500',
    low: 'bg-green-500',
  }

  const senderTypeLabels: Record<string, string> = {
    kultusministerium: 'MK',
    landesschulbehoerde: 'NLSchB',
    rlsb: 'RLSB',
    nibis: 'NiBiS',
    schulamt: 'Schulamt',
  }

  return (
    <button
      onClick={onClick}
      className={`w-full p-4 text-left hover:bg-slate-50 transition-colors ${
        isSelected ? 'bg-primary-50' : ''
      } ${!email.isRead ? 'bg-blue-50' : ''}`}
    >
      <div className="flex items-start gap-3">
        {/* Priority Indicator */}
        {email.priority && (
          <div className={`w-2 h-2 rounded-full mt-2 ${priorityColors[email.priority] || 'bg-slate-300'}`}></div>
        )}

        <div className="flex-1 min-w-0">
          {/* Sender */}
          <div className="flex items-center gap-2 mb-1">
            <span className={`font-medium text-sm ${!email.isRead ? 'text-slate-900' : 'text-slate-700'}`}>
              {email.senderName || email.senderEmail.split('@')[0]}
            </span>
            {email.senderType && senderTypeLabels[email.senderType] && (
              <span className="px-1.5 py-0.5 bg-purple-100 text-purple-700 text-xs font-medium rounded">
                {senderTypeLabels[email.senderType]}
              </span>
            )}
          </div>

          {/* Subject */}
          <p className={`text-sm truncate ${!email.isRead ? 'font-medium text-slate-900' : 'text-slate-700'}`}>
            {email.subject || '(Kein Betreff)'}
          </p>

          {/* Preview */}
          <p className="text-xs text-slate-500 truncate mt-1">
            {email.bodyPreview}
          </p>

          {/* Meta */}
          <div className="flex items-center gap-2 mt-2">
            <span className="text-xs text-slate-400">
              {new Date(email.date).toLocaleDateString('de-DE', {
                day: '2-digit',
                month: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
              })}
            </span>
            {email.hasAttachments && (
              <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
              </svg>
            )}
            {email.deadlines && email.deadlines.length > 0 && (
              <span className="px-1.5 py-0.5 bg-red-100 text-red-700 text-xs rounded flex items-center gap-1">
                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Frist
              </span>
            )}
            {email.aiAnalyzed && (
              <svg className="w-4 h-4 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-label="KI-analysiert">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
              </svg>
            )}
          </div>
        </div>
      </div>
    </button>
  )
}

// ============================================================================
// Email Detail
// ============================================================================

function EmailDetail({
  email,
  onAnalyze
}: {
  email: Email
  onAnalyze: () => void
}) {
  const [showAIPanel, setShowAIPanel] = useState(true)

  const senderTypeLabels: Record<string, { label: string; color: string }> = {
    kultusministerium: { label: 'Kultusministerium', color: 'bg-purple-100 text-purple-800' },
    landesschulbehoerde: { label: 'Landesschulbehörde', color: 'bg-blue-100 text-blue-800' },
    rlsb: { label: 'RLSB', color: 'bg-indigo-100 text-indigo-800' },
    nibis: { label: 'NiBiS', color: 'bg-cyan-100 text-cyan-800' },
    schulamt: { label: 'Schulamt', color: 'bg-teal-100 text-teal-800' },
    elternvertreter: { label: 'Elternvertreter', color: 'bg-green-100 text-green-800' },
    privatperson: { label: 'Privatperson', color: 'bg-slate-100 text-slate-800' },
  }

  const categoryLabels: Record<string, string> = {
    dienstlich: 'Dienstlich',
    personal: 'Personal',
    finanzen: 'Finanzen',
    eltern: 'Eltern',
    schueler: 'Schüler',
    fortbildung: 'Fortbildung',
    veranstaltung: 'Veranstaltung',
    sicherheit: 'Sicherheit',
    newsletter: 'Newsletter',
  }

  return (
    <div className="flex h-full">
      {/* Email Content */}
      <div className="flex-1 flex flex-col">
        {/* Header */}
        <div className="p-6 border-b border-slate-200">
          <h1 className="text-xl font-semibold text-slate-900 mb-4">
            {email.subject || '(Kein Betreff)'}
          </h1>

          <div className="flex items-start justify-between">
            <div className="flex items-center gap-4">
              <div className="w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center">
                <span className="text-primary-700 font-medium">
                  {(email.senderName || email.senderEmail)[0].toUpperCase()}
                </span>
              </div>
              <div>
                <p className="font-medium text-slate-900">
                  {email.senderName || email.senderEmail}
                </p>
                <p className="text-sm text-slate-500">{email.senderEmail}</p>
              </div>
            </div>

            <div className="text-right">
              <p className="text-sm text-slate-500">
                {new Date(email.date).toLocaleDateString('de-DE', {
                  weekday: 'long',
                  day: '2-digit',
                  month: 'long',
                  year: 'numeric',
                  hour: '2-digit',
                  minute: '2-digit',
                })}
              </p>
              <p className="text-xs text-slate-400 mt-1">An: {email.recipients.join(', ')}</p>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-2 mt-4">
            <button className="px-3 py-1.5 text-sm font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100">
              Antworten
            </button>
            <button className="px-3 py-1.5 text-sm font-medium text-slate-600 bg-slate-100 rounded-lg hover:bg-slate-200">
              Weiterleiten
            </button>
            <button className="px-3 py-1.5 text-sm font-medium text-slate-600 bg-slate-100 rounded-lg hover:bg-slate-200">
              Aufgabe erstellen
            </button>
            {!email.aiAnalyzed && (
              <button
                onClick={onAnalyze}
                className="px-3 py-1.5 text-sm font-medium text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 flex items-center gap-1"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                </svg>
                Mit KI analysieren
              </button>
            )}
          </div>
        </div>

        {/* Body */}
        <div className="flex-1 p-6 overflow-y-auto">
          {email.bodyHtml ? (
            <div
              className="prose prose-slate max-w-none"
              dangerouslySetInnerHTML={{ __html: email.bodyHtml }}
            />
          ) : (
            <pre className="whitespace-pre-wrap text-slate-700 font-sans">
              {email.bodyText || email.bodyPreview}
            </pre>
          )}

          {/* Attachments */}
          {email.hasAttachments && (
            <div className="mt-6 pt-6 border-t border-slate-200">
              <h3 className="text-sm font-medium text-slate-700 mb-3">
                Anhänge ({email.attachmentCount})
              </h3>
              <div className="flex flex-wrap gap-2">
                <div className="flex items-center gap-2 px-3 py-2 bg-slate-100 rounded-lg">
                  <svg className="w-5 h-5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  <span className="text-sm text-slate-700">Anhang herunterladen</span>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* AI Panel */}
      {showAIPanel && (
        <div className="w-80 border-l border-slate-200 bg-slate-50 overflow-y-auto">
          <div className="p-4 border-b border-slate-200 bg-white flex items-center justify-between">
            <div className="flex items-center gap-2">
              <svg className="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
              </svg>
              <h2 className="font-semibold text-slate-900">KI-Analyse</h2>
            </div>
            <button
              onClick={() => setShowAIPanel(false)}
              className="p-1 text-slate-400 hover:text-slate-600"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {email.aiAnalyzed ? (
            <div className="p-4 space-y-6">
              {/* Sender Classification */}
              {email.senderType && senderTypeLabels[email.senderType] && (
                <div>
                  <h3 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
                    Absender-Typ
                  </h3>
                  <span className={`px-3 py-1.5 rounded-lg text-sm font-medium ${senderTypeLabels[email.senderType].color}`}>
                    {senderTypeLabels[email.senderType].label}
                  </span>
                </div>
              )}

              {/* Category */}
              {email.category && (
                <div>
                  <h3 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
                    Kategorie
                  </h3>
                  <span className="px-3 py-1.5 bg-slate-200 text-slate-700 rounded-lg text-sm font-medium">
                    {categoryLabels[email.category] || email.category}
                  </span>
                </div>
              )}

              {/* Deadlines */}
              {email.deadlines && email.deadlines.length > 0 && (
                <div>
                  <h3 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
                    Erkannte Fristen
                  </h3>
                  <div className="space-y-2">
                    {email.deadlines.map((deadline, idx) => (
                      <div key={idx} className="p-3 bg-white rounded-lg border border-slate-200">
                        <div className="flex items-center gap-2 mb-1">
                          <svg className="w-4 h-4 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span className="font-medium text-slate-900">
                            {new Date(deadline.date).toLocaleDateString('de-DE', {
                              day: '2-digit',
                              month: '2-digit',
                              year: 'numeric',
                            })}
                          </span>
                          {deadline.isFirm && (
                            <span className="px-1.5 py-0.5 bg-red-100 text-red-700 text-xs rounded">
                              verbindlich
                            </span>
                          )}
                        </div>
                        <p className="text-sm text-slate-600">{deadline.description}</p>
                        <p className="text-xs text-slate-400 mt-1">
                          Konfidenz: {Math.round(deadline.confidence * 100)}%
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Quick Actions */}
              <div>
                <h3 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
                  Schnellaktionen
                </h3>
                <div className="space-y-2">
                  <button className="w-full p-3 bg-white rounded-lg border border-slate-200 text-left hover:bg-slate-50 transition-colors">
                    <div className="flex items-center gap-2">
                      <svg className="w-5 h-5 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                      </svg>
                      <span className="text-sm font-medium text-slate-700">Als Aufgabe speichern</span>
                    </div>
                  </button>
                  <button className="w-full p-3 bg-white rounded-lg border border-slate-200 text-left hover:bg-slate-50 transition-colors">
                    <div className="flex items-center gap-2">
                      <svg className="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                      </svg>
                      <span className="text-sm font-medium text-slate-700">In Kalender eintragen</span>
                    </div>
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div className="p-4 text-center">
              <div className="py-8">
                <svg className="w-12 h-12 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                </svg>
                <p className="text-slate-500 mb-4">Diese E-Mail wurde noch nicht analysiert.</p>
                <button
                  onClick={onAnalyze}
                  className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
                >
                  Jetzt analysieren
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
