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

<div class="li-sidebar" style="width: 260px;">
    <div class="li-card mb-3">
        <div class="li-card-body p-3">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <h6 class="mb-0 fw-bold">Filters</h6>
                <a href="#" class="small text-decoration-none" onclick="clearFilters();return false;">Clear all</a>
            </div>

            <div class="filter-section mb-3">
                <div class="fw-semibold small mb-2">Experience Level</div>
                <?php foreach (['entry'=>'Fresh','junior'=>'Junior (1-2 Years)','mid'=>'Mid (2-5 Years)','senior'=>'Senior (5+ Years)'] as $val => $label): ?>
                    <div class="form-check">
                        <input class="form-check-input level-cb" type="checkbox" value="<?= $val === 'junior' ? 'entry' : $val ?>" id="lvl_<?= $val ?>">
                        <label class="form-check-label small" for="lvl_<?= $val ?>"><?= $label ?></label>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="filter-section mb-3">
                <div class="fw-semibold small mb-2">Salary Range (PKR)</div>
                <?php foreach (['0-30000'=>'Below 30K','30000-50000'=>'30K - 50K','50000-100000'=>'50K - 100K','100000-150000'=>'100K - 150K','150000-'=>'150K+'] as $val => $label): ?>
                    <div class="form-check">
                        <input class="form-check-input salary-cb" type="radio" name="salaryRange" value="<?= $val ?>" id="sal_<?= $val ?>">
                        <label class="form-check-label small" for="sal_<?= $val ?>"><?= $label ?></label>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="filter-section mb-3">
                <div class="fw-semibold small mb-2">Job Type</div>
                <?php foreach (['full_time'=>'Full Time','part_time'=>'Part Time','contract'=>'Contract','internship'=>'Internship','freelance'=>'Freelance'] as $val => $label): ?>
                    <div class="form-check">
                        <input class="form-check-input type-cb" type="checkbox" value="<?= $val ?>" id="jt_<?= $val ?>">
                        <label class="form-check-label small" for="jt_<?= $val ?>"><?= $label ?></label>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="filter-section mb-3">
                <div class="fw-semibold small mb-2">Work Mode</div>
                <?php foreach (['onsite'=>'On Site','remote'=>'Remote','hybrid'=>'Hybrid'] as $val => $label): ?>
                    <div class="form-check">
                        <input class="form-check-input workmode-cb" type="radio" name="workMode" value="<?= $val ?>" id="wm_<?= $val ?>">
                        <label class="form-check-label small" for="wm_<?= $val ?>"><?= $label ?></label>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="filter-section mb-3">
                <div class="fw-semibold small mb-2">Posted Date</div>
                <?php foreach (['today'=>'Last 24 Hours','this_week'=>'Last 7 Days','this_month'=>'Last 30 Days','' => 'Any Time'] as $val => $label): ?>
                    <div class="form-check">
                        <input class="form-check-input posted-rb" type="radio" name="postedDate" value="<?= $val ?>" id="pd_<?= $val ?: 'any' ?>" <?= $val === '' ? 'checked' : '' ?>>
                        <label class="form-check-label small" for="pd_<?= $val ?: 'any' ?>"><?= $label ?></label>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="filter-section mb-2">
                <div class="fw-semibold small mb-2">More</div>
                <div class="form-check"><input class="form-check-input" type="checkbox" id="freshGradFilter"><label class="form-check-label small" for="freshGradFilter">Fresh Graduate Friendly</label></div>
                <div class="form-check"><input class="form-check-input" type="checkbox" id="urgentFilter"><label class="form-check-label small" for="urgentFilter">Urgent Hiring</label></div>
                <div class="form-check"><input class="form-check-input" type="checkbox" id="easyApplyFilter"><label class="form-check-label small" for="easyApplyFilter">Easy Apply</label></div>
                <div class="form-check"><input class="form-check-input" type="checkbox" id="visaFilter"><label class="form-check-label small" for="visaFilter">Visa Sponsorship</label></div>
            </div>

            <button class="btn btn-li-primary btn-sm w-100 mt-2" onclick="searchJobs()">Apply Filters</button>
        </div>
    </div>
