let currentPage = 1;
const limit = 10;
let totalCandidates = 0;

document.addEventListener('DOMContentLoaded', function () {
    fetchDepartments();
    setupEventListeners();
    fetchCandidates();
});

function fetchDepartments() {
    fetch('api/jobs.php')
        .then(response => response.json())
        .then(jobs => {
            if (!Array.isArray(jobs)) return;

            // Extract unique departments
            const departments = [...new Set(jobs.map(job => job.department).filter(Boolean))].sort();

            const deptSelect = document.getElementById('filter-department');
            departments.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept;
                option.textContent = dept;
                deptSelect.appendChild(option);
            });
        })
        .catch(err => console.error('Error fetching departments:', err));
}

function setupEventListeners() {
    // Search with debounce
    const searchInput = document.getElementById('search-input');
    let debounceTimer;
    searchInput.addEventListener('input', () => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            currentPage = 1;
            fetchCandidates();
        }, 300);
    });

    // Filters
    // Department Filter
    const deptFilter = document.getElementById('filter-department');
    if (deptFilter) {
        deptFilter.addEventListener('change', () => {
            currentPage = 1;
            fetchCandidates();
        });
    }

    document.getElementById('filter-status').addEventListener('change', () => {
        currentPage = 1;
        fetchCandidates();
    });

    document.getElementById('filter-sort').addEventListener('change', () => {
        currentPage = 1;
        fetchCandidates();
    });

    // Pagination
    document.getElementById('btn-prev').addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            fetchCandidates();
        }
    });

    document.getElementById('btn-next').addEventListener('click', () => {
        currentPage++;
        fetchCandidates();
    });
}

