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

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

<ul class="nav nav-tabs mb-3">
    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tabConnections">Connections (<span id="connCount">0</span>)</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabReceived">Requests (<span id="receivedCount">0</span>)</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabSent">Sent</a></li>
</ul>

<div class="tab-content">
    <div class="tab-pane fade show active" id="tabConnections">
        <div id="connectionsList"></div>
        <div id="connectionsEmpty" 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 connections yet. Visit a profile and click Connect.
        </div>
    </div>
    <div class="tab-pane fade" id="tabReceived">
        <div id="receivedList"></div>
        <div id="receivedEmpty" class="li-card li-card-body text-center text-muted py-5 d-none">
            <i class="bi bi-person-plus display-4 d-block mb-2"></i>No pending requests.
        </div>
    </div>
    <div class="tab-pane fade" id="tabSent">
        <div id="sentList"></div>
        <div id="sentEmpty" class="li-card li-card-body text-center text-muted py-5 d-none">
            <i class="bi bi-send display-4 d-block mb-2"></i>No sent requests awaiting response.
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
function personRow(item, actions) {
    const u = item.user;
    if (!u) return '';
    const displayName = u.company_name || u.name;
    const subLabel = u.company_name ? u.name : (u.role_slug || '').replace(/_/g,' ');
    return `
        <div class="li-card mb-2">
            <div class="li-card-body d-flex justify-content-between align-items-center">
                <a href="${BASE}/profile/${u.username || ''}" target="_blank" class="d-flex gap-3 align-items-center text-decoration-none text-dark">
                    <span class="avatar-circle md">${escapeHtml((displayName || 'U')[0].toUpperCase())}</span>
                    <div>
                        <div class="fw-bold">${escapeHtml(displayName)} ${u.verification_status === 'verified' ? '<i class="bi bi-patch-check-fill text-primary"></i>' : ''}</div>
                        <div class="text-muted small">${escapeHtml(subLabel)}</div>
                    </div>
                </a>
                <div class="d-flex gap-2">${actions}</div>
            </div>
        </div>
    `;
}

async function loadConnections() {
    try {
        const res = await apiFetch('/connections');
        const list = res.data.connections || [];
        document.getElementById('connCount').textContent = list.length;
        const el = document.getElementById('connectionsList');
        const empty = document.getElementById('connectionsEmpty');
        if (list.length === 0) { el.innerHTML = ''; empty.classList.remove('d-none'); return; }
        empty.classList.add('d-none');
        el.innerHTML = list.map(c => personRow(c, `<button class="btn btn-li-ghost btn-sm text-danger" onclick="removeConnection(${c.id})">Remove</button>`)).join('');
    } catch (e) { showToast(e.message, true); }
}

async function loadReceived() {
    try {
        const res = await apiFetch('/connections/pending/received');
        const list = res.data.requests || [];
        document.getElementById('receivedCount').textContent = list.length;
        const el = document.getElementById('receivedList');
        const empty = document.getElementById('receivedEmpty');
        if (list.length === 0) { el.innerHTML = ''; empty.classList.remove('d-none'); return; }
        empty.classList.add('d-none');
        el.innerHTML = list.map(r => personRow(r, `
            <button class="btn btn-li-primary btn-sm" onclick="acceptRequest(${r.id})">Accept</button>
            <button class="btn btn-li-ghost btn-sm" onclick="rejectRequest(${r.id})">Ignore</button>
        `)).join('');
    } catch (e) { showToast(e.message, true); }
}

async function loadSent() {
    try {
        const res = await apiFetch('/connections/pending/sent');
        const list = res.data.requests || [];
        const el = document.getElementById('sentList');
        const empty = document.getElementById('sentEmpty');
        if (list.length === 0) { el.innerHTML = ''; empty.classList.remove('d-none'); return; }
        empty.classList.add('d-none');
        el.innerHTML = list.map(r => personRow(r, `<span class="li-pill li-pill-yellow">Pending</span>`)).join('');
    } catch (e) { showToast(e.message, true); }
}

async function acceptRequest(id) {
    try { await apiFetch(`/connections/${id}/accept`, { method: 'POST' }); showToast('Connection accepted!'); loadReceived(); loadConnections(); }
    catch (e) { showToast(e.message, true); }
}
async function rejectRequest(id) {
    try { await apiFetch(`/connections/${id}/reject`, { method: 'POST' }); showToast('Request declined.'); loadReceived(); }
    catch (e) { showToast(e.message, true); }
}
async function removeConnection(id) {
    if (!confirm('Remove this connection?')) return;
    try { await apiFetch(`/connections/${id}`, { method: 'DELETE' }); showToast('Connection removed.'); loadConnections(); }
    catch (e) { showToast(e.message, true); }
}

const BASE = "<?= rtrim(base_url(), '/') ?>";
loadConnections();
loadReceived();
loadSent();
</script>
<?= $this->endSection() ?>
