<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { authStore } from '$lib/stores/auth.svelte.js';
	import { Send, User, Clock, Users, MessageSquare } from 'lucide-svelte';
	import { fade, fly } from 'svelte/transition';
    import { io, type Socket } from 'socket.io-client';

	interface ChatMessage {
		id?: number;
		type: 'chat' | 'system';
		message?: string;
		text?: string;
		username?: string;
		userId?: number;
		groupId?: number;
		timestamp: number;
	}

	interface ChatGroup {
		id: number;
		name: string;
		description?: string;
		createdById: number;
		members: {
			id: number;
			userId: number;
			user: {
				id: number;
				username: string;
				email: string;
				role: string;
			};
		}[];
		_count?: {
			messages: number;
			members: number;
		};
	}

	interface User {
		id: number;
		username: string;
		email: string;
		role: string;
	}

	let groups = $state<ChatGroup[]>([]);
	let currentGroup = $state<ChatGroup | null>(null);
	let messages = $state<ChatMessage[]>([]);
	let messageInput = $state('');
	let socket: Socket | null = null;
	let isConnected = $state(false);
	let error = $state<string | null>(null);
	let chatContainer = $state<HTMLDivElement>();
	let showCreateGroupModal = $state(false);
	let newGroupName = $state('');
	let newGroupDescription = $state('');
	let isLoading = $state(false);
	let showMembersModal = $state(false);
	let allUsers = $state<User[]>([]);
	let selectedUserIds = $state<number[]>([]);

	$effect(() => {
		if (!authStore.isLoading) {
			if (!authStore.isAuthenticated) {
				goto('/login');
			} else if (!socket) {
				loadGroups();
				connectToChat();
			}
		}
	});

	onDestroy(() => {
		if (socket && currentGroup) {
			socket.emit('leave-group', { groupId: currentGroup.id });
		}
		if (socket) {
			socket.disconnect();
		}
	});

	async function loadGroups() {
		try {
			const response = await fetch('http://localhost:3000/api/live/groups/my', {
				credentials: 'include'
			});

			if (response.ok) {
				groups = await response.json();
				// Erste Gruppe automatisch auswählen
				if (groups.length > 0 && !currentGroup) {
					await selectGroup(groups[0]);
				}
			}
		} catch (err) {
			console.error('Error loading groups:', err);
		}
	}

	async function selectGroup(group: ChatGroup) {
		// Alte Gruppe verlassen
		if (socket && currentGroup) {
			socket.emit('leave-group', { groupId: currentGroup.id });
		}

		currentGroup = group;
		messages = [];
		isLoading = true;

		try {
			// Nachrichten-Historie laden
			const response = await fetch(`http://localhost:3000/api/live/groups/${group.id}/messages`, {
				credentials: 'include'
			});

			if (response.ok) {
				const history = await response.json();
				messages = history.map((msg: any) => ({
					id: msg.id,
					type: 'chat',
					message: msg.content,
					username: msg.user.username,
					userId: msg.userId,
					groupId: msg.groupId,
					timestamp: new Date(msg.createdAt).getTime()
				}));
			}

			// Neuer Gruppe beitreten (via WebSocket)
			if (socket && isConnected) {
				socket.emit('join-group', { groupId: group.id });
			}
		} catch (err) {
			console.error('Error loading messages:', err);
			error = 'Fehler beim Laden der Nachrichten';
		} finally {
			isLoading = false;
		}

		// Auto-scroll nach unten
		setTimeout(() => {
			if (chatContainer) {
				chatContainer.scrollTop = chatContainer.scrollHeight;
			}
		}, 10);
	}

	function connectToChat() {
		console.log('Connecting to chat...');
		console.log('User authenticated:', authStore.isAuthenticated);

		// Socket.io Verbindung - das httpOnly Cookie wird automatisch mitgesendet
		socket = io('http://localhost:3000/api/live', {
			withCredentials: true,
			transports: ['websocket', 'polling']
		});

		socket.on('connect', () => {
			console.log('Connected to chat successfully!');
			isConnected = true;
			error = null;

			// Aktueller Gruppe beitreten, falls vorhanden
			if (currentGroup) {
				socket?.emit('join-group', { groupId: currentGroup.id });
			}
		});

		socket.on('disconnect', (reason) => {
			console.log('Disconnected from chat. Reason:', reason);
			isConnected = false;
		});

		socket.on('connect_error', (err) => {
			console.error('Connection error:', err);
			error = 'Verbindungsfehler: ' + (err.message || 'Unbekannter Fehler');
			isConnected = false;
		});

		socket.on('error', (err: any) => {
			console.error('Socket error:', err);
			error = err.message || 'Verbindungsfehler';
			isConnected = false;
		});

		socket.on('message', (data: ChatMessage) => {
			console.log('Received message:', data);

			// Nur Nachrichten der aktuellen Gruppe anzeigen
			if (!currentGroup || data.groupId === currentGroup.id) {
				messages = [...messages, data];

				// Auto-scroll nach unten
				setTimeout(() => {
					if (chatContainer) {
						chatContainer.scrollTop = chatContainer.scrollHeight;
					}
				}, 10);
			}
		});

		socket.on('joined-group', (data) => {
			console.log('Joined group:', data.groupId);
		});

		socket.on('left-group', (data) => {
			console.log('Left group:', data.groupId);
		});
	}

	function sendMessage() {
		if (!messageInput.trim() || !socket || !isConnected || !currentGroup) return;

		socket.emit('message', {
			message: messageInput.trim(),
			groupId: currentGroup.id
		});

		messageInput = '';
	}

	async function createGroup() {
		if (!newGroupName.trim()) return;

		try {
			const payload: any = {
				name: newGroupName.trim()
			};

			// Nur Beschreibung hinzufügen, wenn vorhanden
			if (newGroupDescription.trim()) {
				payload.description = newGroupDescription.trim();
			}

			const response = await fetch('http://localhost:3000/api/live/groups', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				credentials: 'include',
				body: JSON.stringify(payload)
			});

			if (response.ok) {
				const newGroup = await response.json();
				groups = [...groups, newGroup];
				showCreateGroupModal = false;
				newGroupName = '';
				newGroupDescription = '';
				await selectGroup(newGroup);
			} else {
				error = 'Fehler beim Erstellen der Gruppe';
			}
		} catch (err) {
			console.error('Error creating group:', err);
			error = 'Fehler beim Erstellen der Gruppe';
		}
	}

	async function deleteGroup(groupId: number) {
		if (!confirm('Möchten Sie diese Gruppe wirklich löschen?')) return;

		try {
			const response = await fetch(`http://localhost:3000/api/live/groups/${groupId}`, {
				method: 'DELETE',
				credentials: 'include'
			});

			if (response.ok) {
				groups = groups.filter((g) => g.id !== groupId);
				if (currentGroup?.id === groupId) {
					currentGroup = null;
					messages = [];
					if (groups.length > 0) {
						await selectGroup(groups[0]);
					}
				}
			} else {
				error = 'Fehler beim Löschen der Gruppe';
			}
		} catch (err) {
			console.error('Error deleting group:', err);
			error = 'Fehler beim Löschen der Gruppe';
		}
	}

	function isTeacher(): boolean {
		return authStore.user?.role === 'Lehrer';
	}

	function handleKeyPress(e: KeyboardEvent) {
		if (e.key === 'Enter' && !e.shiftKey) {
			e.preventDefault();
			sendMessage();
		}
	}

	function formatTime(timestamp: number): string {
		return new Date(timestamp).toLocaleTimeString('de-DE', {
			hour: '2-digit',
			minute: '2-digit'
		});
	}

	async function loadAllUsers() {
		try {
			const response = await fetch('http://localhost:3000/api/users', {
				credentials: 'include'
			});

			if (response.ok) {
				allUsers = await response.json();
			}
		} catch (err) {
			console.error('Error loading users:', err);
			error = 'Fehler beim Laden der Benutzerliste';
		}
	}

	async function openMembersModal() {
		if (!currentGroup) return;
		await loadAllUsers();
		showMembersModal = true;
	}

	async function addMembersToGroup() {
		if (!currentGroup || selectedUserIds.length === 0) return;

		try {
			const response = await fetch(`http://localhost:3000/api/live/groups/${currentGroup.id}/members`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				credentials: 'include',
				body: JSON.stringify({ userIds: selectedUserIds })
			});

			if (response.ok) {
				// Gruppe neu laden um aktualisierte Mitgliederliste zu bekommen
				await loadGroups();
				const updatedGroup = groups.find(g => g.id === currentGroup?.id);
				if (updatedGroup) {
					currentGroup = updatedGroup;
				}
				selectedUserIds = [];
				showMembersModal = false;
			} else {
				error = 'Fehler beim Hinzufügen von Mitgliedern';
			}
		} catch (err) {
			console.error('Error adding members:', err);
			error = 'Fehler beim Hinzufügen von Mitgliedern';
		}
	}

	async function removeMemberFromGroup(userId: number) {
		if (!currentGroup) return;
		if (!confirm('Möchten Sie dieses Mitglied wirklich entfernen?')) return;

		try {
			const response = await fetch(`http://localhost:3000/api/live/groups/${currentGroup.id}/members/${userId}`, {
				method: 'DELETE',
				credentials: 'include'
			});

			if (response.ok) {
				// Gruppe neu laden um aktualisierte Mitgliederliste zu bekommen
				await loadGroups();
				const updatedGroup = groups.find(g => g.id === currentGroup?.id);
				if (updatedGroup) {
					currentGroup = updatedGroup;
				}
			} else {
				const data = await response.json();
				error = data.message || 'Fehler beim Entfernen des Mitglieds';
			}
		} catch (err) {
			console.error('Error removing member:', err);
			error = 'Fehler beim Entfernen des Mitglieds';
		}
	}

	function isUserInGroup(userId: number): boolean {
		if (!currentGroup) return false;
		return currentGroup.members.some(m => m.userId === userId);
	}

	function toggleUserSelection(userId: number) {
		if (selectedUserIds.includes(userId)) {
			selectedUserIds = selectedUserIds.filter(id => id !== userId);
		} else {
			selectedUserIds = [...selectedUserIds, userId];
		}
	}

