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

function fetchDashboardData() {
    fetch('api/dashboard.php')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                console.error('API Error:', data.error);
                return;
            }
            updateStats(data.stats);
            updateRecentApplications(data.recent_applications);
            renderTodaysInterviews(data.todays_interviews);
        })
        .catch(error => console.error('Error fetching dashboard data:', error));
}

function renderTodaysInterviews(interviews) {
    const container = document.getElementById('todays-interviews-list');
    if (!container) return;

    container.innerHTML = '';

    if (!interviews || interviews.length === 0) {
        container.innerHTML = `
            <div class="text-muted" style="grid-column: 1 / -1; padding: 20px; background: white; border-radius: 8px; border: 1px solid #e5e7eb; text-align: center;">
                No interviews scheduled for today.
            </div>`;
        return;
    }

    interviews.forEach(interview => {
        const dateObj = new Date(interview.scheduled_at);
        const time = dateObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

        const card = `
            <div class="interview-card-today flex items-center justify-between gap-4" 
                 onclick="window.location.href='candidate-detail.html?id=${interview.candidate_id}'">
                <div class="flex items-center gap-4 flex-1 min-w-0">
                    <div class="avatar avatar-lg ${getRandomAvatarClass()} text-xl flex-shrink-0">${getInitials(interview.candidate_name)}</div>
                    <div class="min-w-0">
                        <h3 class="font-bold text-lg text-gray-900 mb-1 truncate">${interview.candidate_name}</h3>
                        <p class="text-gray-600 truncate">Interviewing for <span class="font-semibold text-primary">${interview.job_title}</span></p>
                    </div>
                </div>
                <div class="text-right flex-shrink-0">
                    <span class="interview-time-badge">${time}</span>
                    <div class="text-xs text-gray-400 font-semibold mt-2 uppercase tracking-wider">Today</div>
                </div>
            </div>
        `;
        container.innerHTML += card;
    });
}

function updateStats(stats) {
    if (!stats) return;
    document.getElementById('stat-total-applications').textContent = stats.total_applications || 0;
    document.getElementById('stat-interviews').textContent = stats.interviews_scheduled || 0;
    document.getElementById('stat-active-jobs').textContent = stats.active_jobs || 0;
}

function updateRecentApplications(applications) {
    const tbody = document.getElementById('recent-applications-body');
    tbody.innerHTML = '';

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

    applications.forEach(app => {
        const initials = getInitials(app.candidate_name);
        // Random color class for variety
        const colorClass = getRandomAvatarClass();

        const row = `
            <tr>
                <td>
                    <div class="flex items-center">
                        <div class="avatar avatar-sm ${colorClass}">${initials}</div>
                        <div>
                            <div class="font-bold">${app.candidate_name}</div>
                            <div class="text-muted text-sm text-sm-muted">${app.candidate_email}</div>
                        </div>
                    </div>
                </td>
                <td>${app.job_title}</td>
                <td>${formatDate(app.applied_date)}</td>
                <td>${getStatusBadge(app.status)}</td>
                <td>
                    <div class="flex items-center gap-2">
                        <div class="progress-bar-container">
                            <div class="progress-bar ${getProgressBarClass(app.match_score)}" style="width: ${app.match_score}%;"></div>
                        </div>
                        <span class="text-sm font-bold">${app.match_score}%</span>
                    </div>
                </td>
                <td>
                    <button class="btn btn-outline btn-icon-only" onclick="window.location.href='candidate-detail.html?id=${app.candidate_id}'">
                        <i class="fa-solid fa-ellipsis"></i>
                    </button>
                </td>
            </tr>
        `;
        tbody.innerHTML += row;
    });
}

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

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-info';
    switch (status.toLowerCase()) {
        case 'new': className = 'badge-success'; break; // Green for new
        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 navigateToCreateJob() {
    window.location.href = 'create-job.html';
}