</div>

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

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

<div class="li-card mb-3">
    <div class="li-card-body">
        <div class="row g-2">
            <div class="col-md-4">
                <label class="form-label small text-muted mb-1">Job title or keyword</label>
                <input type="text" id="qFilter" class="form-control form-control-sm" placeholder="e.g. Web Developer">
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted mb-1">Location</label>
                <input type="text" id="locationFilter" class="form-control form-control-sm" placeholder="e.g. Lahore, Pakistan">
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted mb-1">Category</label>
                <select id="categoryFilter" class="form-select form-select-sm">
                    <option value="">Select category</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat['id'] ?>"><?= esc($cat['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button class="btn btn-li-primary btn-sm w-100" onclick="searchJobs()"><i class="bi bi-search"></i> Search Jobs</button>
            </div>
        </div>
    </div>
</div>

<div class="d-flex gap-2 mb-3 flex-wrap" id="quickPills">
    <button class="btn btn-li-outline btn-sm quick-pill" data-filter="work_mode" data-value="remote"><i class="bi bi-wifi"></i> Remote Jobs</button>
    <button class="btn btn-li-outline btn-sm quick-pill" data-filter="employment_type" data-value="full_time">Full Time</button>
    <button class="btn btn-li-outline btn-sm quick-pill" data-filter="employment_type" data-value="part_time">Part Time</button>
    <button class="btn btn-li-outline btn-sm quick-pill" data-filter="employment_type" data-value="internship">Internship</button>
    <button class="btn btn-li-outline btn-sm quick-pill" data-filter="is_urgent" data-value="1"><i class="bi bi-fire"></i> Urgent Hiring</button>
    <button class="btn btn-li-outline btn-sm quick-pill" data-filter="is_easy_apply" data-value="1"><i class="bi bi-lightning"></i> Easy Apply</button>
</div>

<div class="d-flex justify-content-between align-items-center mb-2">
    <span class="text-muted small"><strong id="jobCount">0</strong> Jobs Found</span>
</div>

<div id="jobsList"></div>
<div id="jobsEmpty" class="li-card li-card-body text-center text-muted py-5 d-none">
    <i class="bi bi-briefcase display-4 d-block mb-2"></i>No jobs match your search.
</div>

<div class="d-flex justify-content-between align-items-center mt-3" id="paginationBar" style="display:none;">
    <span class="text-muted small" id="pageInfo"></span>
    <div>
        <button class="btn btn-li-ghost btn-sm" id="prevPageBtn" onclick="changePage(-1)">← Previous</button>
        <button class="btn btn-li-ghost btn-sm" id="nextPageBtn" onclick="changePage(1)">Next →</button>
    </div>
</div>

<div class="modal fade" id="applyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">Apply for this job</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="applyJobId">
                <label class="form-label">Resume / CV</label>
                <select id="resumeSelect" class="form-select mb-2"></select>
                <div id="noResumeWarning" class="alert alert-warning py-2 small d-none">
                    You don't have a resume on file yet. Upload one below — it'll be saved to your profile and sent with this application.
                </div>
                <input type="file" id="newResumeFile" accept=".pdf,.doc,.docx" class="form-control mb-3 d-none">

                <label class="form-label">Cover Note (optional)</label>
                <textarea id="coverNote" class="form-control" rows="4" placeholder="Tell them why you're a great fit..."></textarea>
            </div>
            <div class="modal-footer">
                <button class="btn btn-li-ghost" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-li-primary" onclick="submitApplication()">Submit Application</button>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<style>
