<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= title || 'EMTAF Bursary Portal' %></title>

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- Swiper CSS & JS (Updated to latest version) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/11.0.5/swiper-bundle.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/11.0.5/swiper-bundle.min.js"></script>

    <!-- Lucide Icons CDN (only load once) -->
    <script src="https://unpkg.com/lucide@latest"></script>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <!-- Tailwind Config -->
    <script nonce="<%= nonce %>">
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'headline': ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>

    <!-- Custom Styles -->
    <style nonce="<%= nonce %>">
        /* Import Inter font properly */
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

        /* Custom font for headlines */
        .font-headline {
            font-family: 'Inter', system-ui, sans-serif;
            font-weight: 700;
        }

        /* Smooth scroll behavior */
        html {
            scroll-behavior: smooth;
        }

        /* Custom styles for hero image */
        .hero-image {
            object-fit: cover;
            border-radius: 0.75rem;
        }

        /* Bursary card hover effect */
        .bursary-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .bursary-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        /* Loading spinner */
        .spinner {
            border: 2px solid #f3f4f6;
            border-top: 2px solid #3b82f6;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>


</head>
<body class="bg-gray-50 text-gray-900">
    <div class="flex min-h-screen flex-col">
        <%- include('../partials/header') %>
        <main class="flex-1">
            <%- body %>
        </main>
        <%- include('../partials/footer') %>
    </div>



    <!-- API Configuration -->
    <!-- <script nonce="<%= nonce %>">
        // Initialize API instance (since apiConfig.js might not exist)
        const api = axios.create({
        baseURL: window.location.hostname === 'localhost' ? 'http://localhost:3001' : '/api',
        timeout: 10000,
        headers: {
        'Content-Type': 'application/json',
        }
        });

        // Add request interceptor to include auth token
        api.interceptors.request.use(
        (config) => {
        const token = localStorage.getItem('jwtToken');
        if (token) {
        config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
        },
        (error) => {
        return Promise.reject(error);
        }
        );

        // Add response interceptor to handle auth errors
        api.interceptors.response.use(
        (response) => response,
        (error) => {
        if (error.response?.status === 401) {
        localStorage.removeItem('jwtToken');
        window.location.href = '/auth/login';
        }
        return Promise.reject(error);
        }
        );
    </script> -->

    <!-- Main Application Scripts -->
    <script nonce="<%= nonce %>">
        // Initialize Lucide icons
        document.addEventListener('DOMContentLoaded', () => {
            lucide.createIcons();

            // Smooth scroll for anchor links
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    const target = document.querySelector(this.getAttribute('href'));
                    if (target) {
                        target.scrollIntoView({ behavior: 'smooth' });
                    }
                });
            });
        });
    </script>

    <!-- Navigation Bar Script -->
    <script nonce="<%= nonce %>">
        document.addEventListener('DOMContentLoaded', async () => {
            const nav = document.getElementById('navbar-links');
            if (!nav) return;

            async function renderNavbar() {
                nav.innerHTML = '<div class="spinner"></div>'; // Show loading spinner

                const token = localStorage.getItem('jwtToken');

                if (token) {
                    try {
                        const response = await api.get('/api/v1/users/profile');
                        const user = response.data;
                        const userDisplayName = user.fullName || user.email || 'User';

                        nav.innerHTML = `
                            <div class="flex items-center space-x-4">
                                <span class="text-gray-600 flex items-center space-x-1" aria-label="Logged in user">
                                    <i data-lucide="user" class="h-5 w-5"></i>
                                    <span>${escapeHtml(userDisplayName)}</span>
                                </span>
                                <a href="/student/dashboard" class="text-gray-600 hover:text-blue-600 transition-colors" aria-label="Go to dashboard">Dashboard</a>
                                <button id="logout-btn" class="text-red-600 hover:text-red-800 transition-colors flex items-center space-x-1" aria-label="Log out">
                                    <i data-lucide="log-out" class="h-5 w-5"></i>
                                    <span>Logout</span>
                                </button>
                            </div>
                        `;

                        lucide.createIcons();

                        // Attach logout handler
                        document.getElementById('logout-btn').addEventListener('click', handleLogout);

                    } catch (err) {
                        console.error('Profile fetch error:', err);
                        localStorage.removeItem('jwtToken');
                        renderUnauthenticatedLinks();
                    }
                } else {
                    renderUnauthenticatedLinks();
                }
            }

            function renderUnauthenticatedLinks() {
                nav.innerHTML = `
                    <div class="flex items-center space-x-4">
                        <a href="/" class="text-gray-600 hover:text-blue-600 transition-colors">Home</a>
                        <a href="/auth/register" class="text-gray-600 hover:text-blue-600 transition-colors">Register</a>
                        <a href="/auth/login" class="text-gray-600 hover:text-blue-600 transition-colors flex items-center space-x-1">
                            <i data-lucide="log-in" class="h-5 w-5"></i>
                            <span>Login</span>
                        </a>
                    </div>
                `;
                lucide.createIcons();
            }

            async function handleLogout() {
                try {
                    await api.post('/api/v1/auth/logout');
                    localStorage.removeItem('jwtToken');

                    Swal.fire({
                        icon: 'success',
                        title: 'Logged Out',
                        text: 'You have been successfully logged out.',
                        timer: 1500,
                        showConfirmButton: false,
                        background: '#f9fafb',
                        iconColor: '#2563eb',
                    }).then(() => {
                        window.location.href = '/';
                    });
                } catch (err) {
                    console.error('Logout error:', err);
                    // Even if logout fails on server, clear local storage
                    localStorage.removeItem('jwtToken');
                    window.location.href = '/';
                }
            }

            // Utility function to escape HTML
            function escapeHtml(unsafe) {
                return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
            }

            // Initialize navbar
            await renderNavbar();
        });
    </script>

<!-- Load apiConfig.js if it exists (fallback) -->
    <script src="/js/apiConfig.js" onerror="console.log('apiConfig.js not found, using inline config')"></script>
</body>
</html>