<?= $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">Candidate Search</h5>
    <span class="li-pill li-pill-blue"><i class="bi bi-coin"></i> <span id="pageCreditBalance">—</span> credits remaining</span>
</div>

<div class="li-card mb-3">
    <div class="li-card-body">
        <div class="row g-2">
            <div class="col-md-5">
                <input type="text" id="qFilter" class="form-control form-control-sm" placeholder="Keyword (headline, about, name)">
            </div>
            <div class="col-md-4">
                <input type="text" id="skillsFilter" class="form-control form-control-sm" placeholder="Skills, comma-separated (e.g. PHP, React)">
            </div>
            <div class="col-md-3">
                <button class="btn btn-li-primary btn-sm w-100" onclick="searchCandidates()"><i class="bi bi-search"></i> Search</button>
            </div>
        </div>
        <a href="#" class="small text-decoration-none" data-bs-toggle="collapse" data-bs-target="#moreFilters" onclick="return true;">
            <i class="bi bi-sliders"></i> More filters
        </a>

        <div class="collapse mt-3" id="moreFilters">
            <hr>
            <div class="row g-2">
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Availability</label>
                    <select id="availabilityFilter" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <option value="open_to_work">Open to work</option>
                        <option value="actively_looking">Actively looking</option>
                        <option value="available_immediately">Available immediately</option>
                        <option value="not_looking">Not looking</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Work Preference</label>
                    <select id="workPrefFilter" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <option value="remote">Remote</option>
                        <option value="hybrid">Hybrid</option>
                        <option value="onsite">Onsite</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Employment Type</label>
                    <select id="empTypeFilter" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <option value="full_time">Full Time</option>
                        <option value="part_time">Part Time</option>
                        <option value="contract">Contract</option>
                        <option value="internship">Internship</option>
                        <option value="freelance">Freelance</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Career Level</label>
                    <select id="careerLevelFilter" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <option value="entry">Entry</option>
                        <option value="mid">Mid</option>
                        <option value="senior">Senior</option>
                        <option value="lead">Lead</option>
                        <option value="executive">Executive</option>
                    </select>
                </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">
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Industry</label>
                    <input type="text" id="industryFilter" class="form-control form-control-sm">
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Max Salary Budget (PKR)</label>
                    <input type="number" id="salaryMaxFilter" class="form-control form-control-sm">
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-1">Min Profile Completion (%)</label>
                    <input type="number" id="minProfilePctFilter" class="form-control form-control-sm" min="0" max="100">
                </div>

                <div class="col-md-4">
                    <label class="form-label small text-muted mb-1">Active Within (days)</label>
                    <select id="lastActiveFilter" class="form-select form-select-sm">
                        <option value="">Any time</option>
                        <option value="1">Last 24 hours</option>
                        <option value="7">Last 7 days</option>
                        <option value="30">Last 30 days</option>
                    </select>
                </div>
                <div class="col-md-8 d-flex align-items-end">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="verifiedFilter">
                        <label class="form-check-label small" for="verifiedFilter">Verified profiles only</label>
                    </div>
                </div>

                <div class="col-12">
                    <button class="btn btn-li-primary btn-sm" onclick="searchCandidates()">Apply Filters</button>
                    <button class="btn btn-li-ghost btn-sm" onclick="clearFilters()">Clear All</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="candidatesList"></div>
<div id="candidatesEmpty" class="li-card li-card-body text-center text-muted py-5 d-none">
    <i class="bi bi-people display-4 d-block mb-2"></i>No candidates match your filters.
</div>

