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

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

<div class="li-card" style="height: 70vh;">
    <div class="d-flex h-100" id="messagesLayout">
        <div class="border-end" id="convoListPanel" style="width: 320px; overflow-y:auto;">
            <div class="li-card-header">Conversations</div>
            <div id="convoList"></div>
            <div id="convoEmpty" class="text-muted small text-center py-4 d-none px-3">
                No conversations yet. Messages started from candidate search or the ATS pipeline will appear here.
            </div>
        </div>
        <div class="flex-grow-1 d-none d-md-flex flex-column" id="threadPanel">
            <div id="threadHeader" class="li-card-header d-none d-flex align-items-center gap-2">
                <button class="btn btn-li-ghost btn-sm d-md-none" id="backToListBtn" onclick="showConvoList()"><i class="bi bi-arrow-left"></i></button>
                <span id="threadHeaderText"></span>
            </div>
            <div id="threadMessages" class="flex-grow-1 overflow-y-auto p-3"></div>
            <div id="threadComposer" class="border-top p-2 d-none">
                <div class="d-flex gap-2">
                    <input type="text" id="messageInput" class="form-control form-control-sm" placeholder="Type a message...">
                    <button class="btn btn-li-primary btn-sm" onclick="sendMessage()">Send</button>
                </div>
            </div>
            <div id="threadPlaceholder" class="flex-grow-1 d-flex align-items-center justify-content-center text-muted">
                Select a conversation to view messages.
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const BASE = "<?= rtrim(base_url(), '/') ?>";
let activeConversationId = null;

// On mobile, the conversation list and the open thread take turns
// occupying the full width — a 320px fixed list panel simply doesn't fit
// next to a thread on a phone screen. Desktop (≥768px) always shows both.
function showConvoThread() {
    document.getElementById('convoListPanel').classList.add('d-none', 'd-md-block');
    document.getElementById('threadPanel').classList.remove('d-none');
    document.getElementById('threadPanel').classList.add('d-flex');
}
function showConvoList() {
    document.getElementById('convoListPanel').classList.remove('d-none');
    document.getElementById('threadPanel').classList.add('d-none', 'd-md-flex');
}
let conversations = [];

async function loadConversations() {
    try {
        const res = await apiFetch('/conversations');
        conversations = res.data.conversations || [];
        const list = document.getElementById('convoList');
        const empty = document.getElementById('convoEmpty');

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

        list.innerHTML = conversations.map(c => {
            const other = c.other_participant;
            const name = other ? other.display_name : `Conversation #${c.id}`;
            const photo = other && other.photo_path ? `<img src="${BASE}/${other.photo_path}" class="rounded-circle" style="width:36px;height:36px;object-fit:cover;">` : `<span class="avatar-circle" style="width:36px;height:36px;font-size:14px;">${escapeHtml((name || 'U')[0].toUpperCase())}</span>`;
            return `
            <a href="#" class="d-block text-decoration-none text-dark p-3 border-bottom" onclick="openConversation(${c.id});return false;">
                <div class="d-flex gap-2 align-items-center">
                    ${photo}
                    <div class="flex-grow-1" style="min-width:0;">
                        <div class="fw-semibold small">${escapeHtml(name)}</div>
                        <div class="text-muted small text-truncate">${escapeHtml(c.last_message || 'No messages yet')}</div>
                    </div>
                </div>
            </a>
        `;
        }).join('');
    } catch (e) { showToast(e.message, true); }
}

async function openConversation(id) {
    activeConversationId = id;
    document.getElementById('threadPlaceholder').classList.add('d-none');
    document.getElementById('threadHeader').classList.remove('d-none');
    document.getElementById('threadHeaderText').textContent = `Conversation #${id}`;
    const convoData = conversations.find(c => c.id === id);
    if (convoData && convoData.other_participant) {
        document.getElementById('threadHeaderText').textContent = convoData.other_participant.display_name;
    }
    document.getElementById('threadComposer').classList.remove('d-none');
    showConvoThread(); // on mobile, switch from the list view to the thread view

    try {
        const res = await apiFetch(`/conversations/${id}/messages`);
        const messages = (res.data.messages || []).slice().reverse();
        document.getElementById('threadMessages').innerHTML = messages.map(m => `
            <div class="mb-2">
                <div class="small text-muted">${timeAgo(m.created_at)}</div>
                <div class="p-2 rounded" style="background:#f4f2ee; display:inline-block; max-width:80%;">${escapeHtml(m.body)}</div>
            </div>
        `).join('') || '<p class="text-muted small">No messages yet. Say hello!</p>';

        await apiFetch(`/conversations/${id}/read`, { method: 'POST' });
    } catch (e) { showToast(e.message, true); }
}

async function sendMessage() {
    const input = document.getElementById('messageInput');
    if (!input.value.trim() || !activeConversationId) return;
    try {
        await apiFetch(`/conversations/${activeConversationId}/messages`, { method: 'POST', body: JSON.stringify({ body: input.value }) });
        input.value = '';
        openConversation(activeConversationId);
        loadConversations();
    } catch (e) { showToast(e.message, true); }
}

document.getElementById('messageInput')?.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') sendMessage();
});

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