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

<?= $this->section('content') ?>
<h5 class="mb-3">My Applications</h5>
<div id="appsList"></div>
<div id="appsEmpty" class="li-card li-card-body text-center text-muted py-5 d-none">
    <i class="bi bi-file-earmark-text display-4 d-block mb-2"></i>
    You haven't applied to any jobs yet. <a href="<?= base_url('admin/jobs') ?>">Browse jobs</a>.
</div>

<div class="modal fade" id="timelineModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" id="timelineModalTitle">Application Timeline</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="timelineModalBody">Loading...</div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const STAGE_ORDER = ['applied', 'under_review', 'shortlisted', 'interview_scheduled', 'interview_completed', 'hired'];

function statusPill(status) {
    const map = { applied: 'blue', under_review: 'yellow', shortlisted: 'blue', interview_scheduled: 'blue', interview_completed: 'blue', hired: 'green', rejected: 'red' };
    return `<span class="li-pill li-pill-${map[status] || 'gray'}">${status.replace(/_/g,' ')}</span>`;
}

async function loadApplications() {
    try {
        const res = await apiFetch('/applications/me');
        const apps = res.data.applications || [];
        const list = document.getElementById('appsList');
        const empty = document.getElementById('appsEmpty');

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

        list.innerHTML = apps.map(a => `
            <div class="li-card mb-2">
                <div class="li-card-body d-flex justify-content-between">
                    <div>
                        <span class="fw-bold">${escapeHtml(a.job_title || ('Application #' + a.id))}</span>
                        ${statusPill(a.status)}
                        <div class="text-muted small mt-1">Applied ${timeAgo(a.applied_at)}</div>
                        ${a.cover_note ? `<div class="text-muted small mt-1">${escapeHtml(a.cover_note)}</div>` : ''}
                    </div>
                    <div>
                        <button class="btn btn-li-outline btn-sm" onclick="openTimeline(${a.id}, '${escapeHtml(a.job_title || 'Application')}')"><i class="bi bi-clock-history me-1"></i>View Timeline</button>
                    </div>
                </div>
            </div>
        `).join('');
    } catch (e) { showToast(e.message, true); }
}

async function openTimeline(appId, jobTitle) {
    document.getElementById('timelineModalTitle').textContent = `Timeline — ${jobTitle}`;
    document.getElementById('timelineModalBody').innerHTML = 'Loading...';
    new bootstrap.Modal(document.getElementById('timelineModal')).show();

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

        // Simple visual progress stepper based on the furthest stage reached.
        const reached = new Set(events.filter(e => e.type === 'status_change').map(e => e.to_status));
        const stepperHtml = `
            <div class="d-flex justify-content-between mb-4" style="position:relative;">
                <div style="position:absolute; top:14px; left:0; right:0; height:2px; background:#e0dfdc; z-index:0;"></div>
                ${STAGE_ORDER.map(stage => {
                    const done = reached.has(stage) || stage === 'applied';
                    return `
                    <div class="text-center" style="position:relative; z-index:1; flex:1;">
                        <div class="rounded-circle mx-auto mb-1" style="width:28px;height:28px;background:${done ? 'var(--li-blue)' : '#e0dfdc'};color:#fff;display:flex;align-items:center;justify-content:center;font-size:12px;">
                            ${done ? '<i class="bi bi-check"></i>' : ''}
                        </div>
                        <div class="small ${done ? 'fw-semibold' : 'text-muted'}" style="font-size:11px;">${stage.replace(/_/g,' ')}</div>
                    </div>`;
                }).join('')}
            </div>
        `;

        document.getElementById('timelineModalBody').innerHTML = `
            ${stepperHtml}
            ${analytics.time_to_first_view ? `<div class="text-muted small mb-3">The recruiter first viewed your application ${analytics.time_to_first_view} after you applied.</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>
                        <div class="text-muted" style="font-size:11px;">${formatDateTime(e.timestamp)}</div>
                    </div>
                `).join('')}
            </div>
        `;
    } catch (e) {
        document.getElementById('timelineModalBody').innerHTML = `<div class="alert alert-danger">${e.message}</div>`;
    }
}

loadApplications();
</script>
<?= $this->endSection() ?>
