<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
$lms_config = require '../../config/lms.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Handle filters and search
$search = $_GET['search'] ?? '';
$type_filter = $_GET['type'] ?? '';
$status_filter = $_GET['status'] ?? '';
$course_filter = $_GET['course'] ?? '';

// Build query
$query = "
    SELECT e.*, c.title as course_title,
            COUNT(eq.id) as question_count,
            COUNT(DISTINCT ea.student_id) as attempt_count
    FROM exams e
    LEFT JOIN courses c ON e.course_id = c.id
    LEFT JOIN exam_questions eq ON e.id = eq.exam_id
    LEFT JOIN exam_attempts ea ON e.id = ea.exam_id
";

$params = [];

if (!empty($search)) {
    $query .= " AND (e.title LIKE ? OR e.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($type_filter)) {
    $query .= " AND e.exam_type = ?";
    $params[] = $type_filter;
}

if (!empty($status_filter)) {
    $query .= " AND e.status = ?";
    $params[] = $status_filter;
}

if (!empty($course_filter)) {
    $query .= " AND e.course_id = ?";
    $params[] = $course_filter;
}

$query .= " GROUP BY e.id ORDER BY e.created_at DESC";

// Get exams
$stmt = $db->prepare($query);
$stmt->execute($params);
$exams = $stmt->fetchAll();

// Get filter options
$courses = $db->prepare("SELECT id, title FROM courses ORDER BY title")->fetchAll();

$page_title = 'Exams - ' . $lms_config['lms']['site_name'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: var(--success); }
        .toast-error { background-color: var(--danger); }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- Toast Notification Container -->
<div id="toast-container"></div>