<div class="modal fade" id="messageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">Message <span id="msgRecipientName"></span></h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="msgRecipientId">
                <textarea id="msgBody" class="form-control" rows="4" placeholder="Type your message..."></textarea>
                <p class="text-muted small mt-2 mb-0">Starting a new conversation uses 1 credit (per your platform's settings). Replying is free.</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-li-ghost" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-li-primary" onclick="sendMessage()">Send</button>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const BASE = "<?= rtrim(base_url(), '/') ?>";
function availabilityPill(status) {
    const map = { open_to_work: 'green', actively_looking: 'blue', available_immediately: 'green', not_looking: 'gray' };
    const label = (status || '').replace(/_/g, ' ');
    return `<span class="li-pill li-pill-${map[status] || 'gray'}">${label}</span>`;
}

function renderCandidates(candidates) {
    const list = document.getElementById('candidatesList');
    const empty = document.getElementById('candidatesEmpty');

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

    list.innerHTML = candidates.map(c => `
        <div class="li-card mb-2">
            <div class="li-card-body d-flex gap-3">
                ${c.profile_photo_path ? `<img src="${BASE}/${c.profile_photo_path}" class="rounded-circle" style="width:48px;height:48px;object-fit:cover;">` : `<span class="avatar-circle md">${escapeHtml((c.name || 'C')[0].toUpperCase())}</span>`}
                <div class="flex-grow-1">
                    <div class="d-flex justify-content-between">
                        <div>
                            <span class="fw-bold">${escapeHtml(c.name || 'Candidate')}</span>
                            ${availabilityPill(c.availability_status)}
                            ${c.is_verified ? '<i class="bi bi-patch-check-fill text-primary" title="Verified"></i>' : ''}
                            ${c.is_unlocked ? '<span class="li-pill li-pill-blue">Unlocked</span>' : ''}
                        </div>
                        <div class="text-muted small">${c.profile_completion_pct || 0}% complete profile</div>
                    </div>
                    <div class="text-muted small mt-1">${escapeHtml(c.headline || 'No headline set')}</div>
                    <div class="text-muted small mt-1 d-flex gap-3 flex-wrap">
                        ${c.work_preference ? `<span><i class="bi bi-geo-alt"></i> ${c.work_preference}</span>` : ''}
                        ${c.career_level ? `<span><i class="bi bi-briefcase"></i> ${c.career_level}</span>` : ''}
                    </div>
                    <div class="mt-2 d-flex gap-2 align-items-center">
                        ${!c.is_unlocked ? `<button class="btn btn-li-outline btn-sm" onclick="unlockCandidate(${c.id}, 'contact_reveal')"><i class="bi bi-unlock me-1"></i>Reveal Contact</button>` : `
                            <button class="btn btn-li-outline btn-sm" title="Copy phone number" onclick="copyContact('${escapeHtml(c.phone || '')}', 'Phone number')"><i class="bi bi-telephone-fill"></i></button>
                            <button class="btn btn-li-outline btn-sm" title="Copy email address" onclick="copyContact('${escapeHtml(c.email || '')}', 'Email address')"><i class="bi bi-envelope-fill"></i></button>
                        `}
                        <button class="btn btn-li-outline btn-sm" onclick="openMessage(${c.user_id}, '${escapeHtml(c.name || 'Candidate')}')"><i class="bi bi-chat-dots me-1"></i>Message</button>
                        <button class="btn btn-li-ghost btn-sm" onclick="saveCandidate(${c.id})"><i class="bi bi-bookmark me-1"></i>Save</button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

function buildFilterParams() {
    const params = new URLSearchParams();
    const q = document.getElementById('qFilter').value;
    const skills = document.getElementById('skillsFilter').value;
    if (q) params.set('q', q);
    if (skills) params.set('skills', skills);

    const availability = document.getElementById('availabilityFilter').value;
    if (availability) params.set('availability_status', availability);
    const workPref = document.getElementById('workPrefFilter').value;
    if (workPref) params.set('work_preference', workPref);
    const empType = document.getElementById('empTypeFilter').value;
    if (empType) params.set('employment_type', empType);
    const careerLevel = document.getElementById('careerLevelFilter').value;
    if (careerLevel) params.set('career_level', careerLevel);

    const location = document.getElementById('locationFilter').value;
    if (location) params.set('location', location);
    const industry = document.getElementById('industryFilter').value;
    if (industry) params.set('industry', industry);
    const salaryMax = document.getElementById('salaryMaxFilter').value;
    if (salaryMax) params.set('salary_max', salaryMax);
    const minPct = document.getElementById('minProfilePctFilter').value;
    if (minPct) params.set('min_profile_pct', minPct);
    const lastActive = document.getElementById('lastActiveFilter').value;
    if (lastActive) params.set('last_active_days', lastActive);
    if (document.getElementById('verifiedFilter').checked) params.set('is_verified', '1');

    return params;
}

function clearFilters() {
    document.getElementById('qFilter').value = '';
    document.getElementById('skillsFilter').value = '';
    document.getElementById('locationFilter').value = '';
    document.getElementById('industryFilter').value = '';
    document.getElementById('salaryMaxFilter').value = '';
    document.getElementById('minProfilePctFilter').value = '';
    document.querySelectorAll('#moreFilters select').forEach(el => el.value = '');
    document.getElementById('verifiedFilter').checked = false;
    searchCandidates();
}

async function searchCandidates() {
    const params = buildFilterParams();
    try {
        const res = await apiFetch(`/candidates/search?${params.toString()}`);
        renderCandidates(res.data || []);
    } catch (e) {
        showToast(e.message, true);
    }
}

async function loadCreditBalance() {
    try {
        const res = await apiFetch('/billing/credits');
        document.getElementById('pageCreditBalance').textContent = res.data.balance;
        const topbarEl = document.getElementById('creditCountValue');
        if (topbarEl) topbarEl.textContent = res.data.balance;
    } catch (e) { /* non-fatal */ }
}

async function copyContact(value, label) {
    if (!value) { showToast(`No ${label.toLowerCase()} on file.`, true); return; }
    try {
        await navigator.clipboard.writeText(value);
        showToast(`${label} copied to clipboard.`);
    } catch (e) {
        showToast(`Could not copy — ${value}`, true);
    }
}

function openMessage(userId, name) {
    document.getElementById('msgRecipientId').value = userId;
    document.getElementById('msgRecipientName').textContent = name;
    document.getElementById('msgBody').value = '';
    new bootstrap.Modal(document.getElementById('messageModal')).show();
}

async function sendMessage() {
    const recipientId = document.getElementById('msgRecipientId').value;
    const body = document.getElementById('msgBody').value.trim();
    if (!body) { showToast('Write a message first.', true); return; }

    try {
        const convo = await apiFetch('/conversations', {
            method: 'POST',
            body: JSON.stringify({ recipient_user_id: parseInt(recipientId) }),
        });
        await apiFetch(`/conversations/${convo.data.conversation.id}/messages`, {
            method: 'POST',
            body: JSON.stringify({ body }),
        });
        showToast('Message sent!');
        bootstrap.Modal.getInstance(document.getElementById('messageModal')).hide();
        loadCreditBalance();
    } catch (e) {
        showToast(e.message, true);
    }
}

async function unlockCandidate(id, type) {
    try {
        const res = await apiFetch(`/candidates/${id}/unlock`, { method: 'POST', body: JSON.stringify({ type }) });
        showToast(res.data.already_unlocked ? 'Already unlocked.' : `Unlocked (${res.data.credits_spent || 0} credit${res.data.credits_spent === 1 ? '' : 's'} used).`);
        searchCandidates();
        loadCreditBalance();
    } catch (e) {
        if (e.message.toLowerCase().includes('insufficient credits')) {
            showToast(`${e.message} Buy more credits from Billing.`, true);
        } else {
            showToast(e.message, true);
        }
    }
}

async function saveCandidate(id) {
    try {
        await apiFetch(`/candidates/${id}/save`, { method: 'POST' });
        showToast('Candidate saved to your talent pool.');
    } catch (e) {
        showToast(e.message, true);
    }
}

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