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

    if (candidateId) {
        fetchCandidateDetail(candidateId);
    } else {
        document.querySelector('.content-area').innerHTML = '<div class="p-6 text-center text-muted">No candidate selected</div>';
    }
});

let currentCandidateId = null;
let currentApplicationId = null;
let currentScheduledAt = null;

function fetchCandidateDetail(id) {
    // Note: The API currently returns { profile: ..., applications: [...] }
    // Ideally we should pass Application ID, but for now we pass Candidate ID and take the latest application.
    fetch(`api/candidates.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                console.error(data.error);
                return;
            }
            renderCandidateProfile(data);
        })
        .catch(error => console.error('Error fetching candidate details:', error));
}

function renderCandidateProfile(data) {
    const profile = data.profile;
    const applications = data.applications || [];

    currentCandidateId = profile.id;

    // 1. Basic Profile
    document.querySelector('.profile-name').textContent = profile.full_name;
    document.querySelector('.profile-avatar').textContent = getInitials(profile.full_name);
    document.querySelector('.profile-avatar').className = `profile-avatar ${getRandomAvatarClass()}`;

    document.getElementById('cand-email').textContent = profile.email;
    document.getElementById('cand-phone').textContent = profile.phone || '-';

    // 2. Resume Handling
    if (profile.resume_path) {
        // Construct path - assumes uploads/resumes is accessible relative to web root
        // The path in DB might be `../uploads/resumes/filename` or `uploads/resumes/filename`
        // We need to clean it to be browser accessible. 
        // Assuming `recuirtment-portal-UI` is root, and `uploads` is sibling? 
        // Based on `api/apply.php`, uploads is `../uploads/resumes/`. Use `../` relative to UI file?
        // Actually, if we are at `http://localhost/recuirtment-portal-UI/candidate-detail.html`,
        // and uploads are at `d:\xampp\htdocs\recuirtment-portal-UI\uploads`, then:
        let cleanPath = profile.resume_path.replace('../', '');

        document.getElementById('resume-filename').textContent = 'Resume Document';

        const btnDownload = document.getElementById('btn-download-resume');
        const btnOpen = document.getElementById('btn-open-resume');

        btnDownload.href = cleanPath;
        btnOpen.href = cleanPath;

        // Preview if PDF
        const viewer = document.getElementById('resume-viewer');
        if (cleanPath.toLowerCase().endsWith('.pdf')) {
            viewer.innerHTML = `<iframe src="${cleanPath}" style="width: 100%; height: 100%; border: none;"></iframe>`;
        } else {
            // Preview Image
            if (cleanPath.match(/\.(jpg|jpeg|png|webp)$/i)) {
                viewer.innerHTML = `<img src="${cleanPath}" class="max-w-full max-h-full object-contain">`;
            } else {
                viewer.innerHTML = `
                    <div class="text-center p-8">
                        <i class="fa-regular fa-file text-4xl text-muted mb-3"></i>
                        <p class="text-muted mb-4">Preview not available for this file type.</p>
                        <a href="${cleanPath}" target="_blank" class="btn btn-primary">Download File</a>
                    </div>
                 `;
            }
        }
    } else {
        document.getElementById('resume-viewer').innerHTML = '<div class="text-center p-8 text-muted">No resume uploaded.</div>';
    }


    // 3. Application Details (Latest)
    const latestApp = applications.length > 0 ? applications[0] : null;
    if (latestApp) {
        currentApplicationId = latestApp.id;
        currentScheduledAt = latestApp.scheduled_at; // Store for modal

        // Status
        const badge = document.getElementById('application-status-badge');
        badge.className = `badge ${getStatusBadgeClass(latestApp.status)}`;
        badge.textContent = latestApp.status;

        // Job Title
        document.getElementById('job-title-display').textContent = latestApp.job_title;

        // Match Score
        const score = latestApp.match_score || 0;
        document.getElementById('match-score-container').style.display = 'block';
        document.getElementById('match-score-value').textContent = score + '%';
        const bar = document.getElementById('match-score-bar');
        bar.style.width = score + '%';
        bar.className = `progress-bar ${getProgressBarClass(score)}`;

        // Update Buttons based on status
        updateActionButtons(latestApp.status);

        // Answers
        const answersContainer = document.getElementById('answers-list');
        answersContainer.innerHTML = '';

        let answers = [];
        let questions = [];

        try {
            answers = typeof latestApp.answers === 'string' ? JSON.parse(latestApp.answers) : latestApp.answers;
        } catch (e) { console.error('Error parsing answers', e); }

        try {
            // Requirements (Questions) from Job
            if (latestApp.requirements) {
                questions = JSON.parse(latestApp.requirements);
            }
        } catch (e) { console.error('Error parsing requirements', e); }

        if (Array.isArray(answers) && answers.length > 0) {
            answers.forEach((ans, idx) => {
                const div = document.createElement('div');
                div.className = 'mb-4';

                // Determine Label
                let label = `Question ${idx + 1}`;
                if (questions && questions[idx]) {
                    label = questions[idx].question || label;
                }

                // Display
                div.innerHTML = `
                    <div class="rounded-lg border border-gray-200 overflow-hidden bg-white shadow-sm">
                        <div class="px-4 py-3 border-b border-gray-100" style="background-color: #f8f9fa;">
                            <div class="text-xs font-bold text-gray-700 uppercase tracking-wider" style="color: #374151;">
                                <i class="fa-regular fa-circle-question mr-1 text-primary" style="color: var(--primary-color);"></i> ${label}
                            </div>
                        </div>
                        <div class="p-4">
                            <div class="text-sm text-gray-800 leading-relaxed font-medium">
                                ${ans}
                            </div>
                        </div>
                    </div>
                `;
                answersContainer.appendChild(div);
            });
        } else {
            answersContainer.innerHTML = '<span class="text-muted italic text-sm">No custom answers provided.</span>';
        }

        // Cover Letter
        if (latestApp.cover_letter) {
            document.getElementById('cover-letter-section').style.display = 'block';
            document.getElementById('cover-letter-text').textContent = latestApp.cover_letter;
        }

    } else {
        document.getElementById('application-status-badge').textContent = 'No Active Application';
        document.getElementById('job-title-display').textContent = 'Candidate Pool';
    }
}

