<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elite Academy Course Catalogue</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap');
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f7f9fb;
        }
        /* Custom styling for card transition */
        .course-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .course-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(17, 24, 39, 0.1);
        }
        .star-filled { color: #facc15; }
        .star-empty { color: #e5e7eb; }
    </style>
</head>
<body>

    <!-- Main Application Container -->
    <div class="min-h-screen">
        
        <!-- Header/Navigation Placeholder (Simple) -->
        <header class="bg-white shadow-md sticky top-0 z-10">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                <h1 class="text-2xl font-bold text-indigo-700">Elite Academics</h1>
                <div class="flex items-center space-x-4">
                    <!-- Cart Count Badge -->
                    <span id="cartCount" class="bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full absolute -top-1 right-4 sm:right-6 lg:right-8 hidden">0</span>
                    <button class="text-gray-600 hover:text-indigo-600 p-2 rounded-full relative">
                        <!-- Shopping Cart Icon (using lucide-react equivalent SVG) -->
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shopping-cart"><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.15"/></svg>
                    </button>
                </div>
            </div>
        </header>

        <!-- Catalogue Hero Section -->
        <div class="bg-indigo-600 py-16 text-white">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
                <h2 class="text-5xl font-extrabold mb-3">Explore Our Course Catalogue</h2>
                <p class="text-xl opacity-90">Find the perfect course to advance your career and skills.</p>
                <div class="mt-8 max-w-2xl mx-auto">
                    <!-- Search Input -->
                    <input type="text" id="searchInput" placeholder="Search courses, instructors, or keywords..." class="w-full p-4 rounded-xl text-gray-900 shadow-xl focus:ring-2 focus:ring-white focus:outline-none" onkeyup="filterCourses()">
                </div>
            </div>
        </div>

        <!-- Course Listings and Filters -->
        <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <div class="lg:grid lg:grid-cols-4 lg:gap-8">
                
                <!-- Filters Column -->
                <aside class="lg:col-span-1 mb-8 lg:mb-0">
                    <div class="bg-white p-6 rounded-xl shadow-lg sticky top-24 border border-gray-100">
                        <h3 class="text-xl font-bold text-gray-800 mb-6 border-b pb-3">Filter Options</h3>

                        <!-- Category Filter -->
                        <div class="mb-6">
                            <label for="categoryFilter" class="block text-sm font-semibold text-gray-700 mb-2">Category</label>
                            <select id="categoryFilter" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500" onchange="filterCourses()">
                                <option value="">All Categories</option>
                                <option value="Programming">Programming</option>
                                <option value="Design">Design</option>
                                <option value="Business">Business</option>
                                <option value="Marketing">Marketing</option>
                            </select>
                        </div>

                        <!-- Level Filter -->
                        <div class="mb-6">
                            <label for="levelFilter" class="block text-sm font-semibold text-gray-700 mb-2">Level</label>
                            <select id="levelFilter" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500" onchange="filterCourses()">
                                <option value="">All Levels</option>
                                <option value="Beginner">Beginner</option>
                                <option value="Intermediate">Intermediate</option>
                                <option value="Advanced">Advanced</option>
                            </select>
                        </div>

                        <!-- Sorting -->
                        <div class="mb-0">
                            <label for="sortOrder" class="block text-sm font-semibold text-gray-700 mb-2">Sort By</label>
                            <select id="sortOrder" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500" onchange="filterCourses()">
                                <option value="newest">Newest First</option>
                                <option value="priceAsc">Price: Low to High</option>
                                <option value="priceDesc">Price: High to Low</option>
                                <option value="rating">Highest Rated</option>
                            </select>
                        </div>
                    </div>
                </aside>

                <!-- Course Cards Column -->
                <div class="lg:col-span-3">
                    <!-- This class ensures 4 courses per row on extra-large screens: xl:grid-cols-4 -->
                    <div id="courseList" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6">
                        <!-- Course cards will be injected here by JavaScript -->
                    </div>
                    
                    <!-- No Results Message -->
                    <div id="noResults" class="hidden text-center py-12 bg-white rounded-xl shadow-lg mt-8">
                        <p class="text-xl text-gray-600 font-semibold">No courses match your current filters.</p>
                        <p class="text-gray-500 mt-2">Try adjusting your search query or filters.</p>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // --- Mock Data (Based on fields inferred from the course catalogue structure) ---
        const mockCourses = [
            { id: 101, title: "Advanced Data Structures in Python", short_description: "Master algorithms and complex data structures for technical interviews.", thumbnail: "https://placehold.co/600x400/10b981/ffffff?text=Algorithms", price: 99.99, currency: "USD", level: "Advanced", duration_hours: 45, category_name: "Programming", category_color: "bg-green-600", instructor_name: "Anya Smith", average_rating: 4.8, review_count: 1200, enrollment_count: 5500, created_at: "2024-10-01" },
            { id: 102, title: "Figma UI/UX Design Fundamentals", short_description: "Learn to design beautiful, user-friendly interfaces from scratch using Figma.", thumbnail: "https://placehold.co/600x400/3b82f6/ffffff?text=Figma+Design", price: 49.99, currency: "USD", level: "Beginner", duration_hours: 20, category_name: "Design", category_color: "bg-blue-500", instructor_name: "Mark Johnson", average_rating: 4.5, review_count: 850, enrollment_count: 3200, created_at: "2024-11-15" },
            { id: 103, title: "The Complete MBA Course: Business Strategy", short_description: "Essential concepts in finance, strategy, and leadership for modern managers.", thumbnail: "https://placehold.co/600x400/ef4444/ffffff?text=Business+Strategy", price: 199.99, currency: "USD", level: "Intermediate", duration_hours: 60, category_name: "Business", category_color: "bg-red-500", instructor_name: "Dr. Elena Cortez", average_rating: 4.9, review_count: 2100, enrollment_count: 9800, created_at: "2024-09-20" },
            { id: 104, title: "Digital Marketing Masterclass 2025", short_description: "SEO, SEM, social media, and content marketing strategies that convert.", thumbnail: "https://placehold.co/600x400/f97316/ffffff?text=Digital+Marketing", price: 79.99, currency: "USD", level: "Intermediate", duration_hours: 35, category_name: "Marketing", category_color: "bg-orange-500", instructor_name: "Alex Reed", average_rating: 4.6, review_count: 620, enrollment_count: 4100, created_at: "2024-11-05" },
            { id: 105, title: "Introduction to HTML, CSS, and JavaScript", short_description: "The absolute basics of web development to build your first simple website.", thumbnail: "https://placehold.co/600x400/14b8a6/ffffff?text=Web+Dev+Beginner", price: 0.00, currency: "USD", level: "Beginner", duration_hours: 15, category_name: "Programming", category_color: "bg-green-600", instructor_name: "Sam Chen", average_rating: 4.7, review_count: 3500, enrollment_count: 15000, created_at: "2024-08-01" },
            { id: 106, title: "Logo Design and Branding Identity", short_description: "Create memorable logos and comprehensive brand systems.", thumbnail: "https://placehold.co/600x400/4f46e5/ffffff?text=Logo+Design", price: 89.00, currency: "USD", level: "Intermediate", duration_hours: 28, category_name: "Design", category_color: "bg-blue-500", instructor_name: "Emily Clark", average_rating: 4.4, review_count: 410, enrollment_count: 2800, created_at: "2024-07-25" },
        ];

        // --- Utility Functions ---

        /**
         * Generates the star rating HTML structure.
         * @param {number} rating - The average rating (0-5).
         * @returns {string} HTML string for stars.
         */
        function renderStars(rating) {
            const fullStars = Math.floor(rating);
            const halfStar = rating % 1 >= 0.5;
            const emptyStars = 5 - fullStars - (halfStar ? 1 : 0);
            
            let stars = '';
            // Full stars
            for (let i = 0; i < fullStars; i++) {
                stars += `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 star-filled inline-block" viewBox="0 0 20 20" fill="currentColor"><path d="M9.049 2.927c.3-.921 1.65-.921 1.95 0l2.121 6.495 6.83.504c.95.07.72 1.34-0.19 1.91l-5.26 3.73 2.01 6.82c.27 1.25-1.07 1.83-1.63 1.15L10 16.14l-5.83 3.65c-.56.35-1.89-0.27-1.62-1.44l2.01-6.82-5.26-3.73c-.92-.57-.92-1.92 0-2.02l6.83-.504L9.049 2.927z"/></svg>`;
            }
            // Half star (clipped)
            if (halfStar) {
                stars += `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 star-filled inline-block" viewBox="0 0 20 20" fill="currentColor"><defs><clipPath id="half-star"><rect x="0" y="0" width="10" height="20"/></clipPath></defs><path d="M9.049 2.927c.3-.921 1.65-.921 1.95 0l2.121 6.495 6.83.504c.95.07.72 1.34-0.19 1.91l-5.26 3.73 2.01 6.82c.27 1.25-1.07 1.83-1.63 1.15L10 16.14l-5.83 3.65c-.56.35-1.89-0.27-1.62-1.44l2.01-6.82-5.26-3.73c-.92-.57-.92-1.92 0-2.02l6.83-.504L9.049 2.927z" clip-path="url(#half-star)"/></svg>`;
            }
            // Empty stars
            for (let i = 0; i < emptyStars; i++) {
                stars += `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 star-empty inline-block" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9.049 2.927c.3-.921 1.65-.921 1.95 0l2.121 6.495 6.83.504c.95.07.72 1.34-0.19 1.91l-5.26 3.73 2.01 6.82c.27 1.25-1.07 1.83-1.63 1.15L10 16.14l-5.83 3.65c-.56.35-1.89-0.27-1.62-1.44l2.01-6.82-5.26-3.73c-.92-.57-.92-1.92 0-2.02l6.83-.504L9.049 2.927z"/></svg>`;
            }
            return stars;
        }

        /**
         * Renders a single course card HTML.
         * @param {object} course - The course data object.
         * @returns {string} The HTML for the course card.
         */
        function renderCourseCard(course) {
            const priceText = course.price === 0.00 ? 'Free' : `${course.currency} ${course.price.toFixed(2)}`;
            const priceClass = course.price === 0.00 ? 'text-green-600 font-extrabold' : 'text-indigo-600 font-extrabold';
            
            return `
                <div class="course-card bg-white rounded-xl shadow-xl overflow-hidden flex flex-col border border-gray-100">
                    <div class="aspect-video w-full overflow-hidden">
                        <img src="${course.thumbnail}" onerror="this.onerror=null;this.src='https://placehold.co/600x400/94a3b8/ffffff?text=Course+Image'" alt="${course.title} thumbnail" class="w-full h-full object-cover">
                    </div>
                    <div class="p-6 flex flex-col flex-grow">
                        <div class="flex justify-between items-start mb-3">
                            <span class="${course.category_color} text-white text-xs font-semibold px-3 py-1 rounded-full uppercase tracking-wider shadow-md">
                                ${course.category_name}
                            </span>
                            <span class="text-xs font-medium text-gray-500 bg-gray-100 px-3 py-1 rounded-full">${course.level}</span>
                        </div>
                        
                        <h3 class="text-xl font-bold text-gray-900 mb-2 leading-snug">${course.title}</h3>
                        <p class="text-gray-600 text-sm flex-grow mb-4">${course.short_description}</p>
                        
                        <div class="flex items-center space-x-1 mb-4">
                            ${renderStars(course.average_rating)}
                            <span class="text-sm font-semibold text-gray-800 ml-1">${course.average_rating.toFixed(1)}</span>
                            <span class="text-xs text-gray-500">(${course.review_count} reviews)</span>
                        </div>

                        <div class="flex justify-between items-center pt-4 border-t border-gray-100">
                            <span class="text-lg ${priceClass}">
                                ${priceText}
                            </span>
                            <button 
                                onclick="addToCart(${course.id}, '${course.title}')" 
                                class="bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold py-2 px-4 rounded-lg shadow-lg shadow-indigo-200 transition duration-200 flex items-center"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                                </svg>
                                Enroll Now
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }

        /**
         * The core function to filter, sort, and display the courses.
         */
        function filterCourses() {
            const searchInput = document.getElementById('searchInput').value.toLowerCase();
            const categoryFilter = document.getElementById('categoryFilter').value;
            const levelFilter = document.getElementById('levelFilter').value;
            const sortOrder = document.getElementById('sortOrder').value;
            const courseListEl = document.getElementById('courseList');
            const noResultsEl = document.getElementById('noResults');

            // 1. Filtering
            let filteredCourses = mockCourses.filter(course => {
                const searchMatch = course.title.toLowerCase().includes(searchInput) ||
                                    course.short_description.toLowerCase().includes(searchInput) ||
                                    course.instructor_name.toLowerCase().includes(searchInput);
                
                const categoryMatch = !categoryFilter || course.category_name === categoryFilter;
                const levelMatch = !levelFilter || course.level === levelFilter;

                return searchMatch && categoryMatch && levelMatch;
            });

            // 2. Sorting
            filteredCourses.sort((a, b) => {
                switch (sortOrder) {
                    case 'priceAsc':
                        return a.price - b.price;
                    case 'priceDesc':
                        return b.price - a.price;
                    case 'rating':
                        return b.average_rating - a.average_rating;
                    case 'newest':
                    default:
                        // Sort by created_at date descending
                        return new Date(b.created_at) - new Date(a.created_at);
                }
            });

            // 3. Rendering
            if (filteredCourses.length === 0) {
                courseListEl.innerHTML = '';
                noResultsEl.classList.remove('hidden');
            } else {
                courseListEl.innerHTML = filteredCourses.map(renderCourseCard).join('');
                noResultsEl.classList.add('hidden');
            }
        }

        /**
         * Simulates the 'Add to Cart' function using local storage and a custom modal.
         * @param {number} courseId - The ID of the course.
         * @param {string} courseTitle - The title of the course.
         */
        function addToCart(courseId, courseTitle) {
            // Use an array in localStorage to simulate multiple items, or just one for simplicity
            let cart = JSON.parse(localStorage.getItem('cart') || '[]');
            const alreadyInCart = cart.some(item => item.id === courseId);
            
            let message;
            if (alreadyInCart) {
                message = `${courseTitle} is already in your cart.`;
            } else {
                // Simulate adding to cart
                cart.push({ id: courseId, title: courseTitle });
                localStorage.setItem('cart', JSON.stringify(cart));
                message = `${courseTitle} has been added to your cart!`;
            }

            updateCartCount(cart.length);
            showCustomModal(message, alreadyInCart);
        }

        /**
         * Updates the cart count display.
         * @param {number} count - The item count to display.
         */
        function updateCartCount(count) {
            const cartBadge = document.getElementById('cartCount');
            if (cartBadge) {
                cartBadge.textContent = count || 0;
                cartBadge.classList.toggle('hidden', count === 0);
            }
        }

        /**
         * Shows a custom modal message (replaces forbidden alert/confirm).
         * @param {string} message - The main message.
         * @param {boolean} alreadyInCart - True if the item was already present.
         */
        function showCustomModal(message, alreadyInCart) {
            const modalHtml = `
                <div id="cartModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 p-4">
                    <div class="bg-white rounded-xl shadow-2xl p-8 max-w-sm w-full transform transition-all duration-300 scale-100">
                        <h4 class="text-2xl font-bold text-indigo-600 mb-4">${alreadyInCart ? 'Already Added' : 'Success!'}</h4>
                        <p class="text-gray-700 mb-6">${message}</p>
                        <p class="text-gray-500 mb-6">Would you like to proceed to checkout?</p>
                        <div class="flex justify-end space-x-3">
                            <button onclick="closeModal(false)" class="bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-lg hover:bg-gray-300 transition">
                                Continue Browsing
                            </button>
                            <button onclick="closeModal(true)" class="bg-indigo-600 text-white font-medium py-2 px-4 rounded-lg hover:bg-indigo-700 transition shadow-md">
                                Go to Checkout
                            </button>
                        </div>
                    </div>
                </div>
            `;
            // Append modal to body
            document.body.insertAdjacentHTML('beforeend', modalHtml);
        }

        /**
         * Closes the custom modal and performs the checkout redirect if requested.
         * @param {boolean} proceed - True to simulate redirect.
         */
        function closeModal(proceed) {
            const modal = document.getElementById('cartModal');
            if (modal) {
                modal.remove();
            }
            if (proceed) {
                // Simulate window.location.href = '../checkout.php';
                console.log('Simulating redirect to checkout...');
                // Using console.log instead of alert for better user experience
                // alert('Simulated Redirect: You would now be taken to the checkout page.');
            }
        }

        // --- Initialization ---
        document.addEventListener('DOMContentLoaded', function() {
            // Initial render of all courses
            filterCourses();
            
            // Set initial cart state
            let cart = JSON.parse(localStorage.getItem('cart') || '[]');
            updateCartCount(cart.length);
        });

    </script>

</body>
</html>