<script lang="ts">
	import { onMount } from 'svelte';
	import { authStore } from '$lib/stores/auth.svelte.js';
	import { api, type TimetableEntry, type CreateTimetableEntryDto, type User, type Grade, type CreateGradeDto, type Subject, type Room, type FileEntity } from '$lib/api';
	import { goto } from '$app/navigation';
	import FileUploader from '$lib/components/FileUploader.svelte';

	let timetableEntries = $state<TimetableEntry[]>([]);
	let teachers = $state<User[]>([]);
	let subjects = $state<Subject[]>([]);
	let rooms = $state<Room[]>([]);
	let isLoading = $state(true);
	let error = $state<string | null>(null);
	let showAddModal = $state(false);
	let showEditModal = $state(false);
	let showDeleteConfirm = $state(false);
	let showDetailModal = $state(false);
	let editingEntry = $state<TimetableEntry | null>(null);
	let entryToDelete = $state<TimetableEntry | null>(null);
	let selectedEntry = $state<TimetableEntry | null>(null);
	let activeTab = $state<'files' | 'feedback' | 'grades'>('files');
	let modalError = $state<string | null>(null);
	let editModalError = $state<string | null>(null);

	// Files State
	let lessonFiles = $state<FileEntity[]>([]);
	let filesLoading = $state(false);
	let filesError = $state<string | null>(null);

	// Wochennavigation
	let currentWeek = $state(getCurrentWeekNumber());
	let currentYear = $state(new Date().getFullYear());

	// Feedback Form State
	let feedbackOverallRating = $state(5);
	let feedbackClarity = $state(5);
	let feedbackPace = $state(5);
	let feedbackInteraction = $state(5);
	let feedbackMaterials = $state(5);
	let feedbackAtmosphere = $state(5);
	let feedbackWhatWasGood = $state('');
	let feedbackWhatCanImprove = $state('');
	let feedbackAdditionalComments = $state('');
	let feedbackIsAnonymous = $state(false);
	let feedbackAllowTeacherResponse = $state(true);
	let feedbackSubmitting = $state(false);
	let feedbackSuccess = $state(false);
	let feedbackAlreadySubmitted = $state(false);
	let existingFeedbackList = $state<any[]>([]);
	let feedbackError = $state<string | null>(null);

	// Grades State
	let grades = $state<Grade[]>([]);
	let gradesLoading = $state(false);
	let gradesError = $state<string | null>(null);
	let showGradeForm = $state(false);
	let editingGrade = $state<Grade | null>(null);

	// Grade Form State
	let gradeFormStudentId = $state(0);
	let gradeFormGrade = $state(1.0);
	let gradeFormGradeType = $state('Mündlich');
	let gradeFormWeight = $state(1.0);
	let gradeFormTitle = $state('');
	let gradeFormDescription = $state('');
	let gradeFormMaxPoints = $state<number | undefined>(undefined);
	let gradeFormAchievedPoints = $state<number | undefined>(undefined);
	let gradeFormDate = $state('');
	let gradeFormSubmitting = $state(false);
	let students = $state<User[]>([]);

	// Form State
	let formDayOfWeek = $state(1);
	let formStartTime = $state('');
	let formEndTime = $state('');
	let formSubjectId = $state(0);
    let formSubjectInput = $state('');
	let formTeacherId = $state<number | undefined>(undefined);
	let formRoomId = $state<number | undefined>(undefined);
    let formRoomInput = $state('');
	let formIsRecurring = $state(true);
	let formSelectedDate = $state('');

	const DAYS = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag'];

	// Berechne aktuelle Kalenderwoche (ISO 8601)
	function getCurrentWeekNumber(): number {
		const date = new Date();
		const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
		const dayNum = d.getUTCDay() || 7;
		d.setUTCDate(d.getUTCDate() + 4 - dayNum);
		const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
		return Math.ceil((((d.getTime() - yearStart.getTime()) / 86400000) + 1) / 7);
	}

	// Berechne Datum für einen bestimmten Wochentag in der aktuellen Woche
	function getDateForDay(dayOfWeek: number, weekNumber: number, year: number): Date {
		// Finde den ersten Donnerstag des Jahres (ISO 8601)
		const jan4 = new Date(Date.UTC(year, 0, 4));
		const jan4DayOfWeek = jan4.getUTCDay() || 7;
		const firstThursday = new Date(jan4);
		firstThursday.setUTCDate(jan4.getUTCDate() - jan4DayOfWeek + 4);

		// Berechne das Datum der gewünschten Woche
		const targetWeekStart = new Date(firstThursday);
		targetWeekStart.setUTCDate(firstThursday.getUTCDate() + (weekNumber - 1) * 7 - 3); // Montag der Woche

		// Füge Tage hinzu um zum gewünschten Wochentag zu kommen
		const targetDate = new Date(targetWeekStart);
		targetDate.setUTCDate(targetWeekStart.getUTCDate() + dayOfWeek - 1);

		return targetDate;
	}

	// Formatiere Datum als DD.MM
	function formatDate(date: Date): string {
		const day = date.getUTCDate().toString().padStart(2, '0');
		const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');
		return `${day}.${month}`;
	}

	// Navigation zwischen Wochen
	function previousWeek() {
		currentWeek--;
		if (currentWeek < 1) {
			currentWeek = 52;
			currentYear--;
		}
		loadTimetable();
	}

	function nextWeek() {
		currentWeek++;
		if (currentWeek > 52) {
			currentWeek = 1;
			currentYear++;
		}
		loadTimetable();
	}

	function goToCurrentWeek() {
		currentWeek = getCurrentWeekNumber();
		currentYear = new Date().getFullYear();
		loadTimetable();
	}

	onMount(async () => {
		if (!authStore.isAuthenticated) {
			goto('/login');
			return;
		}

		await Promise.all([
			loadTimetable(),
			loadTeachers(),
			loadSubjects(),
			loadRooms()
		]);
	});

	async function loadTimetable() {
		isLoading = true;
		error = null;

		const response = await api.getTimetable(currentWeek, currentYear);

		if (response.data) {
			timetableEntries = response.data;
		} else {
			error = response.error || 'Fehler beim Laden des Stundenplans';
		}

		isLoading = false;
	}

	async function loadTeachers() {
		const response = await api.getTeachers();

		if (response.data) {
			teachers = response.data;
		} else {
			console.warn('Fehler beim Laden der Lehrer:', response.error);
		}
	}

	async function loadSubjects() {
		const response = await api.getSubjects();

		if (response.data) {
			subjects = response.data;
		} else {
			console.warn('Fehler beim Laden der Fächer:', response.error);
		}
	}

	async function loadRooms() {
		const response = await api.getRooms();

		if (response.data) {
			rooms = response.data;
		} else {
			console.warn('Fehler beim Laden der Räume:', response.error);
		}
	}

	function openAddModal() {
		resetForm();
		modalError = null;
		showAddModal = true;
	}

	function closeAddModal() {
		showAddModal = false;
		modalError = null;
		resetForm();
	}

	function openEditModal(entry: TimetableEntry) {
		editingEntry = entry;
		formDayOfWeek = entry.dayOfWeek;
		formStartTime = entry.startTime;
		formEndTime = entry.endTime;
		formSubjectId = entry.subject.id;
        formSubjectInput = entry.subject.name;
		formTeacherId = entry.teacher?.id;
		formRoomId = entry.room?.id;
        formRoomInput = entry.room?.number || '';
		formIsRecurring = entry.isRecurring ?? true;

		// Wenn nicht wiederkehrend und Woche/Jahr vorhanden, berechne das Datum
		if (!formIsRecurring && entry.weekNumber && entry.year) {
			const date = getDateForDay(entry.dayOfWeek, entry.weekNumber, entry.year);
			formSelectedDate = formatDateForInput(date);
		} else {
			formSelectedDate = '';
		}

		editModalError = null;
		showEditModal = true;
	}

	function closeEditModal() {
		showEditModal = false;
		editingEntry = null;
		editModalError = null;
		resetForm();
	}

	function openDeleteConfirm(entry: TimetableEntry) {
		entryToDelete = entry;
		showDeleteConfirm = true;
	}

	function closeDeleteConfirm() {
		showDeleteConfirm = false;
		entryToDelete = null;
	}

	async function loadLessonFiles(entry: TimetableEntry) {
		filesLoading = true;
		filesError = null;
		const res = await api.getLessonFiles(entry.id);
		if (res.data) {
			lessonFiles = res.data;
		} else {
			filesError = res.error || 'Fehler beim Laden der Dateien';
		}
		filesLoading = false;
	}

	async function deleteFile(id: number) {
		if (!confirm('Möchten Sie diese Datei wirklich löschen?')) return;
		
		const res = await api.deleteFile(id);
		if (res.data?.success) {
			lessonFiles = lessonFiles.filter(f => f.id !== id);
		} else {
			alert(res.error || 'Fehler beim Löschen der Datei');
		}
	}

	function formatFileSize(bytes: number) {
		if (bytes === 0) return '0 Bytes';
		const k = 1024;
		const sizes = ['Bytes', 'KB', 'MB', 'GB'];
		const i = Math.floor(Math.log(bytes) / Math.log(k));
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
	}

	async function toggleStudentUploads(entry: TimetableEntry) {
		if (!authStore.isTeacher) return;
		
		const updated = !entry.allowStudentUploads;
		// Optimistic update
		const originalValue = entry.allowStudentUploads;
		entry.allowStudentUploads = updated;

		const res = await api.updateTimetableEntry(entry.id, { allowStudentUploads: updated });
		
		if (!res.data) {
			// Revert on error
			entry.allowStudentUploads = originalValue;
			alert('Fehler beim Aktualisieren der Einstellungen');
		}
	}

	async function openDetailModal(entry: TimetableEntry) {
		selectedEntry = entry;
		activeTab = 'files';
		showDetailModal = true;

		// Lade Lehrerliste (wichtig für Schüler, um teacherId zu ermitteln)
		if (teachers.length === 0) {
			await loadTeachers();
		}

		// Lade existierendes Feedback für diese Stunde
		await loadFeedbackForLesson(entry);

		// Lade Dateien für diese Stunde
		await loadLessonFiles(entry);

		// Lade Noten für diese Stunde
		await loadGradesForLesson(entry);

		// Lade Schülerliste für Lehrer
		if (authStore.isTeacher) {
			await loadStudents();
		}
	}

	async function loadFeedbackForLesson(entry: TimetableEntry) {
		if (!authStore.user) return;

		// Verwende die TimetableEntry ID direkt
		const lessonId = entry.id;

		// Für Lehrer: Lade alle eigenen Feedbacks und filtere
		// Für Schüler: Lade nur Feedbacks für diese spezifische Stunde
		const response = authStore.isTeacher
			? await api.getFeedback()
			: await api.getFeedbackByLesson(lessonId.toString());

		if (response.data) {
			// Filtere Feedback für diese spezifische Stunde anhand der lessonId
			const feedbackForThisLesson = authStore.isTeacher
				? response.data.filter((fb: any) => fb.lessonId === lessonId)
				: response.data;

			existingFeedbackList = feedbackForThisLesson;

			// Prüfe, ob der aktuelle Benutzer bereits Feedback gegeben hat
			if (!authStore.isTeacher) {
				feedbackAlreadySubmitted = feedbackForThisLesson.some(
					(fb: any) => fb.studentId === authStore.user!.id
				);
			}
		}
	}

	function closeDetailModal() {
		showDetailModal = false;
		selectedEntry = null;
		activeTab = 'files';
		lessonFiles = [];
		filesError = null;
		resetFeedbackForm();
		existingFeedbackList = [];
		feedbackAlreadySubmitted = false;
		resetGradeForm();
		grades = [];
		gradesError = null;
		showGradeForm = false;
		editingGrade = null;
	}

	async function loadGradesForLesson(entry: TimetableEntry) {
		if (!authStore.user) return;

		gradesLoading = true;
		gradesError = null;

		const response = await api.getGradesByTimetableEntry(entry.id, currentWeek, currentYear);

		if (response.data) {
			grades = response.data;
		} else {
			gradesError = response.error || 'Fehler beim Laden der Noten';
		}

		gradesLoading = false;
	}

	async function loadStudents() {
		const response = await api.getUsers();

		if (response.data) {
			students = response.data.filter(u => u.role === 'Student');
		} else {
			console.warn('Fehler beim Laden der Schüler:', response.error);
		}
	}

	function openGradeForm() {
		resetGradeForm();
		showGradeForm = true;
		editingGrade = null;
	}

	function openEditGradeForm(grade: Grade) {
		editingGrade = grade;
		gradeFormStudentId = grade.studentId;
		gradeFormGrade = grade.grade;
		gradeFormGradeType = grade.gradeType;
		gradeFormWeight = grade.weight || 1.0;
		gradeFormDescription = grade.description || '';
		showGradeForm = true;
	}

	function closeGradeForm() {
		showGradeForm = false;
		editingGrade = null;
		resetGradeForm();
	}

	function resetGradeForm() {
		gradeFormStudentId = 0;
		gradeFormGrade = 1.0;
		gradeFormGradeType = 'Mündlich';
		gradeFormWeight = 1.0;
		gradeFormTitle = '';
		gradeFormDescription = '';
		gradeFormMaxPoints = undefined;
		gradeFormAchievedPoints = undefined;
		gradeFormDate = '';
	}

	async function handleGradeSubmit(e: Event) {
		e.preventDefault();

		if (!selectedEntry || !authStore.user) return;

		gradeFormSubmitting = true;
		gradesError = null;

		// Verwende das aktuelle Datum für die Note
		const currentDate = new Date().toISOString().split('T')[0];

		const gradeData: CreateGradeDto = {
			studentId: gradeFormStudentId,
			timetableEntryId: selectedEntry.id,
			weekNumber: currentWeek,
			year: currentYear,
			grade: gradeFormGrade,
			gradeType: gradeFormGradeType,
			weight: gradeFormWeight,
			title: gradeFormTitle || undefined,
			description: gradeFormDescription || undefined,
			maxPoints: gradeFormMaxPoints,
			achievedPoints: gradeFormAchievedPoints,
			date: currentDate,
			teacherId: authStore.user.id
		};

		let response;
		if (editingGrade) {
			response = await api.updateGrade(editingGrade.id, gradeData);
		} else {
			response = await api.createGrade(gradeData);
		}

		if (response.data) {
			// Noten neu laden
			if (selectedEntry) {
				await loadGradesForLesson(selectedEntry);
			}
			closeGradeForm();
		} else {
			gradesError = response.error || 'Fehler beim Speichern der Note';
		}

		gradeFormSubmitting = false;
	}

	async function handleDeleteGrade(gradeId: number) {
		if (!confirm('Möchten Sie diese Note wirklich löschen?')) return;

		const response = await api.deleteGrade(gradeId);

		if (response.data) {
			// Noten neu laden
			if (selectedEntry) {
				await loadGradesForLesson(selectedEntry);
			}
		} else {
			gradesError = response.error || 'Fehler beim Löschen der Note';
		}
	}

	function getGradeColor(grade: number): string {
		if (grade <= 2.0) return '#4caf50'; // Grün
		if (grade <= 3.0) return '#ff9800'; // Orange
		if (grade <= 4.0) return '#ff5722'; // Rot-Orange
		return '#f44336'; // Rot
	}

	function resetFeedbackForm() {
		feedbackOverallRating = 5;
		feedbackClarity = 5;
		feedbackPace = 5;
		feedbackInteraction = 5;
		feedbackMaterials = 5;
		feedbackAtmosphere = 5;
		feedbackWhatWasGood = '';
		feedbackWhatCanImprove = '';
		feedbackAdditionalComments = '';
		feedbackIsAnonymous = false;
		feedbackAllowTeacherResponse = true;
		feedbackSuccess = false;
		feedbackError = null;
	}

	async function handleSubmitFeedback(e: Event) {
		e.preventDefault();

		if (!selectedEntry || !authStore.user) return;

		feedbackSubmitting = true;
		feedbackError = null;

		// Hole die User-ID des Lehrers aus der Relation
		const teacherUserId = selectedEntry.teacher?.id;

		if (!teacherUserId) {
			feedbackError = 'Für diese Stunde ist kein Lehrer zugewiesen. Feedback kann nicht abgegeben werden.';
			feedbackSubmitting = false;
			return;
		}

		// Berechne das Datum der Unterrichtsstunde (Wochentag in der aktuellen Woche)
		const lessonDate = getDateForDay(selectedEntry.dayOfWeek, currentWeek, currentYear);

		const feedbackData = {
			studentId: authStore.user.id,
			teacherId: teacherUserId,
			lessonId: selectedEntry.id, // Verwende die tatsächliche TimetableEntry ID
			lessonDate: lessonDate.toISOString(),
			overallRating: feedbackOverallRating,
			categories: {
				clarity: feedbackClarity,
				pace: feedbackPace,
				interaction: feedbackInteraction,
				materials: feedbackMaterials,
				atmosphere: feedbackAtmosphere
			},
			whatWasGood: feedbackWhatWasGood || undefined,
			whatCanImprove: feedbackWhatCanImprove || undefined,
			additionalComments: feedbackAdditionalComments || undefined,
			isAnonymous: feedbackIsAnonymous,
			allowTeacherResponse: feedbackAllowTeacherResponse
		};

		// Debug: Feedback-Daten vor dem Senden loggen
		console.log('Sende Feedback mit teacherId:', teacherUserId);
		console.log('Vollständige Feedback-Daten:', feedbackData);

		const response = await api.createFeedback(feedbackData);

		if (response.data) {
			feedbackSuccess = true;
			feedbackAlreadySubmitted = true;
			resetFeedbackForm();
			// Lade Feedback neu, um die Liste zu aktualisieren
			if (selectedEntry) {
				await loadFeedbackForLesson(selectedEntry);
                // Force true because we just submitted (loadFeedbackForLesson might reset it for anonymous feedback)
                feedbackAlreadySubmitted = true;
			}
			setTimeout(() => {
				feedbackSuccess = false;
			}, 3000);
		} else {
			feedbackError = response.error || 'Fehler beim Absenden des Feedbacks';
		}

		feedbackSubmitting = false;
	}

	function resetForm() {
		formDayOfWeek = 1;
		formStartTime = '';
		formEndTime = '';
		formSubjectId = subjects.length > 0 ? subjects[0].id : 0;
        formSubjectInput = '';
		formTeacherId = undefined;
		formRoomId = undefined;
        formRoomInput = '';
		formIsRecurring = true;
		formSelectedDate = '';
	}

	// Hilfsfunktion: Formatiere Datum für date-input (YYYY-MM-DD)
	function formatDateForInput(date: Date): string {
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		return `${year}-${month}-${day}`;
	}

	// Hilfsfunktion: Berechne Woche und Jahr aus Datum
	function getWeekAndYearFromDate(dateString: string): { weekNumber: number; year: number; dayOfWeek: number } {
		const date = new Date(dateString);
		const year = date.getFullYear();
		const weekNumber = getCurrentWeekNumberForDate(date);
		const dayOfWeek = date.getDay() === 0 ? 7 : date.getDay(); // Sonntag = 7, Montag = 1

		return { weekNumber, year, dayOfWeek };
	}

	// Berechne Kalenderwoche für ein beliebiges Datum
	function getCurrentWeekNumberForDate(date: Date): number {
		const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
		const dayNum = d.getUTCDay() || 7;
		d.setUTCDate(d.getUTCDate() + 4 - dayNum);
		const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
		return Math.ceil((((d.getTime() - yearStart.getTime()) / 86400000) + 1) / 7);
	}

	function validateTimeFormat(time: string): boolean {
		const timeRegex = /^([01]\d|2[0-3]):([0-5]\d)$/;
		return timeRegex.test(time);
	}

	function checkTimeOverlap(
		dayOfWeek: number,
		startTime: string,
		endTime: string,
		isRecurring: boolean,
		weekNumber?: number,
		year?: number,
		excludeEntryId?: number
	): boolean {
		// Filtere Einträge für den gleichen Wochentag
		const dayEntries = timetableEntries.filter(
			(entry) => entry.dayOfWeek === dayOfWeek && entry.id !== excludeEntryId
		);

		for (const entry of dayEntries) {
			// Prüfe ob sich die Veranstaltungen überlappen können
			let canOverlap = false;

			if (isRecurring && (entry.isRecurring ?? true)) {
				// Beide wiederkehrend: Überschneidung möglich
				canOverlap = true;
			} else if (!isRecurring && !(entry.isRecurring ?? true)) {
				// Beide einmalig: Nur wenn gleiche Woche und Jahr
				if (weekNumber === entry.weekNumber && year === entry.year) {
					canOverlap = true;
				}
			} else if (!isRecurring && (entry.isRecurring ?? true)) {
				// Neue ist einmalig, existierende wiederkehrend
				// Die wiederkehrende findet auch in der Woche der einmaligen statt
				canOverlap = true;
			} else if (isRecurring && !(entry.isRecurring ?? true)) {
				// Neue ist wiederkehrend, existierende einmalig
				// Die wiederkehrende findet auch in der Woche der einmaligen statt
				canOverlap = true;
			}

			// Wenn Überlappung möglich ist, prüfe die Zeiten
			if (canOverlap) {
				if (
					(startTime >= entry.startTime && startTime < entry.endTime) ||
					(endTime > entry.startTime && endTime <= entry.endTime) ||
					(startTime <= entry.startTime && endTime >= entry.endTime)
				) {
					return true;
				}
			}
		}

		return false;
	}

	function validateForm(): string | null {
		if (!formSubjectInput.trim()) {
			return 'Bitte geben Sie ein Fach ein';
		}

		if (!validateTimeFormat(formStartTime)) {
			return 'Startzeit muss im Format HH:MM sein (z.B. 08:00)';
		}

		if (!validateTimeFormat(formEndTime)) {
			return 'Endzeit muss im Format HH:MM sein (z.B. 09:30)';
		}

		if (formStartTime >= formEndTime) {
			return 'Endzeit muss nach Startzeit liegen';
		}

		// Wenn nicht wiederkehrend, muss ein Datum ausgewählt sein
		if (!formIsRecurring && !formSelectedDate) {
			return 'Bitte wählen Sie ein Datum für die einmalige Veranstaltung';
		}

		// Berechne dayOfWeek, weekNumber und year für die Überschneidungsprüfung
		let dayOfWeek = formDayOfWeek;
		let weekNumber: number | undefined;
		let year: number | undefined;

		if (!formIsRecurring && formSelectedDate) {
			const dateInfo = getWeekAndYearFromDate(formSelectedDate);
			dayOfWeek = dateInfo.dayOfWeek;
			weekNumber = dateInfo.weekNumber;
			year = dateInfo.year;
		}

		// Prüfe auf Zeitüberschneidungen
		const excludeId = editingEntry ? editingEntry.id : undefined;
		if (checkTimeOverlap(dayOfWeek, formStartTime, formEndTime, formIsRecurring, weekNumber, year, excludeId)) {
			return 'Diese Zeit überschneidet sich mit einer anderen Veranstaltung am selben Tag';
		}

		return null;
	}

	async function handleAddEntry(e: Event) {
		e.preventDefault();

		const validationError = validateForm();
		if (validationError) {
			modalError = validationError;
			return;
		}

		// Bei einmaliger Veranstaltung: Berechne Woche, Jahr und Wochentag aus Datum
		let dayOfWeek = formDayOfWeek;
		let weekNumber: number | undefined;
		let year: number | undefined;

		if (!formIsRecurring && formSelectedDate) {
			const dateInfo = getWeekAndYearFromDate(formSelectedDate);
			dayOfWeek = dateInfo.dayOfWeek;
			weekNumber = dateInfo.weekNumber;
			year = dateInfo.year;
		}

        // Finde ID für Fach
        const subject = subjects.find(s => s.name.toLowerCase() === formSubjectInput.trim().toLowerCase());
        const subjectId = subject ? subject.id : undefined;
        const subjectName = subject ? undefined : formSubjectInput.trim();

        // Finde ID für Raum
        const room = rooms.find(r => r.number.toLowerCase() === formRoomInput.trim().toLowerCase());
        const roomId = room ? room.id : undefined;
        const roomNumber = room ? undefined : formRoomInput.trim();

		const newEntry: CreateTimetableEntryDto = {
			dayOfWeek: dayOfWeek,
			startTime: formStartTime,
			endTime: formEndTime,
			subjectId: subjectId,
            subjectName: subjectName,
			teacherId: formTeacherId,
			roomId: roomId,
            roomNumber: roomNumber,
			isRecurring: formIsRecurring,
			weekNumber: weekNumber,
			year: year
		};

		const response = await api.createTimetableEntry(newEntry);

		if (response.data) {
			await loadTimetable();
			closeAddModal();
			error = null;
		} else {
			modalError = response.error || 'Fehler beim Erstellen des Eintrags';
		}
	}

	async function handleUpdateEntry(e: Event) {
		e.preventDefault();

		if (!editingEntry) return;

		const validationError = validateForm();
		if (validationError) {
			editModalError = validationError;
			return;
		}

		// Bei einmaliger Veranstaltung: Berechne Woche, Jahr und Wochentag aus Datum
		let dayOfWeek = formDayOfWeek;
		let weekNumber: number | undefined;
		let year: number | undefined;

		if (!formIsRecurring && formSelectedDate) {
			const dateInfo = getWeekAndYearFromDate(formSelectedDate);
			dayOfWeek = dateInfo.dayOfWeek;
			weekNumber = dateInfo.weekNumber;
			year = dateInfo.year;
		}

        // Finde ID für Fach
        const subject = subjects.find(s => s.name.toLowerCase() === formSubjectInput.trim().toLowerCase());
        const subjectId = subject ? subject.id : undefined;
        const subjectName = subject ? undefined : formSubjectInput.trim();

        // Finde ID für Raum
        const room = rooms.find(r => r.number.toLowerCase() === formRoomInput.trim().toLowerCase());
        const roomId = room ? room.id : undefined;
        const roomNumber = room ? undefined : formRoomInput.trim();

		const updateData: Partial<CreateTimetableEntryDto> = {
			dayOfWeek: dayOfWeek,
			startTime: formStartTime,
			endTime: formEndTime,
			subjectId: subjectId,
            subjectName: subjectName,
			teacherId: formTeacherId,
			roomId: roomId,
            roomNumber: roomNumber,
			isRecurring: formIsRecurring,
			weekNumber: weekNumber,
			year: year
		};

		const response = await api.updateTimetableEntry(editingEntry.id, updateData);

		if (response.data) {
			await loadTimetable();
			closeEditModal();
			error = null;
		} else {
			editModalError = response.error || 'Fehler beim Aktualisieren des Eintrags';
		}
	}

	async function handleDeleteEntry() {
		if (!entryToDelete) return;

		const response = await api.deleteTimetableEntry(entryToDelete.id);

		if (response.data) {
			await loadTimetable();
			closeDeleteConfirm();
			error = null;
		} else {
			error = response.error || 'Fehler beim Löschen des Eintrags';
			closeDeleteConfirm();
		}
	}

	function getEntriesByDay(day: number): TimetableEntry[] {
		return timetableEntries
			.filter((entry) => entry.dayOfWeek === day)
			.sort((a, b) => a.startTime.localeCompare(b.startTime));
	}

	// Timeслоты für die Tabelle generieren
	function generateTimeSlots(): string[] {
		const slots: string[] = [];
		for (let hour = 7; hour <= 18; hour++) {
			slots.push(`${hour.toString().padStart(2, '0')}:00`);
		}
		return slots;
	}

	const timeSlots = generateTimeSlots();

	function getEntryForTimeSlot(day: number, timeSlot: string): TimetableEntry | null {
		const entries = getEntriesByDay(day);
		return (
			entries.find((entry) => {
				// Ein Eintrag wird angezeigt, wenn seine Starthour <= timeSlotHour < endHour ist
				const [startHour] = entry.startTime.split(':').map(Number);
				const [endHour] = entry.endTime.split(':').map(Number);
				const [slotHour] = timeSlot.split(':').map(Number);
				return slotHour >= startHour && slotHour < endHour;
			}) || null
		);
	}

	function isEntryStart(entry: TimetableEntry, timeSlot: string): boolean {
		// Ein Eintrag startet nur, wenn die Stunde des Zeitslots die Starthour des Eintrags ist
		const entryStartHour = parseInt(entry.startTime.split(':')[0]);
		const slotHour = parseInt(timeSlot.split(':')[0]);
		return entryStartHour === slotHour;
	}

	function calculateRowSpan(entry: TimetableEntry): number {
		const [startHour, startMin] = entry.startTime.split(':').map(Number);
		const [endHour, endMin] = entry.endTime.split(':').map(Number);
		const startMinutes = startHour * 60 + startMin;
		const endMinutes = endHour * 60 + endMin;
		const duration = endMinutes - startMinutes;
		return Math.ceil(duration / 60);
	}
