<section class="w-full py-12 md:py-24 lg:py-32">
    <div class="container mx-auto px-4 md:px-6">
        <div class="mx-auto max-w-3xl">
            <div class="mb-8 space-y-2 text-center">
                <h1 class="font-headline text-3xl font-bold tracking-tight sm:text-4xl">
                    Create Bursary Application
                </h1>
                <p class="text-gray-500">
                    Complete the form below to apply for a bursary.
                </p>
            </div>
            <% if (error) { %>
                <div class="mb-6 text-red-600 text-sm text-center"><%= error %></div>
                <% } %>
                <form id="create-application-form" class="space-y-8">
                    <div class="bg-white shadow-lg rounded-lg">
                        <div class="p-6 flex items-center space-x-2">
                            <i data-lucide="award" class="h-6 w-6 text-blue-600"></i>
                            <h2 class="text-xl font-headline font-bold">Bursary Selection</h2>
                        </div>
                        <div class="p-6 pt-0">
                            <div class="space-y-2">
                                <label for="bursaryId" class="text-sm font-medium">Select Bursary</label>
                                <select
                                id="bursaryId"
                                name="bursaryId"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                aria-describedby="bursaryIdHelp"
                                >
                                <option value="">Select a bursary</option>
                            </select>
                            <p id="bursaryIdHelp" class="text-xs text-gray-500">Choose the bursary you are applying for.</p>
                        </div>
                    </div>
                </div>
                <div class="bg-white shadow-lg rounded-lg">
                    <div class="p-6 flex items-center space-x-2">
                        <i data-lucide="school" class="h-6 w-6 text-blue-600"></i>
                        <h2 class="text-xl font-headline font-bold">Academic Information</h2>
                    </div>
                    <div class="p-6 pt-0 grid grid-cols-1 gap-6 md:grid-cols-2">
                        <div class="space-y-2">
                            <label for="institution" class="text-sm font-medium">Tertiary Institution</label>
                            <select
                            id="institution"
                            name="institution"
                            required
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                            aria-describedby="institutionHelp"
                            >
                            <option value="" disabled selected>Select your institution</option>

                            <optgroup label="Public Universities">
                                <option value="University of Cape Town">University of Cape Town (UCT)</option>
                                <option value="University of the Witwatersrand">University of the Witwatersrand (Wits)</option>
                                <option value="University of Pretoria">University of Pretoria (UP)</option>
                                <option value="Stellenbosch University">Stellenbosch University (SU)</option>
                                <option value="University of Johannesburg">University of Johannesburg (UJ)</option>
                                <option value="University of KwaZulu-Natal">University of KwaZulu-Natal (UKZN)</option>
                                <option value="University of the Western Cape">University of the Western Cape (UWC)</option>
                                <option value="University of South Africa">University of South Africa (UNISA)</option>
                                <option value="University of Fort Hare">University of Fort Hare (UFH)</option>
                                <option value="North-West University">North-West University (NWU)</option>
                                <option value="Rhodes University">Rhodes University</option>
                                <option value="University of Limpopo">University of Limpopo</option>
                                <option value="University of Venda">University of Venda (UNIVEN)</option>
                                <option value="Walter Sisulu University">Walter Sisulu University (WSU)</option>
                                <option value="University of Zululand">University of Zululand (UZ)</option>
                            </optgroup>

                            <optgroup label="Universities of Technology">
                                <option value="Central University of Technology">Central University of Technology (CUT)</option>
                                <option value="Cape Peninsula University of Technology">Cape Peninsula University of Technology (CPUT)</option>
                                <option value="Durban University of Technology">Durban University of Technology (DUT)</option>
                                <option value="Mangosuthu University of Technology">Mangosuthu University of Technology (MUT)</option>
                                <option value="Nelson Mandela University">Nelson Mandela University (NMU)</option>
                                <option value="Tshwane University of Technology">Tshwane University of Technology (TUT)</option>
                                <option value="Vaal University of Technology">Vaal University of Technology (VUT)</option>
                            </optgroup>

                            <optgroup label="TVET Colleges">
                                <option value="Ekurhuleni East TVET College">Ekurhuleni East TVET College</option>
                                <option value="Ekurhuleni West TVET College">Ekurhuleni West TVET College</option>
                                <option value="South West Gauteng TVET College">South West Gauteng TVET College</option>
                                <option value="Tshwane South TVET College">Tshwane South TVET College</option>
                                <option value="Tshwane North TVET College">Tshwane North TVET College</option>
                                <option value="Sedibeng TVET College">Sedibeng TVET College</option>
                                <option value="Western TVET College">Western TVET College</option>
                                <option value="False Bay TVET College">False Bay TVET College</option>
                                <option value="Northlink TVET College">Northlink TVET College</option>
                                <option value="Boland TVET College">Boland TVET College</option>
                                <option value="Port Elizabeth TVET College">Port Elizabeth TVET College</option>
                                <option value="Buffalo City TVET College">Buffalo City TVET College</option>
                                <option value="Eastcape Midlands TVET College">Eastcape Midlands TVET College</option>
                                <option value="Central Johannesburg TVET College">Central Johannesburg TVET College</option>
                                <option value="Gert Sibande TVET College">Gert Sibande TVET College</option>
                            </optgroup>
                        </select>
                        <p id="institutionHelp" class="text-xs text-gray-500">Select your institution from the list.</p>
                    </div>

                    <div class="space-y-2">
                        <label for="qualification" class="text-sm font-medium">Qualification</label>
                        <input
                        id="qualification"
                        name="qualification"
                        required
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                        value=""
                        aria-describedby="qualificationHelp"
                        />
                        <p id="qualificationHelp" class="text-xs text-gray-500">E.g., BSc Computer Science</p>
                    </div>
                    <div class="space-y-2">
                        <label for="institutionType" class="text-sm font-medium">Institution Type</label>
                        <select
                        id="institutionType"
                        name="institutionType"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                        aria-describedby="institutionTypeHelp"
                        >
                        <option value="">Select Institution Type</option>
                        <option value="public">Public</option>
                        <option value="private">Private</option>
                    </select>
                    <p id="institutionTypeHelp" class="text-xs text-gray-500">Select whether your institution is public or private.</p>
                </div>
                <div class="space-y-2">
                    <label for="yearOfStudy" class="text-sm font-medium">Year of Study</label>
                    <input
                    id="yearOfStudy"
                    name="yearOfStudy"
                    type="number"
                    min="1"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                    aria-describedby="yearOfStudyHelp"
                    />
                    <p id="yearOfStudyHelp" class="text-xs text-gray-500">E.g., 1 for first year</p>
                </div>
                <div class="space-y-2">
                    <label for="academicYear" class="text-sm font-medium">Academic Year</label>
                    <input
                    id="academicYear"
                    name="academicYear"
                    type="number"
                    min="2000"
                    max="<%= new Date().getFullYear() + 1 %>"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                    aria-describedby="academicYearHelp"
                    />
                    <p id="academicYearHelp" class="text-xs text-gray-500">E.g., <%= new Date().getFullYear() %></p>
                </div>
                <div class="space-y-2">
                    <label for="studentType" class="text-sm font-medium">Student Type</label>
                    <select
                    id="studentType"
                    name="studentType"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                    aria-describedby="studentTypeHelp"
                    >
                    <option value="">Select Student Type</option>
                    <option value="new">New</option>
                    <option value="returning">Returning</option>
                </select>
                <p id="studentTypeHelp" class="text-xs text-gray-500">Select if you are a new or returning student.</p>
            </div>
        </div>
    </div>
    <div class="bg-white shadow-lg rounded-lg">
        <div class="p-6 flex items-center space-x-2">
            <i data-lucide="dollar-sign" class="h-6 w-6 text-blue-600"></i>
            <h2 class="text-xl font-headline font-bold">Financial Information</h2>
        </div>
        <div class="p-6 pt-0 grid grid-cols-1 gap-6 md:grid-cols-2">
            <div class="space-y-2">
                <label for="tuitionFee" class="text-sm font-medium">Tuition Fee</label>
                <input
                id="tuitionFee"
                name="tuitionFee"
                type="number"
                step="0.01"
                min="0"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                aria-describedby="tuitionFeeHelp"
                />
                <p id="tuitionFeeHelp" class="text-xs text-gray-500">Enter the tuition fee amount in ZAR.</p>
            </div>
            <div class="space-y-2">
                <label for="bookFee" class="text-sm font-medium">Book Fee</label>
                <input
                id="bookFee"
                name="bookFee"
                type="number"
                step="0.01"
                min="0"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                aria-describedby="bookFeeHelp"
                />
                <p id="bookFeeHelp" class="text-xs text-gray-500">Enter the book fee amount in ZAR.</p>
            </div>
            <div class="space-y-2">
                <label for="accommodationFee" class="text-sm font-medium">Accommodation Fee</label>
                <input
                id="accommodationFee"
                name="accommodationFee"
                type="number"
                step="0.01"
                min="0"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                aria-describedby="accommodationFeeHelp"
                />
                <p id="accommodationFeeHelp" class="text-xs text-gray-500">Enter the accommodation fee amount in ZAR.</p>
            </div>
            <div class="space-y-2">
                <label for="totalRequested" class="text-sm font-medium">Total Requested</label>
                <input
                id="totalRequested"
                name="totalRequested"
                type="number"
                step="0.01"
                min="0"
                required
                readonly
                class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-100"
                aria-describedby="totalRequestedHelp"
                />
                <p id="totalRequestedHelp" class="text-xs text-gray-500">Automatically calculated as the sum of tuition, book, and accommodation fees.</p>
            </div>
        </div>
    </div>
    <div class="bg-white shadow-lg rounded-lg">
        <div class="p-6 flex items-center space-x-2">
            <i data-lucide="file-text" class="h-6 w-6 text-blue-600"></i>
            <h2 class="text-xl font-headline font-bold">Additional Information</h2>
        </div>
        <div class="p-6 pt-0">
            <div class="space-y-2">
                <label for="motivation" class="text-sm font-medium">Motivation</label>
                <textarea
                id="motivation"
                name="motivation"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                rows="5"
                aria-describedby="motivationHelp"
                ></textarea>
                <p id="motivationHelp" class="text-xs text-gray-500">Provide a brief motivation for your application (optional, max 500 characters).</p>
            </div>
            <div class="mt-4 flex items-center space-x-2">
                <input
                id="disabilityStatus"
                name="disabilityStatus"
                type="checkbox"
                class="h-4 w-4 text-blue-600 focus:ring-blue-600 border-gray-300 rounded"aria-describedby="disabilityStatusHelp"
                />
                <label for="disabilityStatus" class="text-sm font-medium">I have a disability</label>
                <p id="disabilityStatusHelp" class="text-xs text-gray-500">Check if applicable.</p>
            </div>
        </div>
    </div>
    <div class="flex justify-between items-center">
        <a
        href="/student/dashboard"
        class="inline-flex items-center bg-gray-200 text-gray-700 px-6 py-3 rounded-md hover:bg-gray-300 transition"
        aria-label="Back to dashboard"
        >
        <i data-lucide="arrow-left" class="h-4 w-4 mr-2"></i> Back
    </a>
    <button
    type="submit"
    class="bg-blue-600 text-white px-6 py-3 rounded-md hover:bg-blue-700 transition flex items-center"
    aria-label="Submit application"
    id="submit-btn"
    >
    <i data-lucide="send" class="h-4 w-4 mr-2"></i> Submit Application
