'use client'

import React, { useState, useEffect, useMemo } from 'react'
import Link from 'next/link'
import { useSDK } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import {
  Course,
  CourseCategory,
  Enrollment,
  EnrollmentStatus,
  AcademyStatistics,
  COURSE_CATEGORY_INFO,
  ENROLLMENT_STATUS_INFO,
  isEnrollmentOverdue,
  getDaysUntilDeadline
} from '@/lib/sdk/academy/types'
import {
  fetchSDKAcademyList, generateAllCourses, fetchCertificates,
  deleteEnrollment, updateEnrollment, updateCourse, completeEnrollment
} from '@/lib/sdk/academy/api'
import type { Certificate } from '@/lib/sdk/academy/types'

// =============================================================================
// TYPES
// =============================================================================

type TabId = 'overview' | 'courses' | 'enrollments' | 'certificates' | 'settings'

interface Tab {
  id: TabId
  label: string
  count?: number
  countColor?: string
}

// =============================================================================
// COMPONENTS
// =============================================================================

function TabNavigation({
  tabs,
  activeTab,
  onTabChange
}: {
  tabs: Tab[]
  activeTab: TabId
  onTabChange: (tab: TabId) => void
}) {
  return (
    <div className="border-b border-gray-200">
      <nav className="flex gap-1 -mb-px" aria-label="Tabs">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => onTabChange(tab.id)}
            className={`
              px-4 py-3 text-sm font-medium border-b-2 transition-colors
              ${activeTab === tab.id
                ? 'border-purple-600 text-purple-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }
            `}
          >
            <span className="flex items-center gap-2">
              {tab.label}
              {tab.count !== undefined && tab.count > 0 && (
                <span className={`
                  px-2 py-0.5 text-xs rounded-full
                  ${tab.countColor || 'bg-gray-100 text-gray-600'}
                `}>
                  {tab.count}
                </span>
              )}
            </span>
          </button>
        ))}
      </nav>
    </div>
  )
}

function StatCard({
  label,
  value,
  color = 'gray',
  icon,
  trend
}: {
  label: string
  value: number | string
  color?: 'gray' | 'blue' | 'yellow' | 'red' | 'green' | 'purple'
  icon?: React.ReactNode
  trend?: { value: number; label: string }
}) {
  const colorClasses = {
    gray: 'border-gray-200 text-gray-900',
    blue: 'border-blue-200 text-blue-600',
    yellow: 'border-yellow-200 text-yellow-600',
    red: 'border-red-200 text-red-600',
    green: 'border-green-200 text-green-600',
    purple: 'border-purple-200 text-purple-600'
  }

  return (
    <div className={`bg-white rounded-xl border ${colorClasses[color]} p-6`}>
      <div className="flex items-start justify-between">
        <div>
          <div className={`text-sm ${color === 'gray' ? 'text-gray-500' : `text-${color}-600`}`}>
            {label}
          </div>
          <div className={`text-3xl font-bold mt-1 ${colorClasses[color].split(' ')[1]}`}>
            {value}
          </div>
          {trend && (
            <div className={`text-xs mt-1 ${trend.value >= 0 ? 'text-green-600' : 'text-red-600'}`}>
              {trend.value >= 0 ? '+' : ''}{trend.value} {trend.label}
            </div>
          )}
        </div>
        {icon && (
          <div className={`w-10 h-10 rounded-lg flex items-center justify-center bg-${color}-50`}>
            {icon}
          </div>
        )}
      </div>
    </div>
  )
}