</script>

<div class="timetable-page">
	<div class="content">
		<div class="header-section">
			<div>
				<h2>Stundenplan</h2>
				<p class="subtitle">{authStore.isTeacher ? 'Verwalten Sie den Wochenstundenplan für alle' : 'Ihr Wochenstundenplan'}</p>
			</div>
			{#if authStore.isTeacher}
				<button onclick={openAddModal} class="btn-add">+ Neue Veranstaltung</button>
			{/if}
		</div>

		{#if error}
			<div class="error-banner">
				{error}
				<button onclick={() => (error = null)} class="close-btn">×</button>
			</div>
		{/if}

		<!-- Wochennavigation -->
		<div class="week-navigation">
			<button onclick={previousWeek} class="btn-week-nav" title="Vorherige Woche">
				◀ Vorherige Woche
			</button>
			<div class="week-info">
				<h3>KW {currentWeek} - {currentYear}</h3>
				{#if currentWeek !== getCurrentWeekNumber() || currentYear !== new Date().getFullYear()}
					<button onclick={goToCurrentWeek} class="btn-current-week">
						Zur aktuellen Woche
					</button>
				{/if}
			</div>
			<button onclick={nextWeek} class="btn-week-nav" title="Nächste Woche">
				Nächste Woche ▶
			</button>
		</div>

		{#if isLoading}
			<div class="loading-state">
				<p>Lade Stundenplan...</p>
			</div>
		{:else}
			<div class="timetable-container">
				<table class="timetable-table">
					<thead>
						<tr>
							<th class="time-column">Zeit</th>
							{#each DAYS as day, dayIndex}
								<th>
									<div class="day-header">
										<div class="day-name">{day}</div>
										<div class="day-date">{formatDate(getDateForDay(dayIndex + 1, currentWeek, currentYear))}</div>
									</div>
								</th>
							{/each}
						</tr>
					</thead>
					<tbody>
						{#each timeSlots as timeSlot}
							<tr>
								<td class="time-cell">{timeSlot}</td>
								{#each DAYS as _, dayIndex}
									{@const entry = getEntryForTimeSlot(dayIndex + 1, timeSlot)}
									{#if entry}
										{#if isEntryStart(entry, timeSlot)}
											<td class="entry-cell" rowspan={calculateRowSpan(entry)}>
												<div
													class="table-entry"
													onclick={() => openDetailModal(entry)}
													onkeydown={(e) => e.key === 'Enter' && openDetailModal(entry)}
													role="button"
													tabindex="0"
													aria-label="Details für {entry.subject.name} anzeigen"
												>
													<div class="entry-time-badge">
														{entry.startTime} - {entry.endTime}
													</div>
													<div class="entry-subject">{entry.subject.name}</div>
													{#if entry.teacher}
														<div class="entry-info">👨‍🏫 {entry.teacher.username}</div>
													{/if}
													{#if entry.room}
														<div class="entry-info">🚪 {entry.room.number}</div>
													{/if}
													{#if authStore.isTeacher}
														<div class="entry-actions">
															<button
																onclick={(e) => {
																	e.stopPropagation();
																	openEditModal(entry);
																}}
																class="btn-icon"
																title="Bearbeiten"
															>
																✏️
															</button>
															<button
																onclick={(e) => {
																	e.stopPropagation();
																	openDeleteConfirm(entry);
																}}
																class="btn-icon"
																title="Löschen"
															>
																🗑️
															</button>
														</div>
													{/if}
												</div>
											</td>
										{/if}
									{:else}
										<td class="empty-cell"></td>
									{/if}
								{/each}
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/if}
	</div>
</div>

<!-- Add Modal -->
{#if showAddModal}
	<div
		class="modal-backdrop"
		onclick={closeAddModal}
		onkeydown={(e) => e.key === 'Escape' && closeAddModal()}
		role="button"
		tabindex="0"
		aria-label="Schließe das Modal"
	>
		<div
			class="modal"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => e.stopPropagation()}
			role="dialog"
			aria-modal="true"
			aria-labelledby="add-modal-title"
			tabindex="-1"
		>
			<div class="modal-header">
				<h3 id="add-modal-title">Neue Veranstaltung</h3>
				<button onclick={closeAddModal} class="modal-close">×</button>
			</div>
			<form onsubmit={handleAddEntry}>
				<div class="modal-body">
					{#if modalError}
						<div class="error-banner modal-error-banner">
							{modalError}
							<button onclick={() => (modalError = null)} class="close-btn" type="button">×</button>
						</div>
					{/if}
					<!-- Wiederkehrend oder Einmalig -->
					<div class="form-group">
						<div class="form-group-label">Veranstaltungstyp</div>
						<div class="radio-group">
							<label class="radio-label">
								<input type="radio" bind:group={formIsRecurring} value={true} />
								Wiederkehrend (jede Woche)
							</label>
							<label class="radio-label">
								<input type="radio" bind:group={formIsRecurring} value={false} />
								Einmalig (spezifisches Datum)
							</label>
						</div>
					</div>

					{#if formIsRecurring}
						<!-- Wochentag für wiederkehrende Veranstaltungen -->
						<div class="form-group">
							<label for="add-day">Wochentag</label>
							<select id="add-day" bind:value={formDayOfWeek} required>
								{#each DAYS as day, index}
									<option value={index + 1}>{day}</option>
								{/each}
							</select>
						</div>
					{:else}
						<!-- Datum für einmalige Veranstaltungen -->
						<div class="form-group">
							<label for="add-date">Datum</label>
							<input
								type="date"
								id="add-date"
								bind:value={formSelectedDate}
								required
								class="date-input"
							/>
							<small class="form-hint">Der Wochentag wird automatisch aus dem Datum berechnet</small>
						</div>
					{/if}

					<div class="form-row">
						<div class="form-group">
							<label for="add-start">Startzeit</label>
							<input
								type="time"
								id="add-start"
								bind:value={formStartTime}
								required
							/>
						</div>

						<div class="form-group">
							<label for="add-end">Endzeit</label>
							<input
								type="time"
								id="add-end"
								bind:value={formEndTime}
								required
							/>
						</div>
					</div>

					<div class="form-group">
						<label for="add-subject">Fach</label>
                        <input 
                            list="add-subjects" 
                            id="add-subject" 
                            bind:value={formSubjectInput} 
                            required 
                            placeholder="Fach eingeben oder auswählen"
                            class="form-input"
                        >
                        <datalist id="add-subjects">
							{#each subjects as subject}
								<option value={subject.name}>{subject.abbreviation ? `(${subject.abbreviation})` : ''}</option>
							{/each}
						</datalist>
					</div>

					<div class="form-group">
						<label for="add-teacher">Lehrer (optional)</label>
						<select id="add-teacher" bind:value={formTeacherId}>
							<option value={undefined}>-- Bitte wählen --</option>
							{#each teachers as teacher}
								<option value={teacher.id}>{teacher.username} ({teacher.email})</option>
							{/each}
						</select>
					</div>

					<div class="form-group">
						<label for="add-room">Raum (optional)</label>
                        <input 
                            list="add-rooms" 
                            id="add-room" 
                            bind:value={formRoomInput} 
                            placeholder="Raum eingeben oder auswählen"
                            class="form-input"
                        >
                        <datalist id="add-rooms">
							{#each rooms as room}
								<option value={room.number}>{room.building ? `(${room.building})` : ''}</option>
							{/each}
						</datalist>
					</div>
				</div>

				<div class="modal-footer">
					<button type="button" onclick={closeAddModal} class="btn-secondary">
						Abbrechen
					</button>
					<button type="submit" class="btn-primary">Erstellen</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Edit Modal -->
{#if showEditModal && editingEntry}
	<div
		class="modal-backdrop"
		onclick={closeEditModal}
		onkeydown={(e) => e.key === 'Escape' && closeEditModal()}
		role="button"
		tabindex="0"
		aria-label="Schließe das Bearbeitungs-Modal"
	>
		<div
			class="modal"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => e.stopPropagation()}
			role="dialog"
			aria-modal="true"
			aria-labelledby="edit-modal-title"
			tabindex="-1"
		>
			<div class="modal-header">
				<h3 id="edit-modal-title">Veranstaltung bearbeiten</h3>
				<button onclick={closeEditModal} class="modal-close">×</button>
			</div>
			<form onsubmit={handleUpdateEntry}>
				<div class="modal-body">
					{#if editModalError}
						<div class="error-banner modal-error-banner">
							{editModalError}
							<button onclick={() => (editModalError = null)} class="close-btn" type="button">×</button>
						</div>
					{/if}
					<!-- Wiederkehrend oder Einmalig -->
					<div class="form-group">
						<div class="form-group-label">Veranstaltungstyp</div>
						<div class="radio-group">
							<label class="radio-label">
								<input type="radio" bind:group={formIsRecurring} value={true} />
								Wiederkehrend (jede Woche)
							</label>
							<label class="radio-label">
								<input type="radio" bind:group={formIsRecurring} value={false} />
								Einmalig (spezifisches Datum)
							</label>
						</div>
					</div>

					{#if formIsRecurring}
						<!-- Wochentag für wiederkehrende Veranstaltungen -->
						<div class="form-group">
							<label for="edit-day">Wochentag</label>
							<select id="edit-day" bind:value={formDayOfWeek} required>
								{#each DAYS as day, index}
									<option value={index + 1}>{day}</option>
								{/each}
							</select>
						</div>
					{:else}
						<!-- Datum für einmalige Veranstaltungen -->
						<div class="form-group">
							<label for="edit-date">Datum</label>
							<input
								type="date"
								id="edit-date"
								bind:value={formSelectedDate}
								required
								class="date-input"
							/>
							<small class="form-hint">Der Wochentag wird automatisch aus dem Datum berechnet</small>
						</div>
					{/if}

					<div class="form-row">
						<div class="form-group">
							<label for="edit-start">Startzeit</label>
							<input type="time" id="edit-start" bind:value={formStartTime} required />
						</div>

						<div class="form-group">
							<label for="edit-end">Endzeit</label>
							<input type="time" id="edit-end" bind:value={formEndTime} required />
						</div>
					</div>

					<div class="form-group">
						<label for="edit-subject">Fach</label>
                        <input 
                            list="edit-subjects" 
                            id="edit-subject" 
                            bind:value={formSubjectInput} 
                            required 
                            placeholder="Fach eingeben oder auswählen"
                            class="form-input"
                        >
                        <datalist id="edit-subjects">
							{#each subjects as subject}
								<option value={subject.name}>{subject.abbreviation ? `(${subject.abbreviation})` : ''}</option>
							{/each}
						</datalist>
					</div>

					<div class="form-group">
						<label for="edit-teacher">Lehrer (optional)</label>
						<select id="edit-teacher" bind:value={formTeacherId}>
							<option value={undefined}>-- Bitte wählen --</option>
							{#each teachers as teacher}
								<option value={teacher.id}>{teacher.username} ({teacher.email})</option>
							{/each}
						</select>
					</div>

					<div class="form-group">
						<label for="edit-room">Raum (optional)</label>
                        <input 
                            list="edit-rooms" 
                            id="edit-room" 
                            bind:value={formRoomInput} 
                            placeholder="Raum eingeben oder auswählen"
                            class="form-input"
                        >
                        <datalist id="edit-rooms">
							{#each rooms as room}
								<option value={room.number}>{room.building ? `(${room.building})` : ''}</option>
							{/each}
						</datalist>
					</div>
				</div>

				<div class="modal-footer">
					<button type="button" onclick={closeEditModal} class="btn-secondary">
						Abbrechen
					</button>
					<button type="submit" class="btn-primary">Speichern</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Delete Confirmation Modal -->
{#if showDeleteConfirm && entryToDelete}
	<div
		class="modal-backdrop"
		onclick={closeDeleteConfirm}
		onkeydown={(e) => e.key === 'Escape' && closeDeleteConfirm()}
		role="button"
		tabindex="0"
		aria-label="Schließe das Löschbestätigung-Modal"
	>
		<div
			class="modal modal-small"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => e.stopPropagation()}
			role="dialog"
			aria-modal="true"
			aria-labelledby="delete-modal-title"
			tabindex="-1"
		>
			<div class="modal-header">
				<h3 id="delete-modal-title">Veranstaltung löschen</h3>
				<button onclick={closeDeleteConfirm} class="modal-close">×</button>
			</div>
			<div class="modal-body">
				<p>Möchten Sie diese Veranstaltung wirklich löschen?</p>
				<div class="delete-preview">
					<strong>{entryToDelete.subject.name}</strong>
					<div>
						{DAYS[entryToDelete.dayOfWeek - 1]}, {entryToDelete.startTime} - {entryToDelete.endTime}
					</div>
				</div>
				<p class="warning">Diese Aktion kann nicht rückgängig gemacht werden.</p>
			</div>
			<div class="modal-footer">
				<button onclick={closeDeleteConfirm} class="btn-secondary">Abbrechen</button>
				<button onclick={handleDeleteEntry} class="btn-danger">Löschen</button>
			</div>
		</div>
	</div>
{/if}

<!-- Detail Modal -->
{#if showDetailModal && selectedEntry}
	<div
		class="modal-backdrop"
		onclick={closeDetailModal}
		onkeydown={(e) => e.key === 'Escape' && closeDetailModal()}
		role="button"
		tabindex="0"
		aria-label="Schließe die Detailansicht"
	>
		<div
			class="modal modal-large"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => e.stopPropagation()}
			role="dialog"
			aria-modal="true"
			aria-labelledby="detail-modal-title"
			tabindex="-1"
		>
			<div class="modal-header">
				<div>
					<h3 id="detail-modal-title">{selectedEntry.subject.name}</h3>
					<p class="detail-subtitle">
						{DAYS[selectedEntry.dayOfWeek - 1]}, {selectedEntry.startTime} - {selectedEntry.endTime}
						{#if selectedEntry.teacher}
							• {selectedEntry.teacher.username}
						{/if}
						{#if selectedEntry.room}
							• Raum {selectedEntry.room.number}
						{/if}
					</p>
				</div>
				<button onclick={closeDetailModal} class="modal-close">×</button>
			</div>

			<div class="tab-navigation">
				<button
					class="tab-btn"
					class:active={activeTab === 'files'}
					onclick={() => (activeTab = 'files')}
				>
					📁 Dateiablage
				</button>
				<button
					class="tab-btn"
					class:active={activeTab === 'feedback'}
					onclick={() => (activeTab = 'feedback')}
				>
					💭 Feedback
				</button>
				<button
					class="tab-btn"
					class:active={activeTab === 'grades'}
					onclick={() => (activeTab = 'grades')}
				>
					📊 Noteneinsicht
				</button>
			</div>

			<div class="modal-body tab-content">
				{#if activeTab === 'files'}
					<div class="files-content">
						<div class="files-header">
							<h4>Dateiablage</h4>
							{#if authStore.isTeacher}
								<label class="checkbox-label text-sm">
									<input 
										type="checkbox" 
										checked={selectedEntry.allowStudentUploads} 
										onchange={() => toggleStudentUploads(selectedEntry!)}
									/>
									Schüler-Uploads erlauben
								</label>
							{/if}
						</div>

						{#if authStore.isTeacher || selectedEntry.allowStudentUploads}
							<div style="margin-bottom: 16px;">
								<FileUploader 
									timetableEntryId={selectedEntry.id} 
									onUploadSuccess={() => loadLessonFiles(selectedEntry!)} 
								/>
							</div>
						{:else}
							<div class="bg-gray-50 p-4 rounded-lg mb-6 text-center text-gray-500">
								Uploads sind für diese Stunde deaktiviert.
							</div>
						{/if}

						{#if filesLoading}
							<div class="loading">Dateien werden geladen...</div>
						{:else if filesError}
							<div class="error-banner">
								{filesError}
								<button onclick={() => (filesError = null)} class="close-btn" type="button">×</button>
							</div>
						{:else if lessonFiles.length === 0}
							<div class="empty-state">
								<div class="empty-icon">📁</div>
								<p>Keine Dateien vorhanden</p>
							</div>
						{:else}
							<div class="files-list">
								{#each lessonFiles as file}
									<div class="file-item">
										<div class="file-icon">📄</div>
										<div class="file-info">
											<div class="file-name">{file.filename}</div>
											<div class="file-meta">
												{formatFileSize(file.size)} • {new Date(file.createdAt).toLocaleDateString()} • 
												<span class="font-medium">{file.uploadedBy.username}</span> ({file.uploadedBy.role})
											</div>
										</div>
										<div class="file-actions">
											<a href={api.getDownloadUrl(file.id)} target="_blank" class="btn-icon" title="Download">⬇️</a>
											{#if authStore.isTeacher || authStore.user?.id === file.uploadedById}
												<button onclick={() => deleteFile(file.id)} class="btn-icon text-red-500" title="Löschen">🗑️</button>
											{/if}
										</div>
									</div>
								{/each}
							</div>
						{/if}
					</div>
				{:else if activeTab === 'feedback'}
					<div class="feedback-form-container">
						{#if feedbackError}
							<div class="error-banner">
								{feedbackError}
								<button onclick={() => (feedbackError = null)} class="close-btn">×</button>
							</div>
						{/if}

						{#if authStore.isTeacher}
							<!-- Lehrer-Ansicht: Zeige alle Feedbacks -->
							<div class="feedback-list-view">
								<h4 class="form-section-title">Feedback-Übersicht zu {selectedEntry.subject.name}</h4>

								{#if existingFeedbackList.length === 0}
									<div class="no-feedback-message">
										<div class="placeholder-icon">💭</div>
										<p>Noch kein Feedback für diese Stunde vorhanden.</p>
									</div>
								{:else}
									<div class="feedback-items">
										{#each existingFeedbackList as feedback}
											<div class="feedback-item">
												<div class="feedback-header">
													<div class="feedback-student">
														{feedback.isAnonymous ? '👤 Anonym' : `👤 ${feedback.student?.username || 'Unbekannt'}`}
													</div>
													<div class="feedback-date">
														{new Date(feedback.createdAt).toLocaleDateString('de-DE')}
													</div>
												</div>

												<div class="feedback-rating-summary">
													<div class="rating-badge-large">
														{feedback.overallRating}/10
													</div>
													<div class="rating-categories-compact">
														{#if feedback.categories}
															<span>Verständlichkeit: {feedback.categories.clarity}/10</span>
															<span>Tempo: {feedback.categories.pace}/10</span>
															<span>Interaktion: {feedback.categories.interaction}/10</span>
															<span>Material: {feedback.categories.materials}/10</span>
															<span>Atmosphäre: {feedback.categories.atmosphere}/10</span>
														{/if}
													</div>
												</div>

												{#if feedback.whatWasGood}
													<div class="feedback-section">
														<strong>Was war gut:</strong>
														<p>{feedback.whatWasGood}</p>
													</div>
												{/if}

												{#if feedback.whatCanImprove}
													<div class="feedback-section">
														<strong>Verbesserungsvorschläge:</strong>
														<p>{feedback.whatCanImprove}</p>
													</div>
												{/if}

												{#if feedback.additionalComments}
													<div class="feedback-section">
														<strong>Weitere Kommentare:</strong>
														<p>{feedback.additionalComments}</p>
													</div>
												{/if}
											</div>
										{/each}
									</div>
								{/if}
							</div>
						{:else if feedbackAlreadySubmitted}
							<!-- Schüler hat bereits Feedback abgegeben -->
							<div class="already-submitted-message">
								<div class="info-icon">ℹ️</div>
								<h4>Feedback bereits abgegeben</h4>
								<p>Sie haben für diese Stunde bereits Feedback abgegeben.</p>
								<p class="info-text">Vielen Dank für Ihre Rückmeldung!</p>
							</div>
						{:else if feedbackSuccess}
							<div class="success-message">
								<div class="success-icon">✓</div>
								<h4>Feedback erfolgreich abgesendet!</h4>
								<p>Vielen Dank für Ihr Feedback.</p>
							</div>
						{:else}
							<!-- Schüler-Formular -->
							<form onsubmit={handleSubmitFeedback}>
								<h4 class="form-section-title">Feedback zu {selectedEntry.subject.name}</h4>
								<div class="lesson-info-box">
									<p><strong>Lektion:</strong> {selectedEntry.subject.name}</p>
									{#if selectedEntry.teacher}
										<p><strong>Lehrer:</strong> {selectedEntry.teacher.username}</p>
									{/if}
									<p><strong>Zeit:</strong> {DAYS[selectedEntry.dayOfWeek - 1]}, {selectedEntry.startTime} - {selectedEntry.endTime}</p>
									{#if selectedEntry.room}
										<p><strong>Raum:</strong> {selectedEntry.room.number}</p>
									{/if}
								</div>

								<div class="rating-section">
									<label class="rating-label" for="rating-overall">
										Gesamtbewertung
										<span class="rating-value">{feedbackOverallRating}/10</span>
									</label>
									<input
										type="range"
										id="rating-overall"
										min="1"
										max="10"
										bind:value={feedbackOverallRating}
										class="rating-slider"
									/>
								</div>

								<h5 class="subsection-title">Detaillierte Bewertung</h5>

								<div class="rating-grid">
									<div class="rating-item">
										<label class="rating-label" for="rating-clarity">
											Verständlichkeit
											<span class="rating-value">{feedbackClarity}/10</span>
										</label>
										<input
											type="range"
											id="rating-clarity"
											min="1"
											max="10"
											bind:value={feedbackClarity}
											class="rating-slider"
										/>
									</div>

									<div class="rating-item">
										<label class="rating-label" for="rating-pace">
											Tempo
											<span class="rating-value">{feedbackPace}/10</span>
										</label>
										<input
											type="range"
											id="rating-pace"
											min="1"
											max="10"
											bind:value={feedbackPace}
											class="rating-slider"
										/>
									</div>

									<div class="rating-item">
										<label class="rating-label" for="rating-interaction">
											Interaktion
											<span class="rating-value">{feedbackInteraction}/10</span>
										</label>
										<input
											type="range"
											id="rating-interaction"
											min="1"
											max="10"
											bind:value={feedbackInteraction}
											class="rating-slider"
										/>
									</div>

									<div class="rating-item">
										<label class="rating-label" for="rating-materials">
											Unterrichtsmaterial
											<span class="rating-value">{feedbackMaterials}/10</span>
										</label>
										<input
											type="range"
											id="rating-materials"
											min="1"
											max="10"
											bind:value={feedbackMaterials}
											class="rating-slider"
										/>
									</div>

									<div class="rating-item">
										<label class="rating-label" for="rating-atmosphere">
											Atmosphäre
											<span class="rating-value">{feedbackAtmosphere}/10</span>
										</label>
										<input
											type="range"
											id="rating-atmosphere"
											min="1"
											max="10"
											bind:value={feedbackAtmosphere}
											class="rating-slider"
										/>
									</div>
								</div>

								<div class="form-group">
									<label for="feedback-good">Was hat Ihnen gut gefallen?</label>
									<textarea
										id="feedback-good"
										bind:value={feedbackWhatWasGood}
										rows="3"
										placeholder="z.B. Klare Erklärungen, gute Beispiele..."
									></textarea>
								</div>

								<div class="form-group">
									<label for="feedback-improve">Was kann verbessert werden?</label>
									<textarea
										id="feedback-improve"
										bind:value={feedbackWhatCanImprove}
										rows="3"
										placeholder="z.B. Mehr Übungszeit, langsameres Tempo..."
									></textarea>
								</div>

								<div class="form-group">
									<label for="feedback-additional">Zusätzliche Kommentare (optional)</label>
									<textarea
										id="feedback-additional"
										bind:value={feedbackAdditionalComments}
										rows="2"
										placeholder="Weitere Anmerkungen..."
									></textarea>
								</div>

								<div class="checkbox-group">
									<label class="checkbox-label">
										<input type="checkbox" bind:checked={feedbackIsAnonymous} />
										Anonym absenden
									</label>
									<label class="checkbox-label">
										<input type="checkbox" bind:checked={feedbackAllowTeacherResponse} />
										Lehrer darf auf Feedback antworten
									</label>
								</div>

								<div class="form-actions">
									<button
										type="submit"
										class="btn-primary"
										disabled={feedbackSubmitting}
									>
										{feedbackSubmitting ? 'Wird gesendet...' : 'Feedback absenden'}
									</button>
								</div>
							</form>
						{/if}
					</div>
				{:else if activeTab === 'grades'}
					<div class="grades-content">
						<div class="grades-header">
							<h4>Mündliche Noten - {selectedEntry.subject.name}</h4>
							{#if authStore.isTeacher && !showGradeForm}
								<button onclick={openGradeForm} class="btn-add-grade">+ Mündliche Note hinzufügen</button>
							{/if}
						</div>

						{#if gradesError}
							<div class="error-banner">
								{gradesError}
								<button onclick={() => (gradesError = null)} class="close-btn" type="button">×</button>
							</div>
						{/if}

						{#if gradesLoading}
							<div class="loading">Noten werden geladen...</div>
						{:else if showGradeForm && authStore.isTeacher}
							<!-- Lehrer: Noten-Eingabe-Formular -->
							<form onsubmit={handleGradeSubmit} class="grade-form">
								<div class="form-group">
									<label for="grade-student">Schüler *</label>
									<select id="grade-student" bind:value={gradeFormStudentId} required disabled={editingGrade !== null}>
										<option value={0}>-- Bitte wählen --</option>
										{#each students as student}
											<option value={student.id}>{student.username} ({student.email})</option>
										{/each}
									</select>
								</div>

								<div class="form-group">
									<label for="grade-value">Mündliche Note *</label>
									<input
										type="number"
										id="grade-value"
										bind:value={gradeFormGrade}
										min="1.0"
										max="6.0"
										step="0.1"
										required
									/>
								</div>

								<div class="form-group">
									<label for="grade-description">Notiz (optional)</label>
									<textarea id="grade-description" bind:value={gradeFormDescription} rows="3" placeholder="Bemerkungen zur mündlichen Note..."></textarea>
								</div>

								<div class="form-actions">
									<button type="button" onclick={closeGradeForm} class="btn-secondary">Abbrechen</button>
									<button type="submit" class="btn-primary" disabled={gradeFormSubmitting}>
										{gradeFormSubmitting ? 'Speichern...' : editingGrade ? 'Aktualisieren' : 'Erstellen'}
									</button>
								</div>
							</form>
						{:else if grades.length === 0}
							<div class="empty-state">
								<div class="empty-icon">📊</div>
								<p>{authStore.isTeacher ? 'Noch keine Noten eingetragen' : 'Noch keine Noten vorhanden'}</p>
							</div>
						{:else}
							<!-- Noten-Liste -->
							<div class="grades-list">
								{#if authStore.isTeacher}
									<!-- Lehrer-Ansicht: Alle Noten mit Schülernamen -->
									{#each grades as grade}
										<div class="grade-card">
											<div class="grade-card-header">
												<div class="grade-student-info">
													<strong>{grade.student?.username || 'Unbekannt'}</strong>
												</div>
												<div class="grade-value" style="color: {getGradeColor(grade.grade)}">
													{grade.grade.toFixed(1)}
												</div>
											</div>
											{#if grade.description}
												<div class="grade-card-body">
													<div class="grade-description">{grade.description}</div>
												</div>
											{/if}
											<div class="grade-card-actions">
												<button onclick={() => openEditGradeForm(grade)} class="btn-edit-small">Bearbeiten</button>
												<button onclick={() => handleDeleteGrade(grade.id)} class="btn-delete-small">Löschen</button>
											</div>
										</div>
									{/each}
								{:else}
									<!-- Schüler-Ansicht: Nur eigene Note -->
									{#if grades.length > 0}
										<div class="grade-card-student">
											<div class="grade-value-student" style="color: {getGradeColor(grades[0].grade)}">
												{grades[0].grade.toFixed(1)}
											</div>
											{#if grades[0].description}
												<div class="grade-description-student">{grades[0].description}</div>
											{/if}
										</div>
									{/if}
								{/if}
							</div>
						{/if}
					</div>
				{/if}
			</div>

			<div class="modal-footer">
				<button onclick={closeDetailModal} class="btn-secondary">Schließen</button>
			</div>
		</div>
	</div>
{/if}

<style>
	.timetable-page {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.content {
		max-width: 1400px;
		margin: 0 auto;
		padding: 2rem;
	}

	.header-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 2rem;
		flex-wrap: wrap;
		gap: 1rem;
	}

	.header-section h2 {
		margin: 0 0 0.5rem;
		color: #333;
		font-size: 2rem;
	}

	.subtitle {
		color: #666;
		margin: 0;
	}

	.btn-add {
		background: var(--primary);
		color: white;
		padding: 0.75rem 1.5rem;
		border: none;
		border-radius: 8px;
		font-weight: 600;
		font-size: 1rem;
		cursor: pointer;
		transition: transform 0.2s, box-shadow 0.2s;
	}

	.btn-add:hover {
		transform: translateY(-2px);
		box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
	}

	.error-banner {
		background: #fee;
		color: #c33;
		padding: 1rem 1.25rem;
		border-radius: 8px;
		margin-bottom: 1.5rem;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.modal-error-banner {
		margin-bottom: 1rem;
		animation: slideDown 0.3s ease-out;
	}

	@keyframes slideDown {
		from {
			opacity: 0;
			transform: translateY(-10px);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.close-btn {
		background: none;
		border: none;
		color: inherit;
		font-size: 1.5rem;
		cursor: pointer;
		padding: 0;
		line-height: 1;
	}

	.loading-state {
		text-align: center;
		padding: 3rem;
		color: #999;
	}

	.timetable-container {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		overflow-x: auto;
	}

	.timetable-table {
		width: 100%;
		border-collapse: collapse;
		min-width: 800px;
	}

	.timetable-table thead {
		background: var(--primary);
		color: white;
	}

	.timetable-table th {
		padding: 1rem;
		text-align: center;
		font-weight: 600;
		font-size: 1rem;
	}

	.time-column {
		width: 100px;
		background: var(--primary);
	}

	.time-cell {
		background: #f9f9f9;
		font-weight: 600;
		color: #667eea;
		text-align: center;
		padding: 0.75rem;
		border: 1px solid #e1e1e1;
		font-size: 0.9rem;
	}

	.empty-cell {
		background: white;
		border: 1px solid #e1e1e1;
		min-height: 60px;
	}

	.entry-cell {
		background: #f0f4ff;
		border: 2px solid #667eea;
		padding: 0.75rem;
		vertical-align: top;
		position: relative;
	}

	.table-entry {
		height: 100%;
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
		cursor: pointer;
		transition: background 0.2s;
	}

	.table-entry:hover {
		background: rgba(102, 126, 234, 0.1);
	}

	.table-entry:focus {
		outline: 2px solid #667eea;
		outline-offset: -2px;
		background: rgba(102, 126, 234, 0.1);
	}

	.entry-time-badge {
		background: #667eea;
		color: white;
		padding: 0.25rem 0.5rem;
		border-radius: 4px;
		font-size: 0.75rem;
		font-weight: 600;
		display: inline-block;
		align-self: flex-start;
	}

	.entry-subject {
		font-weight: 600;
		color: #333;
		font-size: 1rem;
		margin-bottom: 0.25rem;
	}

	.entry-info {
		font-size: 0.85rem;
		color: #666;
		margin-bottom: 0.25rem;
	}

	.entry-actions {
		display: flex;
		gap: 0.5rem;
		margin-top: 0.5rem;
	}

	.btn-icon {
		background: white;
		border: 1px solid #e1e1e1;
		font-size: 1.1rem;
		cursor: pointer;
		padding: 0.25rem 0.5rem;
		border-radius: 4px;
		transition: background 0.2s, border-color 0.2s;
	}

	.btn-icon:first-child:hover {
		background: #e8f5e9;
		border-color: #4caf50;
	}

	.btn-icon:last-child:hover {
		background: #ffebee;
		border-color: #ff5252;
	}

	/* Modal Styles */
	.modal-backdrop {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
		padding: 1rem;
	}

	.modal {
		background: white;
		border-radius: 12px;
		width: 100%;
		max-width: 500px;
		max-height: 90vh;
		overflow: auto;
	}

	.modal-small {
		max-width: 400px;
	}

	.modal-large {
		max-width: 800px;
	}

	.modal-header {
		padding: 1.5rem;
		border-bottom: 1px solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.modal-header h3 {
		margin: 0;
		color: #333;
	}

	.modal-close {
		background: none;
		border: none;
		font-size: 2rem;
		cursor: pointer;
		color: #999;
		line-height: 1;
		padding: 0;
	}

	.modal-body {
		padding: 1.5rem;
	}

	.form-group {
		margin-bottom: 1.25rem;
	}

	.form-group:last-child {
		margin-bottom: 0;
	}

	.form-row {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 1rem;
	}

	label,
	.form-group-label {
		display: block;
		margin-bottom: 0.5rem;
		font-weight: 600;
		color: #333;
		font-size: 0.9rem;
	}

	input,
	select {
		width: 100%;
		padding: 0.75rem;
		border: 2px solid #e1e1e1;
		border-radius: 6px;
		font-size: 1rem;
		transition: border-color 0.2s;
	}

	input:focus,
	select:focus {
		outline: none;
		border-color: #667eea;
	}

	.delete-preview {
		background: #f9f9f9;
		padding: 1rem;
		border-radius: 6px;
		margin: 1rem 0;
		border-left: 4px solid #667eea;
	}

	.warning {
		color: #ff5252;
		font-size: 0.9rem;
		margin-top: 1rem;
		margin-bottom: 0;
	}

	.form-input,
	.form-textarea {
		width: 100%;
		padding: 0.75rem;
		border: 1px solid #ddd;
		border-radius: 8px;
		font-size: 1rem;
		font-family: inherit;
		background: white;
	}

    .form-input:focus,
    .form-textarea:focus {
        outline: 2px solid var(--primary);
        border-color: var(--primary);
    }
    
	.modal-footer {
		padding: 1.5rem;
		border-top: 1px solid #f0f0f0;
		display: flex;
		justify-content: flex-end;
		gap: 0.75rem;
	}

	.btn-primary,
	.btn-secondary,
	.btn-danger {
		padding: 0.625rem 1.25rem;
		border: none;
		border-radius: 6px;
		font-weight: 600;
		cursor: pointer;
		transition: transform 0.2s, box-shadow 0.2s;
	}

	.btn-primary {
		background: var(--primary);
		color: white;
	}

	.btn-primary:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
	}

	.btn-secondary {
		background: #e1e1e1;
		color: #333;
	}

	.btn-secondary:hover {
		background: #d1d1d1;
	}

	.btn-danger {
		background: #ff5252;
		color: white;
	}

	.btn-danger:hover {
		background: #ff3838;
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(255, 82, 82, 0.4);
	}

	/* Detail Modal Styles */
	.detail-subtitle {
		color: #666;
		margin: 0.5rem 0 0;
		font-size: 0.9rem;
	}

	.tab-navigation {
		display: flex;
		border-bottom: 2px solid #f0f0f0;
		background: #fafafa;
	}

	.tab-btn {
		flex: 1;
		padding: 1rem;
		border: none;
		background: transparent;
		font-size: 0.95rem;
		font-weight: 600;
		color: #666;
		cursor: pointer;
		transition: all 0.2s;
		border-bottom: 3px solid transparent;
		position: relative;
		top: 2px;
	}

	.tab-btn:hover {
		background: #f0f0f0;
		color: #667eea;
	}

	.tab-btn.active {
		color: #667eea;
		background: white;
		border-bottom-color: #667eea;
	}

	.tab-content {
		min-height: 400px;
		padding: 2rem;
	}

	/* Feedback Form Styles */
	.feedback-form-container {
		max-width: 600px;
		margin: 0 auto;
	}

	.form-section-title {
		color: #333;
		margin: 0 0 1.5rem;
		font-size: 1.3rem;
		text-align: center;
	}

	.subsection-title {
		color: #555;
		margin: 1.5rem 0 1rem;
		font-size: 1rem;
		font-weight: 600;
	}

	.rating-section {
		margin-bottom: 2rem;
		padding: 1.5rem;
		background: #f9f9f9;
		border-radius: 8px;
		border-left: 4px solid #667eea;
	}

	.rating-label {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 0.5rem;
		font-weight: 600;
		color: #333;
	}

	.rating-value {
		background: #667eea;
		color: white;
		padding: 0.25rem 0.75rem;
		border-radius: 12px;
		font-size: 0.9rem;
	}

	.rating-slider {
		width: 100%;
		height: 8px;
		border-radius: 4px;
		background: #e1e1e1;
		outline: none;
		-webkit-appearance: none;
		appearance: none;
	}

	.rating-slider::-webkit-slider-thumb {
		-webkit-appearance: none;
		appearance: none;
		width: 20px;
		height: 20px;
		border-radius: 50%;
		background: #667eea;
		cursor: pointer;
		transition: all 0.2s;
	}

	.rating-slider::-webkit-slider-thumb:hover {
		transform: scale(1.2);
		background: #5568d3;
	}

	.rating-slider::-moz-range-thumb {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		background: #667eea;
		cursor: pointer;
		border: none;
		transition: all 0.2s;
	}

	.rating-slider::-moz-range-thumb:hover {
		transform: scale(1.2);
		background: #5568d3;
	}

	.rating-grid {
		display: grid;
		gap: 1rem;
		margin-bottom: 1.5rem;
	}

	.rating-item {
		padding: 1rem;
		background: white;
		border: 1px solid #e1e1e1;
		border-radius: 6px;
	}

	.checkbox-group {
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
		margin: 1.5rem 0;
		padding: 1rem;
		background: #f9f9f9;
		border-radius: 6px;
	}

	.checkbox-label {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		font-size: 0.95rem;
		color: #555;
		cursor: pointer;
	}

	.checkbox-label input[type='checkbox'] {
		width: 18px;
		height: 18px;
		cursor: pointer;
	}

	.form-actions {
		display: flex;
		justify-content: center;
		margin-top: 2rem;
	}

	.form-actions .btn-primary {
		min-width: 200px;
	}

	.success-message {
		text-align: center;
		padding: 3rem 2rem;
	}

	.success-icon {
		width: 80px;
		height: 80px;
		margin: 0 auto 1.5rem;
		background: var(--success-color);
		color: white;
		font-size: 3rem;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		animation: successPop 0.5s ease-out;
	}

	@keyframes successPop {
		0% {
			transform: scale(0);
		}
		50% {
			transform: scale(1.1);
		}
		100% {
			transform: scale(1);
		}
	}

	.success-message h4 {
		color: #4caf50;
		margin: 0 0 0.5rem;
		font-size: 1.5rem;
	}

	.success-message p {
		color: #666;
		margin: 0;
	}

	textarea {
		width: 100%;
		padding: 0.75rem;
		border: 2px solid #e1e1e1;
		border-radius: 6px;
		font-size: 1rem;
		font-family: inherit;
		resize: vertical;
		transition: border-color 0.2s;
	}

	textarea:focus {
		outline: none;
		border-color: #667eea;
	}

	textarea::placeholder {
		color: #999;
	}

	/* Feedback List View (Lehrer) */
	.feedback-list-view {
		max-width: 700px;
		margin: 0 auto;
	}

	.feedback-items {
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
	}

	.feedback-item {
		background: white;
		border: 1px solid #e1e1e1;
		border-radius: 8px;
		padding: 1.5rem;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.feedback-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 1rem;
		padding-bottom: 0.75rem;
		border-bottom: 2px solid #f0f0f0;
	}

	.feedback-student {
		font-weight: 600;
		color: #333;
		font-size: 1rem;
	}

	.feedback-date {
		color: #999;
		font-size: 0.85rem;
	}

	.feedback-rating-summary {
		display: flex;
		gap: 1.5rem;
		align-items: center;
		margin-bottom: 1rem;
		padding: 1rem;
		background: #f9f9f9;
		border-radius: 6px;
	}

	.rating-badge-large {
		background: var(--primary);
		color: white;
		font-size: 1.5rem;
		font-weight: bold;
		padding: 1rem 1.5rem;
		border-radius: 8px;
		min-width: 80px;
		text-align: center;
	}

	.rating-categories-compact {
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
		font-size: 0.85rem;
		color: #666;
	}

	.rating-categories-compact span {
		display: block;
	}

	.feedback-section {
		margin-bottom: 1rem;
	}

	.feedback-section strong {
		display: block;
		color: #667eea;
		margin-bottom: 0.5rem;
		font-size: 0.9rem;
	}

	.feedback-section p {
		color: #555;
		line-height: 1.6;
		margin: 0;
		padding: 0.75rem;
		background: #f9f9f9;
		border-radius: 4px;
		border-left: 3px solid #667eea;
	}

	.no-feedback-message {
		text-align: center;
		padding: 3rem 2rem;
		color: #999;
	}

	.no-feedback-message p {
		margin: 0;
		font-size: 1rem;
	}

	/* Already Submitted Message */
	.already-submitted-message {
		text-align: center;
		padding: 3rem 2rem;
	}

	.info-icon {
		width: 80px;
		height: 80px;
		margin: 0 auto 1.5rem;
		background: #2196f3;
		color: white;
		font-size: 3rem;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.already-submitted-message h4 {
		color: #2196f3;
		margin: 0 0 0.5rem;
		font-size: 1.5rem;
	}

	.already-submitted-message p {
		color: #666;
		margin: 0.5rem 0;
	}

	.info-text {
		color: #999;
		font-size: 0.9rem;
	}

	.lesson-info-box {
		background: #f0f4ff;
		border: 2px solid #667eea;
		border-radius: 8px;
		padding: 1rem;
		margin-bottom: 1.5rem;
	}

	.lesson-info-box p {
		margin: 0.5rem 0;
		color: #333;
		font-size: 0.95rem;
	}

	.lesson-info-box p:first-child {
		margin-top: 0;
	}

	.lesson-info-box p:last-child {
		margin-bottom: 0;
	}

	.lesson-info-box strong {
		color: #667eea;
	}

	/* Wochennavigation Styles */
	.week-navigation {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: white;
		padding: 1.5rem;
		border-radius: 12px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		margin-bottom: 1.5rem;
		gap: 1rem;
	}

	.week-info {
		text-align: center;
		flex: 1;
	}

	.week-info h3 {
		margin: 0 0 0.5rem;
		color: #667eea;
		font-size: 1.5rem;
		font-weight: 700;
	}

	.btn-week-nav {
		background: var(--primary);
		color: white;
		padding: 0.75rem 1.5rem;
		border: none;
		border-radius: 8px;
		font-weight: 600;
		cursor: pointer;
		transition: transform 0.2s, box-shadow 0.2s;
		white-space: nowrap;
	}

	.btn-week-nav:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
	}

	.btn-current-week {
		background: #f0f4ff;
		color: #667eea;
		padding: 0.5rem 1rem;
		border: 2px solid #667eea;
		border-radius: 6px;
		font-weight: 600;
		font-size: 0.9rem;
		cursor: pointer;
		transition: all 0.2s;
	}

	.btn-current-week:hover {
		background: #667eea;
		color: white;
	}

	.day-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 0.25rem;
	}

	.day-name {
		font-weight: 600;
		font-size: 1rem;
	}

	.day-date {
		font-size: 0.85rem;
		opacity: 0.8;
		font-weight: 400;
	}

	/* Radio Group Styles */
	.radio-group {
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
		padding: 0.5rem 0;
	}

	.radio-label {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		font-size: 0.95rem;
		color: #555;
		cursor: pointer;
		padding: 0.75rem;
		border: 2px solid #e1e1e1;
		border-radius: 6px;
		transition: all 0.2s;
		font-weight: 500;
	}

	.radio-label:hover {
		border-color: #667eea;
		background: #f9f9f9;
	}

	.radio-label input[type='radio'] {
		width: 18px;
		height: 18px;
		cursor: pointer;
		accent-color: #667eea;
	}

	.radio-label:has(input[type='radio']:checked) {
		border-color: #667eea;
		background: #f0f4ff;
		color: #667eea;
	}

	.date-input {
		width: 100%;
		padding: 0.75rem;
		border: 2px solid #e1e1e1;
		border-radius: 6px;
		font-size: 1rem;
		transition: border-color 0.2s;
		font-family: inherit;
	}

	.date-input:focus {
		outline: none;
		border-color: #667eea;
	}

	.form-hint {
		display: block;
		margin-top: 0.5rem;
		color: #999;
		font-size: 0.85rem;
		font-style: italic;
	}

	@media (max-width: 768px) {
		.content {
			padding: 1rem;
		}

		.header-section {
			flex-direction: column;
			align-items: flex-start;
		}

		.header-section h2 {
			font-size: 1.5rem;
		}

		.week-navigation {
			flex-direction: column;
			padding: 1rem;
		}

		.week-info h3 {
			font-size: 1.2rem;
		}

		.btn-week-nav {
			width: 100%;
			padding: 0.625rem 1rem;
			font-size: 0.9rem;
		}

		.day-header {
			gap: 0.1rem;
		}

		.day-name {
			font-size: 0.85rem;
		}

		.day-date {
			font-size: 0.75rem;
		}

		.timetable-table {
			min-width: 600px;
		}

		.timetable-table th,
		.time-cell,
		.entry-cell {
			font-size: 0.85rem;
			padding: 0.5rem;
		}

		.form-row {
			grid-template-columns: 1fr;
		}

		.tab-btn {
			font-size: 0.8rem;
			padding: 0.75rem 0.5rem;
		}

		.tab-content {
			padding: 1rem;
			min-height: 300px;
		}

		.modal-large {
			max-width: 95%;
		}

		.feedback-form-container {
			padding: 0 0.5rem;
		}

		.form-section-title {
			font-size: 1.1rem;
		}

		.rating-section,
		.rating-item {
			padding: 1rem;
		}

		.success-icon {
			width: 60px;
			height: 60px;
			font-size: 2rem;
		}
	}

	/* Grades Styles */
	.grades-content {
		padding: 0;
	}

	.grades-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 1.5rem;
		padding: 0 1rem;
	}

	.grades-header h4 {
		margin: 0;
		color: #333;
		font-size: 1.3rem;
	}

	.btn-add-grade {
		background: var(--primary);
		color: white;
		padding: 0.5rem 1rem;
		border: none;
		border-radius: 6px;
		font-weight: 600;
		cursor: pointer;
		transition: transform 0.2s, box-shadow 0.2s;
	}

	.btn-add-grade:hover {
		transform: translateY(-2px);
		box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
	}

	.grades-list {
		display: grid;
		gap: 1rem;
		padding: 0 1rem;
	}

	.grade-card {
		background: white;
		border: 1px solid #e0e0e0;
		border-radius: 8px;
		padding: 1rem;
		transition: box-shadow 0.2s;
	}

	.grade-card:hover {
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.grade-card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 0.75rem;
	}

	.grade-student-info {
		display: flex;
		align-items: center;
		gap: 0.75rem;
	}

	.grade-value {
		font-size: 1.5rem;
		font-weight: bold;
	}

	.grade-card-body {
		color: #666;
	}

	.grade-description {
		margin-top: 0.75rem;
		padding: 0.75rem;
		background: #f9f9f9;
		border-radius: 6px;
		font-size: 0.9rem;
		color: #555;
	}

	.grade-card-actions {
		display: flex;
		gap: 0.5rem;
		margin-top: 1rem;
		padding-top: 1rem;
		border-top: 1px solid #e0e0e0;
	}

	.btn-edit-small,
	.btn-delete-small {
		padding: 0.4rem 0.8rem;
		border: none;
		border-radius: 6px;
		font-size: 0.85rem;
		font-weight: 600;
		cursor: pointer;
		transition: all 0.2s;
	}

	.btn-edit-small {
		background: #2196f3;
		color: white;
	}

	.btn-edit-small:hover {
		background: #1976d2;
	}

	.btn-delete-small {
		background: #f44336;
		color: white;
	}

	.btn-delete-small:hover {
		background: #d32f2f;
	}

	.grade-card-student {
		background: white;
		border: 2px solid #e0e0e0;
		border-radius: 12px;
		padding: 2rem;
		text-align: center;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.grade-value-student {
		font-size: 4rem;
		font-weight: bold;
		margin-bottom: 1rem;
	}

	.grade-description-student {
		padding: 1rem;
		background: #f9f9f9;
		border-radius: 8px;
		color: #666;
		font-size: 1rem;
		margin-top: 1rem;
	}

	.grade-form {
		background: #f9f9f9;
		padding: 1.5rem;
		border-radius: 8px;
		margin: 0 1rem;
	}

	.form-actions {
		display: flex;
		gap: 1rem;
		justify-content: flex-end;
		margin-top: 1.5rem;
	}

	.empty-state {
		text-align: center;
		padding: 3rem 1rem;
	}

	.empty-icon {
		font-size: 4rem;
		margin-bottom: 1rem;
		opacity: 0.5;
	}

	.loading {
		text-align: center;
		padding: 2rem;
		color: #666;
	}

	/* Files UI Styles */
	.files-content {
		padding: 0;
	}

	.files-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 1.5rem;
	}

	.files-header h4 {
		margin: 0;
		color: #333;
		font-size: 1.3rem;
	}

	.files-list {
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
	}

	.file-item {
		display: flex;
		align-items: center;
		background: white;
		padding: 1rem;
		border: 1px solid #e0e0e0;
		border-radius: 8px;
		transition: box-shadow 0.2s;
	}

	.file-item:hover {
		box-shadow: 0 2px 8px rgba(0,0,0,0.05);
	}

	.file-icon {
		font-size: 1.5rem;
		margin-right: 1rem;
	}

	.file-info {
		flex: 1;
	}

	.file-name {
		font-weight: 600;
		color: #333;
		margin-bottom: 0.25rem;
	}

	.file-meta {
		font-size: 0.85rem;
		color: #666;
	}

	.file-actions {
		display: flex;
		gap: 0.5rem;
	}
</style>
