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

    if (jobId) {
        fetchJobDetails(jobId);
    } else {
        alert('No Job ID specified');
        window.location.href = 'jobs.html';
    }
});

function fetchJobDetails(id) {
    fetch(`api/jobs.php?id=${id}`)
        .then(res => res.json())
        .then(job => {
            if (job.error) throw new Error(job.error);
            renderJobDetails(job);
        })
        .catch(err => {
            console.error(err);
            alert('Failed to load job details');
        });
}

function renderJobDetails(job) {
    // Header & Meta
    setText('job-title-display', job.title);
    setText('job-department', job.department);
    setText('job-location', job.location);
    setText('job-type', job.type);
    setText('job-posted-date', new Date(job.posted_date).toLocaleDateString());

    // Status Badge
    const statusBadge = document.getElementById('job-status-badge');
    statusBadge.textContent = job.status;
    statusBadge.className = `badge ${getBadgeClass(job.status)}`;

    // Description
    setText('job-description', job.description || 'No description provided.');

    // Edit Button
    document.getElementById('btn-edit-job').onclick = () => {
        window.location.href = `create-job.html?id=${job.id}`;
    };

    // View Public Posting Button
    const viewPublicBtn = document.getElementById('btn-view-public');
    if (viewPublicBtn) {
        viewPublicBtn.onclick = () => {
            window.open(`apply.html?id=${job.id}`, '_blank');
        };
    }

    // Copy Link Button
    const copyBtn = document.getElementById('btn-copy-link');
    if (copyBtn) {
        copyBtn.onclick = () => {
            const param = job.slug ? `slug=${job.slug}` : `id=${job.id}`;
            const baseUrl = new URL('apply.html', window.location.href).href.split('?')[0];
            const url = `${baseUrl}?${param}`;
            navigator.clipboard.writeText(url).then(() => {
                const originalText = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="fa-solid fa-check"></i> Copied!';
                setTimeout(() => copyBtn.innerHTML = originalText, 2000);
            }).catch(err => {
                console.error('Failed to copy', err);
                prompt('Copy this link:', url);
            });
        };
    }

    // Questions / Requirements
    const questionsContainer = document.getElementById('job-questions');

    // Create list
    const list = document.createElement('ul');
    list.style.paddingLeft = '1.2rem';

    // 1. Add Standard Fields (Always present)
    const standardFields = [
        { label: 'Full Name', type: 'Text input' },
        { label: 'Email Address', type: 'Email input' },
        { label: 'Resume / CV', type: 'File upload' }
    ];

    standardFields.forEach(field => {
        const li = document.createElement('li');
        li.innerHTML = `<strong>${field.label}</strong> <span class="text-xs text-muted">(${field.type}) *Standard</span>`;
        list.appendChild(li);
    });

    // 2. Add Custom Questions
    if (job.requirements) {
        try {
            const questions = JSON.parse(job.requirements);
            if (Array.isArray(questions) && questions.length > 0) {
                questions.forEach(q => {
                    const li = document.createElement('li');
                    li.innerHTML = `<strong>${q.question}</strong> <span class="text-xs text-muted">(${q.type})${q.required ? ' *Required' : ''}</span>`;
                    list.appendChild(li);
                });
            }
        } catch (e) {
            // If plain text, append as a note
            const li = document.createElement('li');
            li.innerHTML = `<em>${job.requirements}</em>`;
            list.appendChild(li);
        }
    }

    questionsContainer.innerHTML = '';
    questionsContainer.appendChild(list);
}

function setText(id, text) {
    const el = document.getElementById(id);
    if (el) el.textContent = text;
}

function getBadgeClass(status) {
    if (status === 'Active') return 'badge-success';
    if (status === 'Draft') return 'badge-draft';
    if (status === 'Closed') return 'badge-danger';
    return 'badge-secondary';
}
