<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">ATS Pipeline</h5>
    <div class="d-flex gap-2">
        <select id="jobFilter" class="form-select form-select-sm" style="width:220px;">
            <option value="">All jobs</option>
        </select>
        <select id="stageFilter" class="form-select form-select-sm" style="width:200px;">
            <option value="">All stages</option>
            <option value="applied">Applied</option>
            <option value="under_review">Under Review</option>
            <option value="shortlisted">Shortlisted</option>
            <option value="interview_scheduled">Interview Scheduled</option>
            <option value="interview_completed">Interview Completed</option>
            <option value="hired">Hired</option>
            <option value="rejected">Rejected</option>
        </select>
    </div>
</div>

<div class="li-card">
    <div class="table-responsive">
        <table class="table li-table mb-0">
            <thead>
                <tr>
                    <th>Candidate</th>
                    <th>Job</th>
                    <th>Applied</th>
                    <th>Status</th>
                    <th></th>
                </tr>
            </thead>
            <tbody id="applicationsTable"></tbody>
        </table>
    </div>
    <div id="applicationsEmpty" class="text-center text-muted py-5 d-none">No applications match your filters.</div>
</div>

<div class="modal fade" id="candidateModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" id="candidateModalTitle">Candidate</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="candidateModalBody">Loading...</div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<style>
.status-select { min-width: 190px; }
</style>
<script>
const STAGES = [
    { key: 'applied', label: 'Applied' },
    { key: 'under_review', label: 'Under Review' },
    { key: 'shortlisted', label: 'Shortlisted' },
    { key: 'interview_scheduled', label: 'Interview Scheduled' },
    { key: 'interview_completed', label: 'Interview Completed' },
    { key: 'hired', label: 'Hired' },
    { key: 'rejected', label: 'Rejected' },
];

let allApplications = [];

function stageOptions(selected) {
    return STAGES.map(s => `<option value="${s.key}" ${s.key === selected ? 'selected' : ''}>${s.label}</option>`).join('');
}

function renderTable() {
    const stageFilterVal = document.getElementById('stageFilter').value;
    const rows = stageFilterVal ? allApplications.filter(a => a.status === stageFilterVal) : allApplications;

    const tbody = document.getElementById('applicationsTable');
    const empty = document.getElementById('applicationsEmpty');

    if (rows.length === 0) { tbody.innerHTML = ''; empty.classList.remove('d-none'); return; }
    empty.classList.add('d-none');

    tbody.innerHTML = rows.map(c => `
        <tr>
            <td>
                <a href="#" onclick="openCandidate(${c.id});return false;" class="text-decoration-none fw-semibold text-dark">${escapeHtml(c.candidate_name || 'Candidate')}</a>
            </td>
            <td class="text-muted small">${escapeHtml(c.job_title || '')}</td>
            <td class="text-muted small">${timeAgo(c.applied_at)}</td>
            <td>
                <select class="form-select form-select-sm status-select" onchange="changeStatus(${c.id}, this.value, this)">
                    ${stageOptions(c.status)}
                </select>
            </td>
            <td><button class="btn btn-li-ghost btn-sm" onclick="openCandidate(${c.id});return false;"><i class="bi bi-eye"></i> View</button></td>
        </tr>
    `).join('');
}

async function changeStatus(appId, newStage, selectEl) {
    const original = selectEl.dataset.original || selectEl.value;
    try {
        await apiFetch(`/applications/${appId}/status`, {
            method: 'PUT',
            body: JSON.stringify({ status: newStage }),
        });
        showToast('Status updated — added to applicant\'s timeline.');
        // Update local state so the stage filter stays consistent without a full reload.
        const app = allApplications.find(a => a.id === appId);
        if (app) app.status = newStage;
    } catch (e) {
        showToast(e.message, true);
        selectEl.value = original; // revert the dropdown on failure
    }
}

async function loadPipeline() {
    try {
        const jobId = document.getElementById('jobFilter').value;
        const res = await apiFetch(`/applications/kanban${jobId ? '?job_id=' + jobId : ''}`);
        const pipeline = res.data.pipeline || {};

        // Flatten the grouped-by-stage response into one list, stamping
        // each card with its stage as `status` — a list view needs a flat
        // array, not columns.
        allApplications = [];
        Object.entries(pipeline).forEach(([stage, cards]) => {
            cards.forEach(c => allApplications.push({ ...c, status: stage }));
        });
        allApplications.sort((a, b) => new Date(b.applied_at) - new Date(a.applied_at));

        renderTable();
    } catch (e) {
        showToast(e.message, true);
    }
}

