document.addEventListener('DOMContentLoaded', function () {
    fetchJobs();
});

function fetchJobs() {
    fetch('api/jobs.php')
        .then(response => response.json())
        .then(data => {
            renderJobs(data);
        })
        .catch(error => console.error('Error fetching jobs:', error));
}

function renderJobs(jobs) {
    const tbody = document.getElementById('jobs-table-body');
    tbody.innerHTML = '';

    if (!jobs || jobs.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center p-4 text-muted">No jobs found. Create one!</td></tr>';
        return;
    }

    jobs.forEach(job => {
        const row = `
            <tr>
                <td>
                    <div class="font-bold">${job.title}</div>
                    <div class="text-muted text-sm text-sm-muted">${job.type}</div>
                </td>
                <td>${job.department}</td>
                <td>${job.location}</td>
                <td>${formatDate(job.posted_date)}</td>
                <td>${job.applicant_count || 0} Applicants</td>
                <td>${getStatusBadge(job.status)}</td>
                <td>
                    <div class="flex gap-2">
                        <button class="btn btn-outline btn-icon-only" title="View Details" onclick="window.location.href='job-detail.html?id=${job.id}'">
                            <i class="fa-regular fa-eye"></i>
                        </button>
                        <button class="btn btn-outline btn-icon-only" title="Edit" onclick="window.location.href='create-job.html?id=${job.id}'">
                            <i class="fa-regular fa-pen-to-square"></i>
                        </button>
                        <button class="btn btn-outline btn-icon-only" title="Copy Apply Link" onclick="copyJobLink(this, '${job.id}', '${job.slug || ''}')">
                            <i class="fa-solid fa-link"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
        tbody.innerHTML += row;
    });
}

function copyJobLink(btn, jobId, slug) {
    const param = slug ? `slug=${slug}` : `id=${jobId}`;
    const baseUrl = new URL('apply.html', window.location.href).href.split('?')[0]; // Clean base
    const url = `${baseUrl}?${param}`;
    navigator.clipboard.writeText(url).then(() => {
        const icon = btn.querySelector('i');
        icon.className = 'fa-solid fa-check text-green-500';
        setTimeout(() => icon.className = 'fa-solid fa-link', 2000);
    }).catch(err => {
        console.error('Failed to copy', err);
        prompt('Copy this link:', url);
    });
}

function formatDate(dateString) {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('en-US', options);
}

function getStatusBadge(status) {
    let className = 'badge-success';
    if (status === 'Closed') className = 'badge-danger'; // Or warning, but typically closed is red/grey
    if (status === 'Draft') className = 'badge-warning';

    // Use the existing badge classes if they match
    if (status === 'Active') className = 'badge-success';

    return `<span class="badge ${className}">${status}</span>`;
}