.job-card-logo {
    width: 56px; height: 56px; border-radius: 8px;
    background: var(--li-blue); color: #fff;
    display: flex; align-items: center; justify-content: center;
    font-weight: 800; font-size: 20px; flex-shrink: 0;
}
.quick-pill.active { background: var(--li-blue); color: #fff; border-color: var(--li-blue); }
.skill-tag { background: #eef3f8; color: var(--li-text-muted); font-size: 12px; padding: 2px 10px; border-radius: 10px; display: inline-block; margin: 2px 4px 2px 0; }
</style>
<script>
const BASE = "<?= rtrim(base_url(), '/') ?>";
let appliedJobIds = new Set();

async function loadAppliedJobIds() {
    try {
        const res = await apiFetch('/applications/me');
        appliedJobIds = new Set((res.data.applications || []).map(a => Number(a.job_id)));
    } catch (e) { /* non-fatal, e.g. viewer isn't a candidate */ }
}
let activePills = {};

function statusBadges(job) {
    const badges = [];
    if (appliedJobIds.has(Number(job.id))) badges.push('<span class="li-pill li-pill-green"><i class="bi bi-check-circle-fill"></i> Applied</span>');
    if (job.is_featured) badges.push('<span class="li-pill li-pill-blue"><i class="bi bi-star-fill"></i> Featured</span>');
    if (job.is_urgent) badges.push('<span class="li-pill li-pill-red"><i class="bi bi-fire"></i> Urgent Hiring</span>');
    return badges.join(' ');
}

function workModeLabel(job) {
    if (job.is_remote) return '<i class="bi bi-wifi"></i> Remote';
    if (job.is_hybrid) return '<i class="bi bi-building"></i> Hybrid';
    return '<i class="bi bi-geo-alt"></i> On Site';
}

function salaryLabel(job) {
    if (!job.is_salary_visible || (!job.salary_min && !job.salary_max)) return '';
    const min = job.salary_min ? Number(job.salary_min).toLocaleString() : '';
    const max = job.salary_max ? Number(job.salary_max).toLocaleString() : '';
    return `<span><i class="bi bi-cash"></i> PKR ${min}${min && max ? ' - ' : ''}${max}</span>`;
}

function renderJobs(jobs) {
    const list = document.getElementById('jobsList');
    const empty = document.getElementById('jobsEmpty');
    document.getElementById('jobCount').textContent = jobs.length;

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

    let skillsHtml = (job) => {
        try {
            const skills = typeof job.required_skills === 'string' ? JSON.parse(job.required_skills) : (job.required_skills || []);
            return skills.slice(0, 5).map(s => `<span class="skill-tag">${escapeHtml(s)}</span>`).join('');
        } catch (e) { return ''; }
    };

    list.innerHTML = jobs.map(job => `
        <div class="li-card mb-2 ${job.is_featured ? 'border-warning' : ''}">
            <div class="li-card-body">
                <div class="d-flex gap-3">
                    <div class="job-card-logo">${job.logo_path ? `<img src="${BASE}/${job.logo_path}" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;">` : escapeHtml((job.company_name || 'J')[0].toUpperCase())}</div>
                    <div class="flex-grow-1">
                        <div class="d-flex flex-column flex-sm-row justify-content-between">
                            <div>
                                <a href="${BASE}/jobs/${job.seo_slug}" class="fw-bold fs-6 text-decoration-none text-dark">${escapeHtml(job.title)}</a>
                                ${statusBadges(job)}
                                <div class="small mt-1">
                                    ${job.agency_username ? `<a href="${BASE}/profile/${job.agency_username}" target="_blank" class="text-decoration-none">${escapeHtml(job.company_name || '')}</a>` : escapeHtml(job.company_name || '')}
                                    ${job.verification_status === 'verified' ? '<i class="bi bi-patch-check-fill text-primary" title="Verified"></i>' : ''}
                                </div>
                                <div class="text-muted small mt-1 d-flex gap-3 flex-wrap">
                                    <span><i class="bi bi-geo-alt"></i> ${escapeHtml(job.location || job.city || 'Remote')}</span>
                                    <span>${workModeLabel(job)}</span>
                                    ${salaryLabel(job)}
                                    <span><i class="bi bi-briefcase"></i> ${job.experience_level} level</span>
                                    <span><i class="bi bi-people"></i> ${job.applicant_count || 0} applicant${job.applicant_count == 1 ? '' : 's'}</span>
                                </div>
                                <div class="mt-2">${skillsHtml(job)}</div>
                            </div>
                            <div class="text-sm-end job-card-actions-col" style="min-width:140px;">
                                <div class="text-muted small mb-2">Posted ${timeAgo(job.created_at)}</div>
                                <button class="btn btn-li-outline btn-sm w-100 mb-1" onclick="saveJob(${job.id})"><i class="bi bi-bookmark"></i> Save Job</button>
                                ${appliedJobIds.has(Number(job.id)) ? `<button class="btn btn-li-outline btn-sm w-100" disabled style="background:#e9f7ef; border-color:#057642; color:#057642;"><i class="bi bi-check-circle-fill"></i> Applied</button>` : `<button class="btn btn-li-primary btn-sm w-100" onclick="openApply(${job.id})"><i class="bi bi-lightning-fill"></i> Apply Now</button>`}
                                ${job.is_easy_apply ? '<div class="text-success small mt-1"><i class="bi bi-lightning-fill"></i> Easy Apply</div>' : ''}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

function buildFilterParams() {
    const params = new URLSearchParams();
    const q = document.getElementById('qFilter').value;
    const loc = document.getElementById('locationFilter').value;
    const category = document.getElementById('categoryFilter').value;
    if (q) params.set('q', q);
    if (loc) params.set('location', loc);
    if (category) params.set('category_id', category);

    const levels = Array.from(document.querySelectorAll('.level-cb:checked')).map(cb => cb.value);
    if (levels.length) params.set('experience_level', levels.join(','));

    const salaryRange = document.querySelector('.salary-cb:checked');
    if (salaryRange) {
        const [min, max] = salaryRange.value.split('-');
        if (min) params.set('salary_min', min);
        if (max) params.set('salary_max', max);
    }

    const types = Array.from(document.querySelectorAll('.type-cb:checked')).map(cb => cb.value);
    if (types.length) params.set('employment_type', types.join(','));

    const workMode = document.querySelector('.workmode-cb:checked');
    if (workMode) params.set('work_mode', workMode.value);

    const posted = document.querySelector('.posted-rb:checked');
    if (posted && posted.value) params.set('posted_within', posted.value);

    if (document.getElementById('freshGradFilter').checked) params.set('is_fresh_graduate_ok', '1');
    if (document.getElementById('urgentFilter').checked) params.set('is_urgent', '1');
    if (document.getElementById('easyApplyFilter').checked) params.set('is_easy_apply', '1');
    if (document.getElementById('visaFilter').checked) params.set('is_visa_sponsorship', '1');

    // Quick pills layer on top of (don't replace) the sidebar/search filters.
    Object.entries(activePills).forEach(([key, value]) => params.set(key, value));

    return params;
}

function clearFilters() {
    document.querySelectorAll('.level-cb, .type-cb').forEach(el => el.checked = false);
    document.querySelectorAll('.salary-cb, .workmode-cb').forEach(el => el.checked = false);
    document.getElementById('pd_any').checked = true;
    document.getElementById('freshGradFilter').checked = false;
    document.getElementById('urgentFilter').checked = false;
    document.getElementById('easyApplyFilter').checked = false;
    document.getElementById('visaFilter').checked = false;
    document.getElementById('qFilter').value = '';
    document.getElementById('locationFilter').value = '';
    document.getElementById('categoryFilter').value = '';
    activePills = {};
    document.querySelectorAll('.quick-pill').forEach(p => p.classList.remove('active'));
    searchJobs();
}

let currentPage = 1;
const JOBS_PER_PAGE = 20;

async function searchJobs(page) {
    currentPage = page || 1;
    const params = buildFilterParams();
    params.set('page', currentPage);
    params.set('per_page', JOBS_PER_PAGE);
    try {
        const res = await apiFetch(`/jobs?${params.toString()}`);
        const jobs = res.data || [];
        renderJobs(jobs);

        const bar = document.getElementById('paginationBar');
        if (currentPage === 1 && jobs.length < JOBS_PER_PAGE) {
            bar.style.display = 'none'; // everything fit on one page, no need for controls
        } else {
            bar.style.display = 'flex';
            document.getElementById('pageInfo').textContent = `Page ${currentPage}`;
            document.getElementById('prevPageBtn').disabled = currentPage <= 1;
            document.getElementById('nextPageBtn').disabled = jobs.length < JOBS_PER_PAGE; // fewer than a full page means no next page
        }
    } catch (e) { showToast(e.message, true); }
}

function changePage(delta) {
    searchJobs(currentPage + delta);
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

document.querySelectorAll('.quick-pill').forEach(pill => {
    pill.addEventListener('click', () => {
        const key = pill.dataset.filter;
        const value = pill.dataset.value;
        if (activePills[key] === value) {
            delete activePills[key];
            pill.classList.remove('active');
        } else {
            activePills[key] = value;
            pill.classList.add('active');
        }
        searchJobs();
    });
});

let myResumes = [];

async function openApply(jobId) {
    document.getElementById('applyJobId').value = jobId;
    document.getElementById('coverNote').value = '';
    document.getElementById('newResumeFile').value = '';

    try {
        const res = await apiFetch('/candidates/me');
        myResumes = res.data.resumes || [];
    } catch (e) { myResumes = []; }

    const select = document.getElementById('resumeSelect');
    const warning = document.getElementById('noResumeWarning');
    const fileInput = document.getElementById('newResumeFile');

    if (myResumes.length > 0) {
        select.classList.remove('d-none');
        warning.classList.add('d-none');
        fileInput.classList.add('d-none');
        select.innerHTML = myResumes.map(r => `<option value="${r.id}" ${r.is_primary == 1 ? 'selected' : ''}>${escapeHtml(r.original_filename || 'Resume')}${r.is_primary == 1 ? ' (Primary)' : ''}</option>`).join('');
        select.innerHTML += `<option value="__upload_new__">+ Upload a different resume</option>`;
        select.onchange = () => {
            fileInput.classList.toggle('d-none', select.value !== '__upload_new__');
        };
    } else {
        select.classList.add('d-none');
        warning.classList.remove('d-none');
        fileInput.classList.remove('d-none');
    }

    new bootstrap.Modal(document.getElementById('applyModal')).show();
}

async function submitApplication() {
    const jobId = document.getElementById('applyJobId').value;
    const coverNote = document.getElementById('coverNote').value;
    const select = document.getElementById('resumeSelect');
    const fileInput = document.getElementById('newResumeFile');
    const needsUpload = myResumes.length === 0 || select.value === '__upload_new__';

    try {
        let resumeId = needsUpload ? null : select.value;

        if (needsUpload) {
            if (!fileInput.files.length) {
                showToast('Please select a resume file to upload.', true);
                return;
            }
            const fd = new FormData();
            fd.append('resume', fileInput.files[0]);
            const uploadRes = await fetch(`${API_BASE}/candidates/me/resume`, { method: 'POST', body: fd, credentials: 'include' });
            const uploadJson = await uploadRes.json();
            if (!uploadJson.success) throw new Error(uploadJson.errors?.[0]?.message || 'Resume upload failed.');
            resumeId = uploadJson.data.id;
        }

        await apiFetch(`/jobs/${jobId}/apply`, { method: 'POST', body: JSON.stringify({ cover_note: coverNote || null, resume_id: resumeId ? parseInt(resumeId) : null }) });
        showToast('Application submitted!');
        bootstrap.Modal.getInstance(document.getElementById('applyModal')).hide();
        appliedJobIds.add(parseInt(jobId));
        searchJobs();
    } catch (e) {
        showToast(e.message, true);
    }
}

async function saveJob(jobId) {
    showToast('Job saved to your list.');
}

loadAppliedJobIds().then(searchJobs);
</script>
<?= $this->endSection() ?>