async function updateStatus(newStatus) {
    console.log('updateStatus Clicked:', newStatus);

    // Intercept Interview Status to show Modal
    if (newStatus === 'Interview') {
        const modal = document.getElementById('interview-modal');
        if (modal) {
            // Pre-fill date if exists
            const dateInput = document.getElementById('interview-date');
            if (currentScheduledAt) {
                let formattedDate = currentScheduledAt.replace(' ', 'T');
                if (formattedDate.length > 16) formattedDate = formattedDate.substring(0, 16);
                dateInput.value = formattedDate;
            } else {
                dateInput.value = '';
            }

            modal.style.display = 'flex';
        } else {
            console.error('Interview modal not found in DOM');
            alert('Error: Interview modal missing.');
        }
        return;
    }


    // For other statuses, proceed as normal
    await performStatusUpdate(newStatus);
}

function closeInterviewModal() {
    document.getElementById('interview-modal').style.display = 'none';
}

async function confirmInterview() {
    const dateInput = document.getElementById('interview-date').value;
    if (!dateInput) {
        alert('Please select a date and time.');
        return;
    }

    // Close modal
    closeInterviewModal();

    // Perform Update with Date
    await performStatusUpdate('Interview', dateInput);
}

async function performStatusUpdate(newStatus, scheduledAt = null) {
    if (!currentApplicationId) {
        alert('Error: No active application found.');
        return;
    }

    // Only ask confirm if NOT interview (as modal acted as confirm)
    if (newStatus !== 'Interview') {
        if (!confirm(`Are you sure you want to change status to ${newStatus}?`)) {
            console.log('Update cancelled by user.');
            return;
        }
    }

    console.log('Proceeding with API update for:', newStatus);

    try {
        const payload = {
            application_id: currentApplicationId,
            status: newStatus
        };

        if (scheduledAt) {
            payload.scheduled_at = scheduledAt;
        }

        const response = await fetch('api/applications.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const text = await response.text();

        let data;
        try { data = JSON.parse(text); } catch (e) {
            console.error('JSON Parse Error', e);
            alert('Server Error');
            return;
        }

        if (response.ok) {
            const badge = document.getElementById('application-status-badge');
            badge.className = `badge ${getStatusBadgeClass(newStatus)}`;
            badge.textContent = newStatus;

            // Update Buttons
            updateActionButtons(newStatus);

            if (newStatus === 'Interview') {
                alert('Interview scheduled successfully!');
            }
        } else {
            alert('Failed: ' + data.error);
        }

    } catch (error) {
        console.error('Fetch error:', error);
        alert('An error occurred.');
    }
}

function updateActionButtons(status) {
    const btnReject = document.getElementById('btn-reject');
    const btnInterview = document.getElementById('btn-interview');

    if (!btnReject || !btnInterview) return;

    // Reset Defaults
    btnReject.style.display = 'inline-flex';

    // Default Interview Style
    btnInterview.className = 'btn btn-primary';
    btnInterview.innerHTML = '<i class="fa-solid fa-calendar-check"></i> Interview';
    btnInterview.style.display = 'inline-flex';

    const s = (status || '').toLowerCase();

    if (s === 'interview') {
        // If Scheduled: Hide Reject, Change Interview to Update
        btnReject.style.display = 'none';
        btnInterview.innerHTML = '<i class="fa-solid fa-pen-to-square"></i> Update Schedule';
    }
    else if (s === 'offer' || s === 'hired') {
        btnReject.style.display = 'none';
    }
    else if (s === 'rejected') {
        // Hide Reject Button
        btnReject.style.display = 'none';

        // Show Interview Button as "Re-Schedule" (using a distinct style, e.g., outline)
        btnInterview.className = 'btn btn-outline';
        btnInterview.innerHTML = '<i class="fa-solid fa-rotate-right"></i> Re-Schedule Interview';
    }
}


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

function getStatusBadgeClass(status) {
    switch (status.toLowerCase()) {
        case 'new': return 'badge-success';
        case 'screening': return 'badge-warning';
        case 'interview': return 'badge-info';
        case 'rejected': return 'badge-danger';
        case 'offer': return 'badge-success';
        default: return 'badge-info';
    }
}

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

// --- Reject Modal Logic ---
function openRejectModal() {
    console.log('Opening Reject Modal');
    const modal = document.getElementById('reject-modal');
    if (modal) {
        modal.style.display = 'flex';
    } else {
        console.error('Reject modal not found in DOM');
        if (confirm('Are you sure you want to reject this candidate?')) {
            performStatusUpdate('Rejected');
        }
    }
}

function closeRejectModal() {
    document.getElementById('reject-modal').style.display = 'none';
}

async function confirmReject() {
    console.log('confirmReject called');
    closeRejectModal();
    console.log('Calling performStatusUpdate("Rejected")');
    await performStatusUpdate('Rejected');
}

async function performStatusUpdate(newStatus, scheduledAt = null) {
    if (!currentApplicationId) {
        console.error('No currentApplicationId found!');
        alert('Error: No active application found. Please refresh.');
        return;
    }

    console.log('performStatusUpdate:', newStatus, 'App ID:', currentApplicationId);

    // ... confirm checks ...
    if (!['Interview', 'Rejected'].includes(newStatus)) {
        if (!confirm(`Are you sure you want to change status to ${newStatus}?`)) {
            return;
        }
    }

    try {
        const payload = {
            application_id: currentApplicationId,
            status: newStatus
        };

        if (scheduledAt) {
            payload.scheduled_at = scheduledAt;
        }

        console.log('Sending Payload:', payload);

        const response = await fetch('api/applications.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const text = await response.text();
        console.log('API Response:', text);

        let data;
        try { data = JSON.parse(text); } catch (e) {
            console.error('JSON Parse Error', e);
            alert('Server Error: Invalid JSON');
            return;
        }

        if (response.ok) {
            console.log('Update Success. Updating UI...');
            const badge = document.getElementById('application-status-badge');
            if (badge) {
                badge.className = `badge ${getStatusBadgeClass(newStatus)}`;
                badge.textContent = newStatus;
            } else { console.error('Badge element not found'); }

            updateActionButtons(newStatus);
            console.log('UI Updated.');

            if (newStatus === 'Interview') alert('Interview scheduled successfully!');
        } else {
            alert('Failed: ' + data.error);
        }

    } catch (error) {
        console.error('Fetch error:', error);
        alert('An error occurred.');
    }
}

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