</script>

<div class="chat-page">
	<div class="content">
		<div class="chat-layout">
			<!-- Seitenleiste mit Gruppen -->
			<div class="sidebar">
				<div class="sidebar-header">
					<h3>Chat-Gruppen</h3>
					{#if isTeacher()}
						<button onclick={() => (showCreateGroupModal = true)} class="create-group-btn" title="Neue Gruppe erstellen">
							+
						</button>
					{/if}
				</div>

				<div class="groups-list">
					{#if groups.length === 0}
						<div class="no-groups">
							<p>Keine Gruppen vorhanden</p>
							{#if isTeacher()}
								<p class="hint">Erstelle eine neue Gruppe, um zu starten</p>
							{/if}
						</div>
					{:else}
						{#each groups as group}
							<div
								class="group-item"
								class:active={currentGroup?.id === group.id}
								role="button"
								tabindex="0"
								onclick={() => selectGroup(group)}
								onkeydown={(e) => e.key === 'Enter' || e.key === ' ' ? selectGroup(group) : null}
							>
								<div class="group-info">
									<div class="group-name">{group.name}</div>
									{#if group.description}
										<div class="group-description">{group.description}</div>
									{/if}
									<div class="group-meta">
										{group._count?.members || 0} Mitglieder
									</div>
								</div>
								{#if isTeacher()}
									<button
										onclick={(e) => {
											e.stopPropagation();
											deleteGroup(group.id);
										}}
										class="delete-group-btn"
										title="Gruppe löschen"
									>
										×
									</button>
								{/if}
							</div>
						{/each}
					{/if}
				</div>
			</div>

			<!-- Chat-Bereich -->
			<div class="chat-container">
				{#if currentGroup}
					<div class="chat-header">
						<div>
							<h2>{currentGroup.name}</h2>
							{#if currentGroup.description}
								<p class="group-desc">{currentGroup.description}</p>
							{/if}
						</div>
						<div class="header-actions">
							{#if isTeacher()}
								<button onclick={openMembersModal} class="manage-members-btn" title="Mitglieder verwalten">
									👥 Mitglieder verwalten
								</button>
							{/if}
							<div class="connection-status">
								{#if isConnected}
									<span class="status-indicator connected"></span>
									<span>Verbunden</span>
								{:else}
									<span class="status-indicator disconnected"></span>
									<span>Getrennt</span>
								{/if}
							</div>
						</div>
					</div>

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

					{#if isLoading}
						<div class="loading">Laden...</div>
					{:else}
						<div class="chat-messages" bind:this={chatContainer}>
							{#each messages as msg}
								{#if msg.type === 'system'}
									<div class="message system-message">
										<span class="message-text">{msg.text}</span>
									</div>
								{:else}
									<div
										class="message user-message"
										class:own-message={msg.userId === authStore.user?.id}
									>
										<div class="message-header">
											<span class="message-username">{msg.username}</span>
											<span class="message-time">{formatTime(msg.timestamp)}</span>
										</div>
										<div class="message-content">{msg.message}</div>
									</div>
								{/if}
							{/each}
						</div>
					{/if}

					<div class="chat-input-container">
						<input
							type="text"
							bind:value={messageInput}
							onkeypress={handleKeyPress}
							placeholder="Nachricht eingeben..."
							disabled={!isConnected}
							class="chat-input"
						/>
						<button
							onclick={sendMessage}
							disabled={!isConnected || !messageInput.trim()}
							class="send-btn"
						>
							Senden
						</button>
					</div>
				{:else}
					<div class="no-group-selected">
						<h2>Willkommen im Chat!</h2>
						<p>Wähle eine Gruppe aus der Seitenleiste, um zu starten.</p>
					</div>
				{/if}
			</div>
		</div>
	</div>
</div>

<!-- Modal zum Erstellen einer Gruppe -->
{#if showCreateGroupModal}
	<div class="modal-overlay" role="button" tabindex="0" onclick={() => (showCreateGroupModal = false)} onkeydown={(e) => e.key === 'Escape' && (showCreateGroupModal = false)}>
		<div class="modal" role="dialog" tabindex="-1" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
			<div class="modal-header">
				<h3>Neue Gruppe erstellen</h3>
				<button onclick={() => (showCreateGroupModal = false)} class="close-btn">×</button>
			</div>
			<div class="modal-body">
				<div class="form-group">
					<label for="group-name">Gruppenname *</label>
					<input
						id="group-name"
						type="text"
						bind:value={newGroupName}
						placeholder="z.B. Klasse 10A"
						class="form-input"
					/>
				</div>
				<div class="form-group">
					<label for="group-description">Beschreibung</label>
					<textarea
						id="group-description"
						bind:value={newGroupDescription}
						placeholder="Optional: Beschreibung der Gruppe"
						class="form-textarea"
						rows="3"
					></textarea>
				</div>
			</div>
			<div class="modal-footer">
				<button onclick={() => (showCreateGroupModal = false)} class="btn-secondary">
					Abbrechen
				</button>
				<button onclick={createGroup} disabled={!newGroupName.trim()} class="btn-primary">
					Erstellen
				</button>
			</div>
		</div>
	</div>
{/if}

<!-- Modal zur Mitgliederverwaltung -->
{#if showMembersModal && currentGroup}
	<div class="modal-overlay" role="button" tabindex="0" onclick={() => (showMembersModal = false)} onkeydown={(e) => e.key === 'Escape' && (showMembersModal = false)}>
		<div class="modal modal-large" role="dialog" tabindex="-1" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
			<div class="modal-header">
				<h3>Mitglieder verwalten - {currentGroup.name}</h3>
				<button onclick={() => (showMembersModal = false)} class="close-btn">×</button>
			</div>
			<div class="modal-body">
				<!-- Aktuelle Mitglieder -->
				<div class="members-section">
					<h4>Aktuelle Mitglieder ({currentGroup.members.length})</h4>
					<div class="members-list">
						{#each currentGroup.members as member}
							<div class="member-item">
								<div class="member-info">
									<span class="member-name">{member.user.username}</span>
									<span class="member-role">{member.user.role}</span>
								</div>
								{#if member.userId !== currentGroup.createdById}
									<button
										onclick={() => removeMemberFromGroup(member.userId)}
										class="remove-member-btn"
										title="Mitglied entfernen"
									>
										Entfernen
									</button>
								{:else}
									<span class="creator-badge">Ersteller</span>
								{/if}
							</div>
						{/each}
					</div>
				</div>

				<!-- Benutzer hinzufügen -->
				<div class="members-section">
					<h4>Benutzer hinzufügen</h4>
					<div class="users-list">
						{#each allUsers.filter(u => !isUserInGroup(u.id)) as user}
							<label class="user-checkbox-item">
								<input
									type="checkbox"
									checked={selectedUserIds.includes(user.id)}
									onchange={() => toggleUserSelection(user.id)}
								/>
								<div class="user-info">
									<span class="user-name">{user.username}</span>
									<span class="user-role">{user.role}</span>
								</div>
							</label>
						{/each}
						{#if allUsers.filter(u => !isUserInGroup(u.id)).length === 0}
							<p class="no-users">Alle Benutzer sind bereits Mitglieder dieser Gruppe.</p>
						{/if}
					</div>
				</div>
			</div>
			<div class="modal-footer">
				<button onclick={() => (showMembersModal = false)} class="btn-secondary">
					Schließen
				</button>
				<button
					onclick={addMembersToGroup}
					disabled={selectedUserIds.length === 0}
					class="btn-primary"
				>
					{selectedUserIds.length} Mitglied(er) hinzufügen
				</button>
			</div>
		</div>
	</div>
{/if}

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

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

	.chat-layout {
		display: grid;
		grid-template-columns: 300px 1fr;
		gap: 1.5rem;
		height: calc(100vh - 200px);
	}

	/* Sidebar Styles */
	.sidebar {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.sidebar-header {
		padding: 1.5rem;
		background: var(--primary);
		color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.sidebar-header h3 {
		margin: 0;
		font-size: 1.1rem;
	}

	.create-group-btn {
		background: rgba(255, 255, 255, 0.2);
		border: 2px solid white;
		color: white;
		width: 36px;
		height: 36px;
		border-radius: 50%;
		font-size: 1.5rem;
		cursor: pointer;
		transition: all 0.2s;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
	}

	.create-group-btn:hover {
		background: rgba(255, 255, 255, 0.3);
		transform: scale(1.1);
	}

	.groups-list {
		overflow-y: auto;
		flex: 1;
	}

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

	.no-groups .hint {
		font-size: 0.9rem;
		color: #999;
		margin-top: 0.5rem;
	}

	.group-item {
		padding: 1rem 1.5rem;
		border-bottom: 1px solid #e0e0e0;
		cursor: pointer;
		transition: background 0.2s;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.group-item:hover {
		background: #f8f9fa;
	}

	.group-item.active {
		background: #e8eaf6;
		border-left: 4px solid var(--primary);
	}

	.group-info {
		flex: 1;
		min-width: 0;
	}

	.group-name {
		font-weight: 600;
		color: #333;
		margin-bottom: 0.25rem;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.group-description {
		font-size: 0.85rem;
		color: #666;
		margin-bottom: 0.25rem;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.group-meta {
		font-size: 0.75rem;
		color: #999;
	}

	.delete-group-btn {
		background: #fee;
		border: none;
		color: #c33;
		width: 28px;
		height: 28px;
		border-radius: 50%;
		font-size: 1.5rem;
		cursor: pointer;
		transition: all 0.2s;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
		margin-left: 0.5rem;
		flex-shrink: 0;
	}

	.delete-group-btn:hover {
		background: #fcc;
	}

	/* Chat Container Styles */
	.chat-container {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.no-group-selected {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100%;
		color: #999;
		text-align: center;
		padding: 2rem;
	}

	.no-group-selected h2 {
		color: #666;
		margin-bottom: 1rem;
	}

	.loading {
		display: flex;
		align-items: center;
		justify-content: center;
		flex: 1;
		color: #999;
		font-size: 1.1rem;
	}

	.chat-header {
		padding: 1.5rem;
		border-bottom: 1px solid #e0e0e0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: var(--primary);
		color: white;
	}

	.chat-header h2 {
		margin: 0;
		font-size: 1.5rem;
	}

	.group-desc {
		margin: 0.5rem 0 0 0;
		font-size: 0.9rem;
		opacity: 0.9;
	}

	.connection-status {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		font-size: 0.9rem;
	}

	.status-indicator {
		width: 10px;
		height: 10px;
		border-radius: 50%;
		display: inline-block;
	}

	.status-indicator.connected {
		background: #4caf50;
		box-shadow: 0 0 8px #4caf50;
	}

	.status-indicator.disconnected {
		background: #f44336;
	}

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

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

	.chat-messages {
		flex: 1;
		overflow-y: auto;
		padding: 1.5rem;
		display: flex;
		flex-direction: column;
		gap: 1rem;
	}

	.message {
		max-width: 70%;
		animation: slideIn 0.2s ease-out;
	}

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

	.system-message {
		align-self: center;
		background: #f0f0f0;
		color: #666;
		padding: 0.5rem 1rem;
		border-radius: 20px;
		font-size: 0.85rem;
		max-width: 80%;
		text-align: center;
	}

	.user-message {
		align-self: flex-start;
		background: #f0f0f0;
		padding: 0.75rem 1rem;
		border-radius: 12px;
		border-top-left-radius: 4px;
	}

	.user-message.own-message {
		align-self: flex-end;
		background: var(--primary);
		color: white;
		border-radius: 12px;
		border-top-right-radius: 4px;
	}

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

	.message-username {
		font-weight: 600;
		font-size: 0.85rem;
	}

	.user-message.own-message .message-username {
		color: rgba(255, 255, 255, 0.9);
	}

	.message-time {
		font-size: 0.75rem;
		opacity: 0.7;
	}

	.message-content {
		word-wrap: break-word;
		line-height: 1.4;
	}

	.chat-input-container {
		padding: 1.5rem;
		border-top: 1px solid #e0e0e0;
		display: flex;
		gap: 1rem;
	}

	.chat-input {
		flex: 1;
		padding: 0.75rem 1rem;
		border: 2px solid #e1e1e1;
		border-radius: 8px;
		font-size: 1rem;
		transition: border-color 0.2s;
	}

	.chat-input:focus {
		outline: none;
		border-color: var(--primary);
	}

	.chat-input:disabled {
		background: #f5f5f5;
		cursor: not-allowed;
	}

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

	.send-btn:hover:not(:disabled) {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}

	.send-btn:disabled {
		opacity: 0.5;
		cursor: not-allowed;
		transform: none;
	}

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

	.modal {
		background: white;
		border-radius: 12px;
		max-width: 500px;
		width: 90%;
		box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
	}

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

	.modal-header h3 {
		margin: 0;
		font-size: 1.3rem;
	}

	.modal-body {
		padding: 1.5rem;
	}

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

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

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

	.form-input:focus,
	.form-textarea:focus {
		outline: none;
		border-color: var(--primary);
	}

	.form-textarea {
		resize: vertical;
	}

	.modal-footer {
		padding: 1.5rem;
		border-top: 1px solid #e0e0e0;
		display: flex;
		justify-content: flex-end;
		gap: 1rem;
	}

	.btn-primary,
	.btn-secondary {
		padding: 0.75rem 1.5rem;
		border-radius: 8px;
		font-weight: 600;
		cursor: pointer;
		transition: all 0.2s;
		border: none;
		font-size: 1rem;
	}

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

	.btn-primary:hover:not(:disabled) {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}

	.btn-primary:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

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

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

	/* Members Management Styles */
	.header-actions {
		display: flex;
		align-items: center;
		gap: 1rem;
	}

	.manage-members-btn {
		background: rgba(255, 255, 255, 0.2);
		border: 2px solid rgba(255, 255, 255, 0.6);
		color: white;
		padding: 0.5rem 1rem;
		border-radius: 8px;
		font-weight: 600;
		cursor: pointer;
		transition: all 0.2s;
		font-size: 0.9rem;
	}

	.manage-members-btn:hover {
		background: rgba(255, 255, 255, 0.3);
		transform: translateY(-2px);
	}

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

	.members-section {
		margin-bottom: 2rem;
	}

	.members-section:last-child {
		margin-bottom: 0;
	}

	.members-section h4 {
		margin: 0 0 1rem 0;
		color: #333;
		font-size: 1.1rem;
		padding-bottom: 0.5rem;
		border-bottom: 2px solid #e0e0e0;
	}

	.members-list,
	.users-list {
		max-height: 300px;
		overflow-y: auto;
		border: 1px solid #e0e0e0;
		border-radius: 8px;
		padding: 0.5rem;
	}

	.member-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0.75rem 1rem;
		border-radius: 6px;
		margin-bottom: 0.5rem;
		background: #f8f9fa;
		transition: background 0.2s;
	}

	.member-item:hover {
		background: #e9ecef;
	}

	.member-info,
	.user-info {
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
	}

	.member-name,
	.user-name {
		font-weight: 600;
		color: #333;
	}

	.member-role,
	.user-role {
		font-size: 0.85rem;
		color: #666;
	}

	.remove-member-btn {
		background: #fee;
		border: 1px solid #fcc;
		color: #c33;
		padding: 0.5rem 1rem;
		border-radius: 6px;
		font-weight: 600;
		cursor: pointer;
		transition: all 0.2s;
		font-size: 0.85rem;
	}

	.remove-member-btn:hover {
		background: #fcc;
		transform: translateY(-1px);
	}

	.creator-badge {
		background: var(--primary);
		color: white;
		padding: 0.5rem 1rem;
		border-radius: 6px;
		font-weight: 600;
		font-size: 0.85rem;
	}

	.user-checkbox-item {
		display: flex;
		align-items: center;
		gap: 1rem;
		padding: 0.75rem 1rem;
		border-radius: 6px;
		margin-bottom: 0.5rem;
		background: #f8f9fa;
		cursor: pointer;
		transition: background 0.2s;
	}

	.user-checkbox-item:hover {
		background: #e9ecef;
	}

	.user-checkbox-item input[type='checkbox'] {
		width: 20px;
		height: 20px;
		cursor: pointer;
	}

	.no-users {
		text-align: center;
		color: #999;
		padding: 2rem;
		font-style: italic;
	}

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

		.chat-layout {
			grid-template-columns: 1fr;
			height: auto;
		}

		.sidebar {
			height: 200px;
		}

		.chat-container {
			height: calc(100vh - 480px);
			min-height: 400px;
		}

		.message {
			max-width: 85%;
		}

		.send-btn {
			padding: 0.75rem 1rem;
		}
	}
</style>