function CourseCard({ course, enrollmentCount, onEdit }: { course: Course; enrollmentCount: number; onEdit?: (course: Course) => void }) {
  const categoryInfo = COURSE_CATEGORY_INFO[course.category] || COURSE_CATEGORY_INFO['custom']

  return (
    <div className="relative group">
      <Link href={`/sdk/academy/${course.id}`}>
        <div className="bg-white rounded-xl border-2 p-6 hover:shadow-md transition-all cursor-pointer border-gray-200 hover:border-purple-300">
          <div className="flex items-start justify-between">
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-2 flex-wrap">
                <span className={`px-2 py-1 text-xs rounded-full ${categoryInfo.bgColor} ${categoryInfo.color}`}>
                  {categoryInfo.label}
                </span>
                {course.status === 'published' && (
                  <span className="px-2 py-1 text-xs rounded-full bg-green-100 text-green-700">Veroeffentlicht</span>
                )}
              </div>
              <h3 className="text-lg font-semibold text-gray-900 truncate">{course.title}</h3>
              <p className="text-sm text-gray-500 mt-1 line-clamp-2">{course.description}</p>
              <div className="mt-3 flex items-center gap-4 text-sm text-gray-500">
                <span className="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="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                  </svg>
                  {course.lessons.length} Lektionen
                </span>
                <span className="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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  {course.durationMinutes} Min.
                </span>
                <span className="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="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                  {enrollmentCount} Teilnehmer
                </span>
                <span className="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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  Bestehensgrenze: {course.passingScore}%
                </span>
              </div>
            </div>
            <div className="text-right ml-4 text-gray-500">
              <div className="text-sm font-medium">
                {course.requiredForRoles.includes('all') ? 'Pflicht fuer alle' : `${course.requiredForRoles.length} Rollen`}
              </div>
              <div className="text-xs mt-0.5">
                {new Date(course.updatedAt).toLocaleDateString('de-DE')}
              </div>
            </div>
          </div>
          <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
            <div className="text-sm text-gray-500">
              Erstellt: {new Date(course.createdAt).toLocaleDateString('de-DE')}
            </div>
            <span className="px-3 py-1 text-sm text-purple-600 hover:bg-purple-50 rounded-lg transition-colors">
              Details
            </span>
          </div>
        </div>
      </Link>
      {onEdit && (
        <button
          onClick={(e) => { e.preventDefault(); onEdit(course) }}
          className="absolute top-3 right-3 p-1.5 bg-white rounded-lg shadow border border-gray-200 text-gray-400 hover:text-purple-600 hover:border-purple-300 opacity-0 group-hover:opacity-100 transition-all z-10"
          title="Kurs bearbeiten"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
          </svg>
        </button>
      )}
    </div>
  )
}