function fetchCandidates() {
    const search = document.getElementById('search-input').value;
    const department = document.getElementById('filter-department') ? document.getElementById('filter-department').value : '';
    const status = document.getElementById('filter-status').value;
    const sort = document.getElementById('filter-sort').value;

    const params = new URLSearchParams({
        page: currentPage,
        limit: limit,
        search: search,
        department: department,
        status: status,
        sort: sort
    });

    fetch(`api/candidates.php?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.data && data.pagination) {
                renderCandidates(data.data);
                updatePagination(data.pagination);
            } else {
                // Handle fallback if API returns just array (backward compatibility or error)
                renderCandidates(Array.isArray(data) ? data : []);
            }
        })
        .catch(error => console.error('Error fetching candidates:', error));
}

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

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

    candidates.forEach(candidate => {
        const initials = getInitials(candidate.full_name);
        const colorClass = getRandomAvatarClass();

        // Use latest application status if available, else 'New'
        const status = candidate.application_status || 'New';
        const matchScore = candidate.match_score || 0;
        const jobTitle = candidate.job_title || 'General';

        const row = `
            <tr class="clickable-row" onclick="window.location.href='candidate-detail.html?id=${candidate.id}'" style="cursor: pointer;">
                <td>
                    <div class="flex items-center">
                        <div class="avatar avatar-sm ${colorClass}">${initials}</div>
                        <div>
                            <div class="font-bold">${candidate.full_name}</div>
                            <div class="text-muted text-sm text-sm-muted">${candidate.email}</div>
                        </div>
                    </div>
                </td>
                <td>${jobTitle}</td>
                <td>${formatDate(candidate.created_at)}</td>
                <td>${getStatusBadge(status)}</td>
                <td>
                    <div class="flex items-center gap-2">
                        <div class="progress-bar-container">
                            <div class="progress-bar ${getProgressBarClass(matchScore)}" style="width: ${matchScore}%;"></div>
                        </div>
                        <span class="text-sm font-bold">${matchScore}%</span>
                    </div>
                </td>
                <td>
                    <button class="btn btn-outline btn-icon-only">
                        <i class="fa-solid fa-chevron-right"></i>
                    </button>
                </td>
            </tr>
        `;
        tbody.innerHTML += row;
    });
}

function updatePagination(pagination) {
    totalCandidates = pagination.total;
    const totalPages = pagination.total_pages;

    const start = (currentPage - 1) * limit + 1;
    const end = Math.min(currentPage * limit, totalCandidates);

    const infoText = totalCandidates > 0 ? `Showing ${start}-${end} of ${totalCandidates} candidates` : 'Showing 0 of 0 candidates';
    document.getElementById('pagination-info').textContent = infoText;

    // Also update top info if it exists
    const topInfo = document.getElementById('top-pagination-info');
    if (topInfo) {
        topInfo.textContent = infoText;
    }

    document.getElementById('btn-prev').disabled = currentPage <= 1;
    document.getElementById('btn-next').disabled = currentPage >= totalPages;
}

function getInitials(name) {
    if (!name) return '??';
    return name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
}

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

function getStatusBadge(status) {
    let className = 'badge-info';
    switch (status.toLowerCase()) {
        case 'new': className = 'badge-success'; break;
        case 'screening': className = 'badge-warning'; break;
        case 'interview': className = 'badge-info'; break;
        case 'rejected': className = 'badge-danger'; break;
        case 'offer': className = 'badge-success'; break;
    }
    return `<span class="badge ${className}">${status}</span>`;
}

function getProgressBarClass(score) {
    if (score >= 80) return 'progress-success';
    if (score >= 50) return 'progress-warning';
    return 'progress-danger';
}

function getRandomAvatarClass() {
    const classes = ['avatar-blue', 'avatar-pink', 'avatar-green', 'avatar-indigo', 'avatar-slate'];
    return classes[Math.floor(Math.random() * classes.length)];
}

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

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

    candidates.forEach(candidate => {
        const initials = getInitials(candidate.full_name);
        const colorClass = getRandomAvatarClass();

        // Use latest application status if available, else 'New'
        const status = candidate.application_status || 'New';
        const matchScore = candidate.match_score || 0;
        const jobTitle = candidate.job_title || 'General';

        const row = `
            <tr class="clickable-row" onclick="window.location.href='candidate-detail.html?id=${candidate.id}'" style="cursor: pointer;">
                <td>
                    <div class="flex items-center">
                        <div class="avatar avatar-sm ${colorClass}">${initials}</div>
                        <div>
                            <div class="font-bold">${candidate.full_name}</div>
                            <div class="text-muted text-sm text-sm-muted">${candidate.email}</div>
                        </div>
                    </div>
                </td>
                <td>${jobTitle}</td>
                <td>${formatDate(candidate.created_at)}</td>
                <td>${getStatusBadge(status)}</td>
                <td>${candidate.experience_years} Years</td>
                <td>
                    <div class="flex items-center gap-2">
                        <div class="progress-bar-container">
                            <div class="progress-bar ${getProgressBarClass(matchScore)}" style="width: ${matchScore}%;"></div>
                        </div>
                        <span class="text-sm font-bold">${matchScore}%</span>
                    </div>
                </td>
                <td>
                    <button class="btn btn-outline btn-icon-only">
                        <i class="fa-solid fa-chevron-right"></i>
                    </button>
                </td>
            </tr>
        `;
        tbody.innerHTML += row;
    });
}

function getInitials(name) {
    if (!name) return '??';
    return name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
}

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

function getStatusBadge(status) {
    let className = 'badge-info';
    switch (status.toLowerCase()) {
        case 'new': className = 'badge-success'; break;
        case 'screening': className = 'badge-warning'; break;
        case 'interview': className = 'badge-info'; break;
        case 'rejected': className = 'badge-danger'; break;
        case 'offer': className = 'badge-success'; break;
    }
    return `<span class="badge ${className}">${status}</span>`;
}

function getProgressBarClass(score) {
    if (score >= 80) return 'progress-success';
    if (score >= 50) return 'progress-warning';
    return 'progress-danger';
}

function getRandomAvatarClass() {
    const classes = ['avatar-blue', 'avatar-pink', 'avatar-green', 'avatar-indigo', 'avatar-slate'];
    return classes[Math.floor(Math.random() * classes.length)];
}