async function loadJobsForFilter() {
    try {
        const res = await apiFetch('/jobs/mine');
        const select = document.getElementById('jobFilter');
        (res.data || []).forEach(job => {
            const opt = document.createElement('option');
            opt.value = job.id;
            opt.textContent = job.title;
            select.appendChild(opt);
        });
    } catch (e) { /* non-fatal */ }
}

async function openCandidate(appId) {
    const modalEl = document.getElementById('candidateModal');
    const modal = new bootstrap.Modal(modalEl);
    document.getElementById('candidateModalBody').innerHTML = 'Loading...';
    modal.show();

    try {
        const res = await apiFetch(`/applications/${appId}`);
        const app = res.data.application;

        const timelineRes = await apiFetch(`/applications/${appId}/timeline`);
        const events = timelineRes.data.events || [];
        const analytics = timelineRes.data.analytics || {};

        document.getElementById('candidateModalTitle').textContent = `Application #${app.id}`;
        document.getElementById('candidateModalBody').innerHTML = `
            <p><strong>Status:</strong> <span class="li-pill li-pill-blue">${app.status}</span></p>
            ${app.cover_note ? `<p><strong>Cover Note:</strong><br>${escapeHtml(app.cover_note)}</p>` : ''}
            <p>
                <strong>Resume:</strong>
                ${app.resume_id ? `<a href="${API_BASE}/resumes/${app.resume_id}/download" target="_blank" class="btn btn-li-outline btn-sm ms-2"><i class="bi bi-file-earmark-arrow-down me-1"></i>View / Download CV</a>` : '<span class="text-muted">No resume attached</span>'}
            </p>

            ${(analytics.time_to_first_view || analytics.total_time) ? `
                <div class="li-card li-card-body mb-3" style="background:#f4f2ee;">
                    <h6 class="mb-2">Hiring Speed</h6>
                    ${analytics.time_to_first_view ? `<div class="small">Time to First View: <strong>${analytics.time_to_first_view}</strong></div>` : ''}
                    ${(analytics.stage_durations || []).map(s => `<div class="small text-muted">${s.from} → ${s.to}: ${s.duration}</div>`).join('')}
                    ${analytics.total_time ? `<div class="small mt-1">Total Time (${analytics.outcome}): <strong>${analytics.total_time}</strong></div>` : ''}
                </div>
            ` : ''}

            <hr>
            <h6>Add Note</h6>
            <div class="d-flex gap-2 mb-3">
                <input type="text" id="noteInput" class="form-control form-control-sm" placeholder="Internal note...">
                <button class="btn btn-li-primary btn-sm" onclick="addNote(${app.id})">Add</button>
            </div>

            <h6>Timeline</h6>
            <div style="max-height:300px; overflow-y:auto;">
                ${events.map(e => `
                    <div class="border-bottom py-2">
                        <div class="small fw-semibold">${escapeHtml(e.label)}</div>
                        ${e.note ? `<div class="small text-muted">${escapeHtml(e.note)}</div>` : ''}
                        <div class="text-muted" style="font-size:11px;">
                            ${e.actor ? escapeHtml(e.actor) + (e.actor_role ? ' (' + e.actor_role.replace(/_/g,' ') + ')' : '') + ' · ' : ''}
                            ${formatDateTime(e.timestamp)}
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    } catch (e) {
        document.getElementById('candidateModalBody').innerHTML = `<div class="alert alert-danger">${e.message}</div>`;
    }
}

async function addNote(appId) {
    const input = document.getElementById('noteInput');
    if (!input.value.trim()) return;
    try {
        await apiFetch(`/applications/${appId}/notes`, { method: 'POST', body: JSON.stringify({ note: input.value }) });
        openCandidate(appId);
    } catch (e) { showToast(e.message, true); }
}

document.getElementById('jobFilter').addEventListener('change', loadPipeline);
document.getElementById('stageFilter').addEventListener('change', renderTable);
loadJobsForFilter();
loadPipeline();
</script>
<?= $this->endSection() ?>