function EnrollmentCard({ enrollment, courseName, onEdit, onComplete, onDelete }: {
  enrollment: Enrollment
  courseName: string
  onEdit?: (enrollment: Enrollment) => void
  onComplete?: (id: string) => void
  onDelete?: (id: string) => void
}) {
  const statusInfo = ENROLLMENT_STATUS_INFO[enrollment.status]
  const overdue = isEnrollmentOverdue(enrollment)
  const daysUntil = getDaysUntilDeadline(enrollment.deadline)

  return (
    <div className={`
      bg-white rounded-xl border-2 p-6
      ${overdue ? 'border-red-300' :
        enrollment.status === 'completed' ? 'border-green-200' :
        enrollment.status === 'in_progress' ? 'border-yellow-200' :
        'border-gray-200'
      }
    `}>
      <div className="flex items-start justify-between">
        <div className="flex-1 min-w-0">
          {/* Status Badge */}
          <div className="flex items-center gap-2 mb-2 flex-wrap">
            <span className={`px-2 py-1 text-xs rounded-full ${statusInfo.bgColor} ${statusInfo.color}`}>
              {statusInfo.label}
            </span>
            {overdue && (
              <span className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded-full 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 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
                Ueberfaellig
              </span>
            )}
          </div>

          {/* User Info */}
          <h3 className="text-lg font-semibold text-gray-900 truncate">
            {enrollment.userName}
          </h3>
          <p className="text-sm text-gray-500">{enrollment.userEmail}</p>
          <p className="text-sm text-gray-600 mt-1 font-medium">{courseName}</p>

          {/* Progress Bar */}
          <div className="mt-3">
            <div className="flex items-center justify-between text-sm mb-1">
              <span className="text-gray-500">Fortschritt</span>
              <span className="font-medium text-gray-700">{enrollment.progress}%</span>
            </div>
            <div className="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full transition-all ${
                  enrollment.progress === 100 ? 'bg-green-500' :
                  overdue ? 'bg-red-500' :
                  'bg-purple-500'
                }`}
                style={{ width: `${enrollment.progress}%` }}
              />
            </div>
          </div>
        </div>

        {/* Right Side - Deadline */}
        <div className={`text-right ml-4 ${
          overdue ? 'text-red-600' :
          daysUntil <= 7 ? 'text-orange-600' :
          'text-gray-500'
        }`}>
          <div className="text-sm font-medium">
            {enrollment.status === 'completed'
              ? 'Abgeschlossen'
              : overdue
                ? `${Math.abs(daysUntil)} Tage ueberfaellig`
                : `${daysUntil} Tage verbleibend`
            }
          </div>
          <div className="text-xs mt-0.5">
            Frist: {new Date(enrollment.deadline).toLocaleDateString('de-DE')}
          </div>
        </div>
      </div>

      {/* Footer */}
      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
        <div className="text-sm text-gray-500">
          Gestartet: {new Date(enrollment.startedAt).toLocaleDateString('de-DE')}
          {enrollment.completedAt && (
            <span className="ml-3 text-green-600">
              Abgeschlossen: {new Date(enrollment.completedAt).toLocaleDateString('de-DE')}
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          {enrollment.status === 'in_progress' && onComplete && (
            <button
              onClick={() => onComplete(enrollment.id)}
              className="px-3 py-1 text-xs bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
            >
              Abschliessen
            </button>
          )}
          {onEdit && (
            <button
              onClick={() => onEdit(enrollment)}
              className="px-3 py-1 text-xs bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
            >
              Bearbeiten
            </button>
          )}
          {onDelete && (
            <button
              onClick={() => onDelete(enrollment.id)}
              className="px-3 py-1 text-xs bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors"
            >
              Loeschen
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

function FilterBar({
  selectedCategory,
  selectedStatus,
  onCategoryChange,
  onStatusChange,
  onClear
}: {
  selectedCategory: CourseCategory | 'all'
  selectedStatus: EnrollmentStatus | 'all'
  onCategoryChange: (category: CourseCategory | 'all') => void
  onStatusChange: (status: EnrollmentStatus | 'all') => void
  onClear: () => void
}) {
  const hasFilters = selectedCategory !== 'all' || selectedStatus !== 'all'

  return (
    <div className="flex items-center gap-4 flex-wrap">
      <span className="text-sm text-gray-500">Filter:</span>

      {/* Category Filter */}
      <select
        value={selectedCategory}
        onChange={(e) => onCategoryChange(e.target.value as CourseCategory | 'all')}
        className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
      >
        <option value="all">Alle Kategorien</option>
        {Object.entries(COURSE_CATEGORY_INFO).map(([cat, info]) => (
          <option key={cat} value={cat}>{info.label}</option>
        ))}
      </select>

      {/* Enrollment Status Filter */}
      <select
        value={selectedStatus}
        onChange={(e) => onStatusChange(e.target.value as EnrollmentStatus | 'all')}
        className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
      >
        <option value="all">Alle Status</option>
        {Object.entries(ENROLLMENT_STATUS_INFO).map(([status, info]) => (
          <option key={status} value={status}>{info.label}</option>
        ))}
      </select>

      {/* Clear Filters */}
      {hasFilters && (
        <button
          onClick={onClear}
          className="px-3 py-1.5 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
        >
          Filter zuruecksetzen
        </button>
      )}
    </div>
  )
}

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

export default function AcademyPage() {
  const { state } = useSDK()
  const [activeTab, setActiveTab] = useState<TabId>('overview')
  const [courses, setCourses] = useState<Course[]>([])
  const [enrollments, setEnrollments] = useState<Enrollment[]>([])
  const [certificates, setCertificates] = useState<Certificate[]>([])
  const [statistics, setStatistics] = useState<AcademyStatistics | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isGenerating, setIsGenerating] = useState(false)
  const [generateResult, setGenerateResult] = useState<{ generated: number; skipped: number; errors: string[] } | null>(null)

  // Modal states
  const [editingEnrollment, setEditingEnrollment] = useState<Enrollment | null>(null)
  const [editingCourse, setEditingCourse] = useState<Course | null>(null)
  const [settingsSaved, setSettingsSaved] = useState(false)

  // Filters
  const [selectedCategory, setSelectedCategory] = useState<CourseCategory | 'all'>('all')
  const [selectedStatus, setSelectedStatus] = useState<EnrollmentStatus | 'all'>('all')
  const [certSearch, setCertSearch] = useState('')

  // Load data from SDK backend
  useEffect(() => {
    loadData()
  }, [])

  // Calculate tab counts
  const tabCounts = useMemo(() => {
    return {
      courses: courses.length,
      enrollments: enrollments.filter(e => e.status !== 'completed').length,
      certificates: certificates.length || enrollments.filter(e => e.certificateId).length,
      overdue: enrollments.filter(e => isEnrollmentOverdue(e)).length
    }
  }, [courses, enrollments, certificates])

  // Filtered courses
  const filteredCourses = useMemo(() => {
    let filtered = [...courses]

    if (selectedCategory !== 'all') {
      filtered = filtered.filter(c => c.category === selectedCategory)
    }

    return filtered.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
  }, [courses, selectedCategory])

  // Filtered enrollments
  const filteredEnrollments = useMemo(() => {
    let filtered = [...enrollments]

    if (selectedStatus !== 'all') {
      filtered = filtered.filter(e => e.status === selectedStatus)
    }

    // Sort: overdue first, then by deadline
    return filtered.sort((a, b) => {
      const aOverdue = isEnrollmentOverdue(a) ? -1 : 0
      const bOverdue = isEnrollmentOverdue(b) ? -1 : 0
      if (aOverdue !== bOverdue) return aOverdue - bOverdue
      return getDaysUntilDeadline(a.deadline) - getDaysUntilDeadline(b.deadline)
    })
  }, [enrollments, selectedStatus])

  // Enrollment counts per course
  const enrollmentCountByCourseId = useMemo(() => {
    const counts: Record<string, number> = {}
    enrollments.forEach(e => {
      counts[e.courseId] = (counts[e.courseId] || 0) + 1
    })
    return counts
  }, [enrollments])

  // Course name lookup
  const courseNameById = useMemo(() => {
    const map: Record<string, string> = {}
    courses.forEach(c => { map[c.id] = c.title })
    return map
  }, [courses])

  const tabs: Tab[] = [
    { id: 'overview', label: 'Uebersicht' },
    { id: 'courses', label: 'Kurse', count: tabCounts.courses, countColor: 'bg-blue-100 text-blue-600' },
    { id: 'enrollments', label: 'Einschreibungen', count: tabCounts.enrollments, countColor: 'bg-yellow-100 text-yellow-600' },
    { id: 'certificates', label: 'Zertifikate', count: tabCounts.certificates, countColor: 'bg-green-100 text-green-600' },
    { id: 'settings', label: 'Einstellungen' }
  ]

  const stepInfo = STEP_EXPLANATIONS['academy']

  const loadData = async () => {
    setIsLoading(true)
    try {
      const [data, certs] = await Promise.allSettled([
        fetchSDKAcademyList(),
        fetchCertificates(),
      ])
      if (data.status === 'fulfilled') {
        setCourses(data.value.courses)
        setEnrollments(data.value.enrollments)
        setStatistics(data.value.statistics)
      } else {
        console.error('Failed to load Academy data:', data.reason)
      }
      if (certs.status === 'fulfilled') {
        setCertificates(certs.value)
      }
    } finally {
      setIsLoading(false)
    }
  }

  const handleCompleteEnrollment = async (id: string) => {
    try {
      await completeEnrollment(id)
      await loadData()
    } catch (e) {
      console.error('Failed to complete enrollment:', e)
    }
  }

  const handleDeleteEnrollment = async (id: string) => {
    if (!window.confirm('Einschreibung wirklich loeschen?')) return
    try {
      await deleteEnrollment(id)
      await loadData()
    } catch (e) {
      console.error('Failed to delete enrollment:', e)
    }
  }

  const handleGenerateAll = async () => {
    setIsGenerating(true)
    setGenerateResult(null)
    try {
      const result = await generateAllCourses()
      setGenerateResult({ generated: result.generated, skipped: result.skipped, errors: result.errors || [] })
      // Reload data to show new courses
      await loadData()
    } catch (error) {
      console.error('Failed to generate courses:', error)
      setGenerateResult({ generated: 0, skipped: 0, errors: [error instanceof Error ? error.message : 'Fehler bei der Generierung'] })
    } finally {
      setIsGenerating(false)
    }
  }

  const clearFilters = () => {
    setSelectedCategory('all')
    setSelectedStatus('all')
  }

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="academy"
        title={stepInfo?.title || 'Compliance Academy'}
        description={stepInfo?.description || 'E-Learning Plattform fuer Compliance-Schulungen'}
        explanation={stepInfo?.explanation}
        tips={stepInfo?.tips}
      >
        <div className="flex gap-2">
          <button
            onClick={handleGenerateAll}
            disabled={isGenerating}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50"
          >
            {isGenerating ? (
              <svg className="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
            ) : (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            )}
            {isGenerating ? 'Generiere...' : 'Alle Kurse generieren'}
          </button>
          <Link
            href="/sdk/academy/new"
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            <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>
            Kurs erstellen
          </Link>
        </div>
      </StepHeader>

      {/* Generation Result */}
      {generateResult && (
        <div className={`p-4 rounded-lg border ${generateResult.errors.length > 0 ? 'bg-yellow-50 border-yellow-200' : 'bg-green-50 border-green-200'}`}>
          <div className="flex items-center gap-4 text-sm">
            <span className="text-green-700 font-medium">{generateResult.generated} Kurse generiert</span>
            <span className="text-gray-500">{generateResult.skipped} uebersprungen</span>
            {generateResult.errors.length > 0 && (
              <span className="text-red-600">{generateResult.errors.length} Fehler</span>
            )}
          </div>
          {generateResult.errors.length > 0 && (
            <div className="mt-2 text-xs text-red-600">
              {generateResult.errors.map((err, i) => <div key={i}>{err}</div>)}
            </div>
          )}
        </div>
      )}

      {/* Tab Navigation */}
      <TabNavigation
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
      />

      {/* Loading State */}
      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <svg className="animate-spin w-8 h-8 text-purple-600" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
          </svg>
        </div>
      ) : activeTab === 'settings' ? (
        /* Settings Tab — localStorage-basiert */
        <SettingsTab onSaved={() => { setSettingsSaved(true); setTimeout(() => setSettingsSaved(false), 2000) }} saved={settingsSaved} />
      ) : activeTab === 'certificates' ? (
        /* Certificates Tab */
        <div className="space-y-4">
          {/* Stats */}
          <div className="grid grid-cols-3 gap-4">
            {(() => {
              const now = new Date()
              const total = certificates.length
              const valid = certificates.filter(c => new Date(c.validUntil) > now).length
              const expired = certificates.filter(c => new Date(c.validUntil) <= now).length
              return (
                <>
                  <div className="bg-white rounded-xl border border-gray-200 p-4 text-center">
                    <div className="text-2xl font-bold text-gray-900">{total}</div>
                    <div className="text-sm text-gray-500">Gesamt</div>
                  </div>
                  <div className="bg-white rounded-xl border border-green-200 p-4 text-center">
                    <div className="text-2xl font-bold text-green-600">{valid}</div>
                    <div className="text-sm text-gray-500">Gueltig</div>
                  </div>
                  <div className="bg-white rounded-xl border border-red-200 p-4 text-center">
                    <div className="text-2xl font-bold text-red-600">{expired}</div>
                    <div className="text-sm text-gray-500">Abgelaufen</div>
                  </div>
                </>
              )
            })()}
          </div>

          {/* Search */}
          <div>
            <input
              type="text"
              placeholder="Nach Mitarbeiter oder Kurs suchen..."
              value={certSearch}
              onChange={e => setCertSearch(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>

          {/* Table */}
          {certificates.length === 0 ? (
            <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
              <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
                <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-gray-900">Noch keine Zertifikate ausgestellt</h3>
              <p className="mt-2 text-gray-500">Zertifikate werden automatisch nach Kursabschluss generiert.</p>
            </div>
          ) : (
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 border-b border-gray-200">
                  <tr>
                    <th className="text-left px-4 py-3 font-medium text-gray-700">Mitarbeiter</th>
                    <th className="text-left px-4 py-3 font-medium text-gray-700">Kurs</th>
                    <th className="text-left px-4 py-3 font-medium text-gray-700">Ausgestellt am</th>
                    <th className="text-left px-4 py-3 font-medium text-gray-700">Gueltig bis</th>
                    <th className="text-center px-4 py-3 font-medium text-gray-700">Status</th>
                    <th className="text-center px-4 py-3 font-medium text-gray-700">Aktionen</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {certificates
                    .filter(c =>
                      !certSearch ||
                      c.userName.toLowerCase().includes(certSearch.toLowerCase()) ||
                      c.courseName.toLowerCase().includes(certSearch.toLowerCase())
                    )
                    .map(cert => <CertificateRow key={cert.id} cert={cert} />)
                  }
                </tbody>
              </table>
            </div>
          )}
        </div>
      ) : (
        <>
          {/* Statistics (Overview Tab) */}
          {activeTab === 'overview' && statistics && (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <StatCard
                label="Kurse gesamt"
                value={statistics.totalCourses}
                color="gray"
              />
              <StatCard
                label="Aktive Teilnehmer"
                value={(statistics.byStatus?.in_progress || 0) + (statistics.byStatus?.not_started || 0)}
                color="blue"
              />
              <StatCard
                label="Abschlussrate"
                value={`${statistics.completionRate}%`}
                color="green"
              />
              <StatCard
                label="Ueberfaellig"
                value={statistics.overdueCount}
                color={statistics.overdueCount > 0 ? 'red' : 'green'}
              />
            </div>
          )}

          {/* Overdue Alert */}
          {tabCounts.overdue > 0 && (
            <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-center gap-4">
              <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0">
                <svg className="w-5 h-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <div className="flex-1">
                <h4 className="font-medium text-red-800">
                  Achtung: {tabCounts.overdue} ueberfaellige Schulung(en)
                </h4>
                <p className="text-sm text-red-600">
                  Mitarbeiter haben Pflichtschulungen nicht fristgerecht abgeschlossen. Handeln Sie umgehend.
                </p>
              </div>
              <button
                onClick={() => {
                  setActiveTab('enrollments')
                  setSelectedStatus('all')
                }}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm font-medium"
              >
                Anzeigen
              </button>
            </div>
          )}

          {/* Info Box (Overview Tab) */}
          {activeTab === 'overview' && (
            <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
              <div className="flex items-start gap-3">
                <svg className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <div>
                  <h4 className="font-medium text-blue-800">Schulungspflicht nach Art. 39 DSGVO</h4>
                  <p className="text-sm text-blue-600 mt-1">
                    Gemaess Art. 39 Abs. 1 lit. b DSGVO gehoert die Sensibilisierung und Schulung
                    der an den Verarbeitungsvorgaengen beteiligten Mitarbeiter zu den Aufgaben des
                    Datenschutzbeauftragten. Nachweisbare Compliance-Schulungen sind Pflicht und
                    sollten mindestens jaehrlich aufgefrischt werden.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Filters */}
          <FilterBar
            selectedCategory={selectedCategory}
            selectedStatus={selectedStatus}
            onCategoryChange={setSelectedCategory}
            onStatusChange={setSelectedStatus}
            onClear={clearFilters}
          />

          {/* Courses Tab */}
          {(activeTab === 'overview' || activeTab === 'courses') && (
            <div className="space-y-4">
              {activeTab === 'courses' && (
                <h2 className="text-lg font-semibold text-gray-900">Kurse ({filteredCourses.length})</h2>
              )}
              {filteredCourses.map(course => (
                <CourseCard
                  key={course.id}
                  course={course}
                  enrollmentCount={enrollmentCountByCourseId[course.id] || 0}
                  onEdit={setEditingCourse}
                />
              ))}
            </div>
          )}

          {/* Enrollments Tab */}
          {activeTab === 'enrollments' && (
            <div className="space-y-4">
              <h2 className="text-lg font-semibold text-gray-900">Einschreibungen ({filteredEnrollments.length})</h2>
              {filteredEnrollments.map(enrollment => (
                <EnrollmentCard
                  key={enrollment.id}
                  enrollment={enrollment}
                  courseName={courseNameById[enrollment.courseId] || 'Unbekannter Kurs'}
                  onEdit={setEditingEnrollment}
                  onComplete={handleCompleteEnrollment}
                  onDelete={handleDeleteEnrollment}
                />
              ))}
            </div>
          )}

          {/* Empty States */}
          {activeTab === 'courses' && filteredCourses.length === 0 && (
            <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
              <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
                <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-gray-900">Keine Kurse gefunden</h3>
              <p className="mt-2 text-gray-500">
                {selectedCategory !== 'all'
                  ? 'Passen Sie die Filter an oder'
                  : 'Es sind noch keine Kurse vorhanden.'
                }
              </p>
              {selectedCategory !== 'all' ? (
                <button
                  onClick={clearFilters}
                  className="mt-4 px-4 py-2 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors"
                >
                  Filter zuruecksetzen
                </button>
              ) : (
                <Link
                  href="/sdk/academy/new"
                  className="mt-4 inline-flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
                >
                  <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>
                  Ersten Kurs erstellen
                </Link>
              )}
            </div>
          )}

          {activeTab === 'enrollments' && filteredEnrollments.length === 0 && (
            <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
              <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
                <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-gray-900">Keine Einschreibungen gefunden</h3>
              <p className="mt-2 text-gray-500">
                {selectedStatus !== 'all'
                  ? 'Passen Sie die Filter an.'
                  : 'Es sind noch keine Mitarbeiter in Kurse eingeschrieben.'
                }
              </p>
              {selectedStatus !== 'all' && (
                <button
                  onClick={clearFilters}
                  className="mt-4 px-4 py-2 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors"
                >
                  Filter zuruecksetzen
                </button>
              )}
            </div>
          )}
        </>
      )}

      {/* Enrollment Edit Modal */}
      {editingEnrollment && (
        <EnrollmentEditModal
          enrollment={editingEnrollment}
          onClose={() => setEditingEnrollment(null)}
          onSaved={() => { setEditingEnrollment(null); loadData() }}
        />
      )}

      {/* Course Edit Modal */}
      {editingCourse && (
        <CourseEditModal
          course={editingCourse}
          onClose={() => setEditingCourse(null)}
          onSaved={() => { setEditingCourse(null); loadData() }}
        />
      )}
    </div>
  )
}

// =============================================================================
// CERTIFICATE ROW COMPONENT
// =============================================================================

function CertificateRow({ cert }: { cert: Certificate }) {
  const now = new Date()
  const validUntil = new Date(cert.validUntil)
  const daysLeft = Math.ceil((validUntil.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  const isExpired = daysLeft <= 0
  const isExpiringSoon = daysLeft > 0 && daysLeft <= 30

  return (
    <tr className="hover:bg-gray-50">
      <td className="px-4 py-3 font-medium text-gray-900">{cert.userName}</td>
      <td className="px-4 py-3 text-gray-600">{cert.courseName}</td>
      <td className="px-4 py-3 text-gray-500">{new Date(cert.issuedAt).toLocaleDateString('de-DE')}</td>
      <td className="px-4 py-3 text-gray-500">{validUntil.toLocaleDateString('de-DE')}</td>
      <td className="px-4 py-3 text-center">
        {isExpired ? (
          <span className="px-2 py-1 text-xs rounded-full bg-red-100 text-red-700">Abgelaufen</span>
        ) : isExpiringSoon ? (
          <span className="px-2 py-1 text-xs rounded-full bg-orange-100 text-orange-700">Laeuft bald ab</span>
        ) : (
          <span className="px-2 py-1 text-xs rounded-full bg-green-100 text-green-700">Gueltig</span>
        )}
      </td>
      <td className="px-4 py-3 text-center">
        {cert.pdfUrl ? (
          <a
            href={cert.pdfUrl}
            download
            target="_blank"
            rel="noopener noreferrer"
            className="px-3 py-1 text-xs bg-purple-600 text-white rounded hover:bg-purple-700 transition-colors"
          >
            PDF Download
          </a>
        ) : (
          <span className="px-3 py-1 text-xs bg-gray-100 text-gray-400 rounded cursor-not-allowed">
            Nicht verfuegbar
          </span>
        )}
      </td>
    </tr>
  )
}

// =============================================================================
// ENROLLMENT EDIT MODAL
// =============================================================================

function EnrollmentEditModal({ enrollment, onClose, onSaved }: {
  enrollment: Enrollment
  onClose: () => void
  onSaved: () => void
}) {
  const [deadline, setDeadline] = useState(enrollment.deadline ? enrollment.deadline.split('T')[0] : '')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSave = async () => {
    setSaving(true)
    setError(null)
    try {
      await updateEnrollment(enrollment.id, { deadline: new Date(deadline).toISOString() })
      onSaved()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler beim Speichern')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900">Einschreibung bearbeiten</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-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>
        <div className="p-6 space-y-4">
          <div>
            <p className="text-sm text-gray-500">Teilnehmer: <span className="font-medium text-gray-900">{enrollment.userName}</span></p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Deadline</label>
            <input
              type="date"
              value={deadline}
              onChange={e => setDeadline(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>
          {error && <p className="text-sm text-red-600">{error}</p>}
        </div>
        <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Abbrechen
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !deadline}
            className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
          >
            {saving ? 'Speichern...' : 'Speichern'}
          </button>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// COURSE EDIT MODAL
// =============================================================================

function CourseEditModal({ course, onClose, onSaved }: {
  course: Course
  onClose: () => void
  onSaved: () => void
}) {
  const [title, setTitle] = useState(course.title)
  const [description, setDescription] = useState(course.description)
  const [category, setCategory] = useState<CourseCategory>(course.category)
  const [durationMinutes, setDurationMinutes] = useState(course.durationMinutes)
  const [passingScore, setPassingScore] = useState(course.passingScore ?? 70)
  const [status, setStatus] = useState<'draft' | 'published'>(course.status ?? 'draft')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSave = async () => {
    setSaving(true)
    setError(null)
    try {
      await updateCourse(course.id, { title, description, category, durationMinutes, passingScore, status })
      onSaved()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler beim Speichern')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900">Kurs bearbeiten</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-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>
        <div className="p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Titel</label>
            <input
              type="text"
              value={title}
              onChange={e => setTitle(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
            <textarea
              value={description}
              onChange={e => setDescription(e.target.value)}
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Kategorie</label>
              <select
                value={category}
                onChange={e => setCategory(e.target.value as CourseCategory)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
              >
                {Object.entries(COURSE_CATEGORY_INFO).map(([key, info]) => (
                  <option key={key} value={key}>{info.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
              <select
                value={status}
                onChange={e => setStatus(e.target.value as 'draft' | 'published')}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
              >
                <option value="draft">Entwurf</option>
                <option value="published">Veroeffentlicht</option>
              </select>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Dauer (Minuten)</label>
              <input
                type="number"
                min={1}
                value={durationMinutes}
                onChange={e => setDurationMinutes(Number(e.target.value))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Bestehensgrenze (%)</label>
              <input
                type="number"
                min={0}
                max={100}
                value={passingScore}
                onChange={e => setPassingScore(Number(e.target.value))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
              />
            </div>
          </div>
          {error && <p className="text-sm text-red-600">{error}</p>}
        </div>
        <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Abbrechen
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !title}
            className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
          >
            {saving ? 'Speichern...' : 'Aenderungen speichern'}
          </button>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// SETTINGS TAB
// =============================================================================

function SettingsTab({ onSaved, saved }: { onSaved: () => void; saved: boolean }) {
  const SETTINGS_KEY = 'bp_academy_settings'

  const loadSettings = () => {
    try {
      const raw = localStorage.getItem(SETTINGS_KEY)
      if (raw) return JSON.parse(raw)
    } catch { /* ignore */ }
    return {}
  }

  const defaults = { emailReminders: true, reminderDays: 7, defaultPassingScore: 70, defaultValidityDays: 365 }
  const saved_settings = loadSettings()
  const [emailReminders, setEmailReminders] = useState<boolean>(saved_settings.emailReminders ?? defaults.emailReminders)
  const [reminderDays, setReminderDays] = useState<number>(saved_settings.reminderDays ?? defaults.reminderDays)
  const [defaultPassingScore, setDefaultPassingScore] = useState<number>(saved_settings.defaultPassingScore ?? defaults.defaultPassingScore)
  const [defaultValidityDays, setDefaultValidityDays] = useState<number>(saved_settings.defaultValidityDays ?? defaults.defaultValidityDays)

  const handleSave = () => {
    localStorage.setItem(SETTINGS_KEY, JSON.stringify({ emailReminders, reminderDays, defaultPassingScore, defaultValidityDays }))
    onSaved()
  }

  return (
    <div className="space-y-6 max-w-2xl">
      {/* Notifications */}
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <h3 className="text-base font-semibold text-gray-900 mb-4">Benachrichtigungen</h3>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-gray-700">E-Mail-Erinnerung bei ueberfaelligen Kursen</div>
              <div className="text-xs text-gray-500">Mitarbeiter per E-Mail an ausstehende Schulungen erinnern</div>
            </div>
            <button
              onClick={() => setEmailReminders(!emailReminders)}
              className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${emailReminders ? 'bg-purple-600' : 'bg-gray-200'}`}
            >
              <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${emailReminders ? 'translate-x-6' : 'translate-x-1'}`} />
            </button>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Tage vor Ablauf erinnern</label>
            <input
              type="number"
              min={1}
              max={90}
              value={reminderDays}
              onChange={e => setReminderDays(Number(e.target.value))}
              className="w-32 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>
        </div>
      </div>

      {/* Course Defaults */}
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <h3 className="text-base font-semibold text-gray-900 mb-4">Standard-Einstellungen fuer neue Kurse</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Standard-Bestehensgrenze (%)</label>
            <input
              type="number"
              min={0}
              max={100}
              value={defaultPassingScore}
              onChange={e => setDefaultPassingScore(Number(e.target.value))}
              className="w-32 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Gueltigkeitsdauer (Tage)</label>
            <input
              type="number"
              min={1}
              value={defaultValidityDays}
              onChange={e => setDefaultValidityDays(Number(e.target.value))}
              className="w-32 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>
        </div>
      </div>

      {/* Info */}
      <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
        <div className="flex items-start gap-3">
          <svg className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <p className="text-sm text-blue-700">
            Zertifikate werden automatisch nach erfolgreichem Kursabschluss generiert. Die Gueltigkeitsdauer gilt ab dem Ausstellungsdatum.
          </p>
        </div>
      </div>

      <button
        onClick={handleSave}
        className={`px-6 py-2 rounded-lg text-sm font-medium transition-colors ${
          saved ? 'bg-green-600 text-white' : 'bg-purple-600 text-white hover:bg-purple-700'
        }`}
      >
        {saved ? 'Gespeichert ✓' : 'Einstellungen speichern'}
      </button>
    </div>
  )
}