</button>
</div>
</form>
<div id="loading" class="hidden text-center text-gray-500 mt-4">
    <i data-lucide="loader" class="h-6 w-6 animate-spin inline-block"></i>
    Submitting application...
</div>
</div>
</div>
</section>

<script nonce="<%= nonce %>">
    const form = document.getElementById('create-application-form');
    const bursarySelect = document.getElementById('bursaryId');
    const tuitionFeeInput = document.getElementById('tuitionFee');
    const bookFeeInput = document.getElementById('bookFee');
    const accommodationFeeInput = document.getElementById('accommodationFee');
    const totalRequestedInput = document.getElementById('totalRequested');
    const submitBtn = document.getElementById('submit-btn');
    const loading = document.getElementById('loading');

    // Fetch bursaries from backend
    async function fetchBursaries() {
        try {
            // 🔐 Retrieve token
            const token = localStorage.getItem('jwtToken');
            if (!token) {
                return Swal.fire({ icon: 'error', title: 'Not Authenticated', text: 'Please log in to update your profile.' });
            }


            if (!token) {
                Swal.fire({
                    icon: 'error',
                    title: 'Session Expired',
                    text: 'Please log in again.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                }).then(() => {
                    window.location.href = '/auth/login';
                });
                return;
            }

            const response = await api.get('/api/v1/bursaries');

            const bursaries = response.data;
            if (!bursaries || bursaries.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No Bursaries Available',
                    text: 'No bursaries are currently available for application.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#f59e0b'
                });
                return;
            }

            bursaries.forEach(bursary => {
                const option = document.createElement('option');
                option.value = bursary.id;
                option.textContent = bursary.title;
                bursarySelect.appendChild(option);
            });
        } catch (err) {
            console.error('Error fetching bursaries:', err);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: err.response?.data?.message || 'Unable to load bursaries. Please try again later.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
        }
    }

    // Call fetchBursaries on page load
    fetchBursaries();

    // Real-time total calculation
    function updateTotalRequested() {
        const tuitionFee = parseFloat(tuitionFeeInput.value) || 0;
        const bookFee = parseFloat(bookFeeInput.value) || 0;
        const accommodationFee = parseFloat(accommodationFeeInput.value) || 0;
        const total = (tuitionFee + bookFee + accommodationFee).toFixed(2);
        totalRequestedInput.value = total;
    }

    tuitionFeeInput.addEventListener('input', updateTotalRequested);
    bookFeeInput.addEventListener('input', updateTotalRequested);
    accommodationFeeInput.addEventListener('input', updateTotalRequested);

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        submitBtn.disabled = true;
        loading.classList.remove('hidden');

        const formData = new FormData(form);
        const data = {
            qualification: formData.get('qualification'),
            institution: formData.get('institution'),
            institutionType: formData.get('institutionType'),
            yearOfStudy: formData.get('yearOfStudy'),
            academicYear: formData.get('academicYear'),
            studentType: formData.get('studentType'),
            tuitionFee: parseFloat(formData.get('tuitionFee')),
            bookFee: parseFloat(formData.get('bookFee')),
            accommodationFee: parseFloat(formData.get('accommodationFee')),
            totalRequested: parseFloat(formData.get('totalRequested')),
            bursaryId: formData.get('bursaryId'),
            motivation: formData.get('motivation'),
            disabilityStatus: formData.get('disabilityStatus') === 'on'
        };

        // Client-side validation
        if (!data.qualification || !data.institution || !data.bursaryId ||
        isNaN(data.tuitionFee) || isNaN(data.bookFee) || isNaN(data.accommodationFee) || isNaN(data.totalRequested)) {
            Swal.fire({
                icon: 'error',
                title: 'Missing Fields',
                text: 'All required fields must be filled.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            submitBtn.disabled = false;
            loading.classList.add('hidden');
            return;
        }

        const numericFields = [
        { id: 'tuitionFee', value: data.tuitionFee },
        { id: 'bookFee', value: data.bookFee },
        { id: 'accommodationFee', value: data.accommodationFee },
        { id: 'totalRequested', value: data.totalRequested }
        ];
        for (const field of numericFields) {
            if (isNaN(field.value) || field.value < 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Input',
                    text: `${field.id} must be a valid positive number.`,
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                });
                submitBtn.disabled = false;
                loading.classList.add('hidden');
                return;
            }
        }

        const calculatedTotal = (data.tuitionFee + data.bookFee + data.accommodationFee).toFixed(2);
        if (parseFloat(data.totalRequested).toFixed(2) !== calculatedTotal) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Total',
                text: 'Total requested must equal the sum of tuition, book, and accommodation fees.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            submitBtn.disabled = false;
            loading.classList.add('hidden');
            return;
        }

        if (data.yearOfStudy && (isNaN(data.yearOfStudy) || data.yearOfStudy < 1)) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Year',
                text: 'Year of study must be a positive number.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            submitBtn.disabled = false;
            loading.classList.add('hidden');
            return;
        }

        const currentYear = new Date().getFullYear();
        if (data.academicYear && (isNaN(data.academicYear) || data.academicYear < 2000 || data.academicYear > currentYear + 1)) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Academic Year',
                text: `Academic year must be between 2000 and ${currentYear + 1}.`,
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            submitBtn.disabled = false;
            loading.classList.add('hidden');
            return;
        }

        if (data.motivation && data.motivation.length > 500) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Motivation',
                text: 'Motivation must be 500 characters or less.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            submitBtn.disabled = false;
            loading.classList.add('hidden');
            return;
        }

        try {
            // 🔐 Retrieve token
            const token = localStorage.getItem('jwtToken');
            if (!token) {
                return Swal.fire({ icon: 'error', title: 'Not Authenticated', text: 'Please log in to update your profile.' });
            }


            if (!token) {
                Swal.fire({
                    icon: 'error',
                    title: 'Session Expired',
                    text: 'Please log in again.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                }).then(() => {
                    window.location.href = '/auth/login';
                });
                submitBtn.disabled = false;
                loading.classList.add('hidden');
                return;
            }

            const response = await api.post('/api/v1/applications', data);

            Swal.fire({
                icon: 'success',
                title: 'Application Submitted',
                text: `Your application has been submitted successfully.`,
                timer: 2000,
                showConfirmButton: false,
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#2563eb'
            }).then(() => {
                window.location.href = '/student/dashboard';
            });
        } catch (err) {
            console.error('Error submitting application:', err);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: err.response?.data?.message || 'An error occurred while submitting your application.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            submitBtn.disabled = false;
            loading.classList.add('hidden');
        }
    });

    // Initialize Lucide icons
    lucide.createIcons();
</script>