<!-- Sidebar Overlay (for closing sidebar on mobile tap outside) -->
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="flex">
    <!-- Sidebar Navigation (Desktop View) -->
    <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen">
        <div class="flex flex-col h-full">
            <!-- Logo/Title -->
            <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                <?php echo htmlspecialchars($lms_config['lms']['site_name']); ?>
            </div>

            <!-- Navigation Links -->
            <nav class="space-y-2 flex-grow">
                <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🏠</span>
                    <span>Dashboard</span>
                </a>
                <a href="courses/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">📚</span>
                    <span>My Courses</span>
                </a>
                <a href="courses/new.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">➕</span>
                    <span>Create Course</span>
                </a>
                <a href="/lms/instructor/questions/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">❓</span>
                    <span>Question Bank</span>
                </a>
                <a href="/lms/instructor/exams/index.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                    <span class="w-5 h-5">📝</span>
                    <span>Exams & Quizzes</span>
                </a>
                <a href="students.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">👥</span>
                    <span>My Students</span>
                </a>
                <a href="resources.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">📖</span>
                    <span>Resources</span>
                </a>
                <a href="/lms/instructor/grading/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🏆</span>
                    <span>Grades</span>
                </a>
                <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🚪</span>
                    <span>Logout</span>
                </a>
            </nav>

            <!-- Footer/User Info (Bottom of Sidebar) -->
            <div class="mt-8 pt-4 border-t border-accent-subtle">
                <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'Instructor'); ?></p>
            </div>
        </div>
    </aside>

    <!-- Top Bar (Mobile/Desktop Header) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../assets/images/logo_1757657555.jpg" alt="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600">Exams & Quizzes</p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></span>
                <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'I'), 0, 1); ?>" alt="User Avatar">
                <!-- Mobile Menu Button (Hamburger) -->
                <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                    <span class="text-xl">☰</span>
                </button>
            </div>
        </div>
    </header>

    <!-- Main Content Area -->
    <main class="flex-1 overflow-y-auto pt-16">

        <!-- Mobile Navigation Overlay (Hidden by default) -->
        <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
            <div class="flex justify-between items-center mb-10">
                <div class="text-xl font-extrabold text-primary-blue tracking-wider"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></div>
                <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
            </div>
            <nav class="space-y-4">
                <a href="dashboard.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                <a href="courses/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📚 My Courses</a>
                <a href="courses/new.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">➕ Create Course</a>
                <a href="/lms/instructor/questions/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">❓ Question Bank</a>
                <a href="/lms/instructor/exams/index.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">📝 Exams & Quizzes</a>
                <a href="/lms/instructor/exams/new.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📋 Create Exam</a>
                <a href="students.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">👥 My Students</a>
                <a href="resources.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 Resources</a>
                <a href="/lms/instructor/grading/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏆 Grades</a>
                <a href="../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</a>
            </nav>
        </div>

        <!-- Display Messages -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="mb-6 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
                <span class="block sm:inline"><?php echo htmlspecialchars($_SESSION['success_message']); ?></span>
                <span class="absolute top-0 bottom-0 right-0 px-4 py-3" onclick="this.parentElement.style.display='none'">
                    <svg class="fill-current h-6 w-6 text-green-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                        <title>Close</title>
                        <path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/>
                    </svg>
                </span>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="mb-6 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
                <span class="block sm:inline"><?php echo htmlspecialchars($_SESSION['error_message']); ?></span>
                <span class="absolute top-0 bottom-0 right-0 px-4 py-3" onclick="this.parentElement.style.display='none'">
                    <svg class="fill-current h-6 w-6 text-red-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                        <title>Close</title>
                        <path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/>
                    </svg>
                </span>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Exams Content -->
        <div class="p-6">

            <!-- Filters -->
            <div class="filter-section bg-white p-6 rounded-xl shadow-lg border border-accent-subtle mb-8">
                <div class="filter-form">
                    <div class="filter-row grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                        <div class="filter-group">
                            <label for="search" class="block text-sm font-medium text-gray-700 mb-1"><i class="fas fa-search me-1"></i>Search</label>
                            <input type="text" id="search" class="form-control" name="search" placeholder="Search exams..." value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="filter-group">
                            <label for="type" class="block text-sm font-medium text-gray-700 mb-1"><i class="fas fa-list me-1"></i>Exam Type</label>
                            <select class="form-select" id="type" name="type">
                                <option value="">All Types</option>
                                <option value="quiz" <?php echo $type_filter === 'quiz' ? 'selected' : ''; ?>>Quiz</option>
                                <option value="midterm" <?php echo $type_filter === 'midterm' ? 'selected' : ''; ?>>Midterm</option>
                                <option value="final" <?php echo $type_filter === 'final' ? 'selected' : ''; ?>>Final</option>
                                <option value="practice" <?php echo $type_filter === 'practice' ? 'selected' : ''; ?>>Practice</option>
                                <option value="certification" <?php echo $type_filter === 'certification' ? 'selected' : ''; ?>>Certification</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label for="status" class="block text-sm font-medium text-gray-700 mb-1"><i class="fas fa-info-circle me-1"></i>Status</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">All Status</option>
                                <option value="draft" <?php echo $status_filter === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                <option value="published" <?php echo $status_filter === 'published' ? 'selected' : ''; ?>>Published</option>
                                <option value="archived" <?php echo $status_filter === 'archived' ? 'selected' : ''; ?>>Archived</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label for="course" class="block text-sm font-medium text-gray-700 mb-1"><i class="fas fa-book me-1"></i>Course</label>
                            <select class="form-select" id="course" name="course">
                                <option value="">All Courses</option>
                                <?php foreach ($courses as $course): ?>
                                    <option value="<?php echo $course['id']; ?>" <?php echo $course_filter == $course['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($course['title']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="filter-actions flex items-end space-x-2">
                            <button type="submit" class="btn btn-primary px-4 py-2 rounded-lg">Apply Filters</button>
                            <a href="index.php" class="btn btn-outline-secondary px-4 py-2 rounded-lg">Clear</a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Exams List -->
            <div class="exams-grid-container bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                <div class="grid-header mb-6">
                    <h3 class="text-2xl font-bold text-gray-800"><i class="fas fa-clipboard-list me-2"></i>Exams (<?php echo count($exams); ?>)</h3>
                </div>

                <?php if (empty($exams)): ?>
                    <div class="empty-state text-center py-12">
                        <div class="empty-state-icon w-20 h-20 bg-blue-500 rounded-full flex items-center justify-center text-white text-3xl mx-auto mb-4">
                            <i class="fas fa-clipboard-list"></i>
                        </div>
                        <h3 class="text-xl font-bold text-gray-800 mb-2">No Exams Found</h3>
                        <p class="text-gray-600 mb-6">Start creating assessments to evaluate your students' knowledge and skills.</p>
                        <a href="new.php" class="btn btn-primary px-6 py-3 rounded-lg inline-block">Create Your First Exam</a>
                    </div>
                <?php else: ?>
                    <div class="exams-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($exams as $exam): ?>
                            <div class="exam-card bg-white border border-gray-200 p-6 rounded-xl shadow-md hover:shadow-lg transition">
                                <div class="exam-card-header flex justify-between items-start mb-4">
                                    <div class="exam-title-section">
                                        <h4 class="text-lg font-bold text-gray-800 mb-2"><?php echo htmlspecialchars($exam['title']); ?></h4>
                                        <span class="exam-type-badge inline-block px-3 py-1 rounded-full text-xs font-semibold uppercase <?php echo $exam['exam_type']; ?>">
                                            <?php echo ucfirst($exam['exam_type']); ?>
                                        </span>
                                    </div>
                                    <div class="exam-status-section">
                                        <span class="status-badge inline-block px-2 py-1 rounded-full text-xs font-semibold uppercase <?php
                                            echo $exam['status'] === 'published' ? 'bg-green-100 text-green-800' :
                                                 ($exam['status'] === 'draft' ? 'bg-gray-100 text-gray-800' : 'bg-yellow-100 text-yellow-800');
                                        ?>">
                                            <?php echo ucfirst($exam['status']); ?>
                                        </span>
                                    </div>
                                </div>

                                <div class="exam-card-body mb-4">
                                    <?php if ($exam['description']): ?>
                                        <p class="exam-description text-gray-600 text-sm mb-4">
                                            <?php echo htmlspecialchars(substr($exam['description'], 0, 120)); ?><?php echo strlen($exam['description']) > 120 ? '...' : ''; ?>
                                        </p>
                                    <?php endif; ?>

                                    <div class="exam-stats grid grid-cols-3 gap-4 mb-4">
                                        <div class="stat-item text-center">
                                            <div class="stat-value text-xl font-bold text-blue-600"><?php echo $exam['question_count']; ?></div>
                                            <div class="stat-label text-xs text-gray-500 uppercase">Questions</div>
                                        </div>
                                        <div class="stat-item text-center">
                                            <div class="stat-value text-xl font-bold text-purple-600"><?php echo $exam['total_points']; ?></div>
                                            <div class="stat-label text-xs text-gray-500 uppercase">Points</div>
                                        </div>
                                        <div class="stat-item text-center">
                                            <div class="stat-value text-xl font-bold text-green-600"><?php echo $exam['attempt_count']; ?></div>
                                            <div class="stat-label text-xs text-gray-500 uppercase">Attempts</div>
                                        </div>
                                    </div>

                                    <div class="exam-details flex flex-wrap gap-4 mb-4">
                                        <?php if ($exam['time_limit']): ?>
                                            <div class="detail-item flex items-center text-sm text-gray-600">
                                                <i class="fas fa-clock mr-1 text-blue-500"></i>
                                                <span><?php echo $exam['time_limit']; ?> min</span>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($exam['passing_score']): ?>
                                            <div class="detail-item flex items-center text-sm text-gray-600">
                                                <i class="fas fa-trophy mr-1 text-yellow-500"></i>
                                                <span><?php echo $exam['passing_score']; ?>% pass</span>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($exam['course_title']): ?>
                                            <div class="detail-item flex items-center text-sm text-gray-600">
                                                <i class="fas fa-book mr-1 text-green-500"></i>
                                                <span><?php echo htmlspecialchars($exam['course_title']); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div class="exam-card-footer bg-gray-50 p-4 rounded-b-xl">
                                    <div class="exam-actions flex justify-center space-x-2">
                                        <button class="action-btn edit bg-blue-500 text-white px-3 py-2 rounded-lg text-sm hover:bg-blue-600 transition" onclick="window.location.href='edit.php?id=<?php echo $exam['id']; ?>'">
                                            <i class="fas fa-edit mr-1"></i>Edit
                                        </button>
                                        <button class="action-btn enroll bg-purple-500 text-white px-3 py-2 rounded-lg text-sm hover:bg-purple-600 transition" onclick="window.location.href='assignments.php?exam_id=<?php echo $exam['id']; ?>'">
                                            <i class="fas fa-user-plus mr-1"></i>Enroll Students
                                        </button>
                                        <button class="action-btn preview bg-gray-500 text-white px-3 py-2 rounded-lg text-sm hover:bg-gray-600 transition" onclick="previewExam(<?php echo $exam['id']; ?>)">
                                            <i class="fas fa-eye mr-1"></i>Preview
                                        </button>
                                        <button class="action-btn results bg-green-500 text-white px-3 py-2 rounded-lg text-sm hover:bg-green-600 transition" onclick="viewResults(<?php echo $exam['id']; ?>)">
                                            <i class="fas fa-chart-bar mr-1"></i>Results
                                        </button>
                                        <button class="action-btn delete bg-red-500 text-white px-3 py-2 rounded-lg text-sm hover:bg-red-600 transition" onclick="deleteExam(<?php echo $exam['id']; ?>, '<?php echo htmlspecialchars($exam['title']); ?>')">
                                            <i class="fas fa-trash mr-1"></i>Delete
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<script>
    function previewExam(examId) {
        window.open('preview.php?id=' + examId, '_blank');
    }

    function viewResults(examId) {
        window.location.href = 'results.php?id=' + examId;
    }

    function deleteExam(examId, examTitle) {
        if (confirm('Are you sure you want to delete the exam "' + examTitle + '"? This action cannot be undone.')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'delete.php';

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'exam_id';
            input.value = examId;

            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }
    }

    // --- UI/Utility Functions ---

    // Function to show a dismissible toast notification
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`; // Note: 'show' added below
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>${message}`;
        container.appendChild(toast);

        // Force repaint to start transition
        setTimeout(() => toast.classList.add('show'), 10);

        // Auto-dismiss after 4 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            // Remove from DOM after transition finishes
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }

    // Mobile Menu Functionality
    const mobileMenuButton = document.getElementById('mobileMenuButton');
    const closeMobileMenu = document.getElementById('closeMobileMenu');
    const mobileMenu = document.getElementById('mobileMenu');

    if (mobileMenuButton && closeMobileMenu && mobileMenu) {
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.remove('-translate-x-full');
        });

        closeMobileMenu.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });

        // Close menu when a link is clicked
        mobileMenu.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });
        });
    }
</script>

</body>
</html>