document.addEventListener('DOMContentLoaded', function () {
    const urlParams = new URLSearchParams(window.location.search);
    const jobId = urlParams.get('id');
    const slug = urlParams.get('slug');

    if (!jobId && !slug) {
        document.body.innerHTML = '<div style="text-align:center; padding: 3rem;"><h1>Job Link Invalid</h1></div>';
        return;
    }

    if (jobId) document.getElementById('job_id').value = jobId;
    // If we only have slug, we'll get ID from API response and set it then

    fetchJobDetails(jobId, slug);

    const form = document.getElementById('application-form');
    form.addEventListener('submit', handleApplicationSubmit);
});

function fetchJobDetails(id, slug) {
    const param = slug ? `slug=${slug}` : `id=${id}`;
    fetch(`api/apply.php?${param}`)
        .then(res => res.json())
        .then(job => {
            if (job.error) {
                document.body.innerHTML = '<div style="text-align:center; padding: 3rem;"><h1>Job Not Found</h1></div>';
                return;
            }

            // IMPORTANT: Set the hidden job_id field if we looked up by slug
            document.getElementById('job_id').value = job.id;

            document.getElementById('job-title').textContent = job.title;
            document.getElementById('job-department').textContent = job.department;
            document.getElementById('job-location').textContent = job.location;
            document.getElementById('job-type').textContent = job.type;
            document.getElementById('job-description').textContent = job.description; // Consider truncating if too long

            renderCustomQuestions(job.requirements);
        })
        .catch(err => console.error(err));
}

function renderCustomQuestions(requirementsJson) {
    if (!requirementsJson) return;

    try {
        const questions = JSON.parse(requirementsJson);
        if (!Array.isArray(questions) || questions.length === 0) return;

        const container = document.getElementById('custom-questions-area');
        container.innerHTML = '<div class="section-break"></div><h3 class="text-md font-bold mb-4">Additional Questions</h3>';

        questions.forEach((q, index) => {
            const group = document.createElement('div');
            group.className = 'form-group';

            const label = document.createElement('label');
            label.className = 'form-label';
            label.innerHTML = `${q.question} ${q.required ? '<span class="text-red-500">*</span>' : ''}`;

            let input;
            const inputName = `custom_q_${index}`; // We will map this back on server or just store array

            // Store the question text as a data attribute to send back easily
            group.dataset.question = q.question;

            if (q.type === 'Text Answer') {
                input = document.createElement('input');
                input.type = 'text';
                input.className = 'form-control';
            } else if (q.type === 'Multiple Choice') {
                input = document.createElement('select');
                input.className = 'form-control';
                input.innerHTML = '<option value="">Select an option...</option><option>Yes</option><option>No</option>'; // Simplified
            } else if (q.type === 'File Upload') {
                input = document.createElement('input');
                input.type = 'file';
                input.className = 'form-control';
            } else {
                input = document.createElement('input');
                input.type = 'text';
                input.className = 'form-control';
            }

            if (q.required) input.required = true;
            input.name = `answers[${index}]`; // Array syntax for PHP

            group.appendChild(label);
            group.appendChild(input);
            container.appendChild(group);
        });

    } catch (e) { console.error('Error rendering questions', e); }
}

function handleApplicationSubmit(e) {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    const originalText = btn.textContent;
    btn.textContent = 'Submitting...';
    btn.disabled = true;

    const formData = new FormData(e.target);

    // We also want to send the actual question text linked to the answer index
    // But for simplicity, we'll let the backend just store the array of answers provided
    // or we can reconstruct it. For now, sending standard FormData.

    fetch('api/apply.php', {
        method: 'POST',
        body: formData
    })
        .then(res => res.json())
        .then(result => {
            if (result.error) {
                alert(result.error);
            } else {
                document.querySelector('.apply-content').innerHTML = `
                <div style="text-align: center; padding: 3rem;">
                    <i class="fa-solid fa-circle-check text-green-500" style="font-size: 4rem; margin-bottom: 1rem;"></i>
                    <h2 class="text-2xl font-bold mb-2">Application Submitted!</h2>
                    <p class="text-muted">Thank you for applying. We will be in touch soon.</p>
                </div>
            `;
            }
        })
        .catch(err => {
            console.error(err);
            alert('An error occurred. Please try again.');
        })
        .finally(() => {
            if (btn) {
                btn.textContent = originalText;
                btn.disabled = false;
            }
        });
}
