<?php
 
 
 
 

$selectedId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$filterUnread = ($_GET['filter'] ?? '') === 'unread';

 
$relTime = function (string $dt): string {
    $diff = time() - strtotime($dt);
    if ($diff < 60)     return $diff . 's';
    if ($diff < 3600)   return floor($diff / 60) . 'm';
    if ($diff < 86400)  return floor($diff / 3600) . 'h';
    if ($diff < 604800) return floor($diff / 86400) . 'd';
    return date('M j', strtotime($dt));
};
?>


<div class="inbox-toolbar mb-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
    <div class="flex items-center gap-3 flex-1 min-w-0">
        <input type="text" id="msg-search" placeholder="Search messages..."
               class="w-full sm:w-72 px-3 py-2 sm:py-1.5 border border-gray-300 rounded-lg text-sm sm:text-xs focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
        <span id="msg-count" class="text-xs text-gray-500 whitespace-nowrap hidden sm:inline">
            <?= number_format($totalMessages) ?> message<?= $totalMessages !== 1 ? 's' : '' ?>
        </span>
    </div>
    <div class="inbox-pills flex items-center gap-2">
        <a href="/admin/inbox?tab=messages"
           class="px-2.5 py-1 text-xs font-medium rounded border <?= !$filterUnread ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50' ?>">All</a>
        <a href="/admin/inbox?tab=messages&filter=unread"
           class="px-2.5 py-1 text-xs font-medium rounded border <?= $filterUnread ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50' ?>">
            Unread
            <?php if ($unreadMessages > 0): ?>
            <span class="ml-1 inline-flex items-center justify-center min-w-[16px] h-4 px-1 text-[10px] font-bold rounded-full <?= $filterUnread ? 'bg-white/25 text-white' : 'bg-primary-600 text-white' ?>"><?= $unreadMessages ?></span>
            <?php endif; ?>
        </a>
    </div>
</div>


<div id="msg-bulk" class="inbox-bulk hidden mb-3 px-3 py-2 bg-primary-50 border border-primary-200 rounded-lg text-xs">
    <div class="flex items-center gap-2 flex-wrap">
        <span class="font-medium text-primary-700"><span id="msg-bulk-count">0</span> selected</span>
        <button type="button" onclick="msgBulkRead(1)" class="inline-flex items-center gap-1 px-3 py-1.5 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded hover:bg-gray-50">
            <i class="fa-regular fa-envelope-open text-[11px]"></i> <span class="hidden xs:inline">Mark </span>read
        </button>
        <button type="button" onclick="msgBulkRead(0)" class="inline-flex items-center gap-1 px-3 py-1.5 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded hover:bg-gray-50">
            <i class="fa-regular fa-envelope text-[11px]"></i> <span class="hidden xs:inline">Mark </span>unread
        </button>
        <button type="button" onclick="msgBulkDelete()" class="inline-flex items-center gap-1 px-3 py-1.5 bg-red-600 text-white text-xs font-medium rounded hover:bg-red-700">
            <i class="fa-regular fa-trash-can text-[11px]"></i> Delete
        </button>
        <button type="button" onclick="msgBulkClear()" class="ml-auto text-xs text-gray-500 hover:text-gray-700 px-2 py-1">Clear</button>
    </div>
</div>


<div class="inbox-shell grid grid-cols-1 lg:grid-cols-[420px_1fr] gap-4 items-start" data-pane="list" id="msg-shell">

    
    <div class="inbox-list-pane space-y-3 min-w-0">
        <?php if (empty($messages)): ?>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
                <i class="fa-regular fa-envelope-open text-5xl text-gray-200 mb-3"></i>
                <p class="text-sm font-medium text-gray-700"><?= $filterUnread ? 'No unread messages.' : 'No messages yet.' ?></p>
                <p class="text-xs text-gray-400 mt-1"><?= $filterUnread ? 'You are all caught up.' : 'Submissions from your contact form will appear here.' ?></p>
            </div>
        <?php else: ?>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                
                <div class="px-3 py-2 border-b border-gray-200 bg-gray-50 flex items-center gap-3">
                    <label class="inline-flex items-center" title="Select all on this page">
                        <input type="checkbox" id="msg-select-all"
                               class="w-3.5 h-3.5 rounded border-gray-300 text-primary-600 focus:ring-primary-500 cursor-pointer">
                    </label>
                    <span class="text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                        Inbox
                        <?php if ($filterUnread): ?>· unread only<?php endif; ?>
                    </span>
                    <span class="ml-auto text-[11px] text-gray-400"><?= count($messages) ?> on this page</span>
                </div>

                
                <ul id="msg-list" class="divide-y divide-gray-100 max-h-[calc(100vh-280px)] overflow-y-auto">
                    <?php foreach ($messages as $msg): ?>
                    <?php
                        $isUnread = !$msg['is_read'];
                        $isActive = (int) $msg['id'] === $selectedId;
                        $search = strtolower(
                            $msg['name'] . ' ' . $msg['email'] . ' ' . $msg['subject'] . ' ' . $msg['message']
                            . ' ' . ($msg['subject_type'] ?? '')
                        );
                    ?>
                    <li class="msg-row"
                        data-id="<?= (int)$msg['id'] ?>"
                        data-unread="<?= $isUnread ? '1' : '0' ?>"
                        data-search="<?= htmlspecialchars($search, ENT_QUOTES) ?>">
                        <div class="group relative inbox-row-tap flex items-stretch transition-colors cursor-pointer <?= $isActive ? 'bg-primary-50' : ($isUnread ? 'bg-blue-50/30 hover:bg-blue-50/60' : 'hover:bg-gray-50') ?>"
                             onclick="msgOpen(<?= (int)$msg['id'] ?>, event)">

                            
                            <span class="msg-accent absolute left-0 top-0 bottom-0 w-1 <?= $isActive ? 'bg-primary-600' : ($isUnread ? 'bg-primary-400' : 'bg-transparent') ?>"></span>

                            
                            <label class="flex items-center pl-2 pr-2 sm:pl-3 py-2.5 -my-2.5 cursor-pointer" onclick="event.stopPropagation()">
                                <input type="checkbox" class="msg-check w-3.5 h-3.5 rounded border-gray-300 text-primary-600 focus:ring-primary-500 cursor-pointer"
                                       data-id="<?= (int)$msg['id'] ?>" onchange="msgSelectChanged()">
                            </label>

                            
                            <div class="flex-1 min-w-0 py-2.5 pr-3">
                                <div class="flex items-center justify-between gap-2">
                                    <span class="text-sm truncate <?= $isUnread ? 'font-semibold text-gray-900' : 'text-gray-700' ?>">
                                        <?php if ($isUnread): ?><span class="msg-dot inline-block w-1.5 h-1.5 rounded-full bg-primary-500 align-middle mr-1.5"></span><?php endif; ?>
                                        <?= htmlspecialchars($msg['name']) ?>
                                    </span>
                                    <span class="text-[10px] text-gray-400 shrink-0 whitespace-nowrap" title="<?= htmlspecialchars(date('Y-m-d H:i', strtotime($msg['created_at']))) ?>">
                                        <?= $relTime($msg['created_at']) ?>
                                    </span>
                                </div>
                                <div class="text-xs <?= $isUnread ? 'text-gray-800 font-medium' : 'text-gray-600' ?> truncate mt-0.5">
                                    <?= htmlspecialchars($msg['subject']) ?>
                                    <?php if (!empty($msg['subject_type'])): ?>
                                        <span class="ml-1 inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-primary-100 text-primary-700 align-middle"><?= htmlspecialchars($msg['subject_type']) ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="text-[11px] text-gray-400 truncate mt-0.5">
                                    <?= htmlspecialchars($msg['email']) ?> · <?= htmlspecialchars(mb_substr(preg_replace('/\s+/', ' ', $msg['message']), 0, 60)) ?><?= mb_strlen($msg['message']) > 60 ? '…' : '' ?>
                                </div>
                            </div>
                        </div>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>

            <?php require APP_ROOT . '/templates/admin/_admin_pagination.php'; ?>
        <?php endif; ?>
    </div>

    
    <div id="msg-detail-wrap" class="inbox-detail-pane lg:sticky lg:top-4 min-w-0">
        
        <div class="inbox-detail-back hidden" id="msg-back-bar">
            <button type="button" onclick="msgClose()" class="inline-flex items-center justify-center w-9 h-9 rounded-full hover:bg-gray-100 text-gray-700" aria-label="Back to inbox">
                <i class="fa-solid fa-arrow-left"></i>
            </button>
            <span class="text-sm font-medium text-gray-700 truncate flex-1" id="msg-back-title">Message</span>
            <button type="button" onclick="msgDeleteCurrent()" class="inline-flex items-center justify-center w-9 h-9 rounded-full hover:bg-red-50 text-red-600" aria-label="Delete">
                <i class="fa-regular fa-trash-can"></i>
            </button>
        </div>
        
        <div id="msg-detail-empty" class="bg-white rounded-lg shadow-sm border border-gray-200 p-16 text-center">
            <i class="fa-regular fa-envelope-open-text text-6xl text-gray-200 mb-4"></i>
            <p class="text-sm font-medium text-gray-700">Select a message</p>
            <p class="text-xs text-gray-400 mt-1">Click a message on the left to view its contents.</p>
        </div>

        
        <div id="msg-detail-loading" class="hidden bg-white rounded-lg shadow-sm border border-gray-200 p-16 text-center">
            <i class="fa-solid fa-spinner fa-spin text-3xl text-primary-400 mb-3"></i>
            <p class="text-sm text-gray-500">Loading message…</p>
        </div>

        
        <article id="msg-detail" class="hidden bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            
            <header class="px-5 py-4 border-b border-gray-200">
                <h2 id="msg-d-subject" class="text-lg font-semibold text-gray-900 leading-snug"></h2>
                <span id="msg-d-tag" class="hidden mt-2 inline-flex items-center px-2 py-0.5 rounded text-[11px] font-medium bg-primary-100 text-primary-700"></span>
            </header>

            
            <div class="px-5 py-3 border-b border-gray-100 bg-gray-50/60">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-2 text-xs">
                    <div class="flex items-center gap-2 min-w-0">
                        <i class="fa-regular fa-user text-gray-400 w-3.5 text-center"></i>
                        <span class="font-medium text-gray-700 truncate" id="msg-d-name"></span>
                    </div>
                    <div class="flex items-center gap-2 min-w-0">
                        <i class="fa-regular fa-envelope text-gray-400 w-3.5 text-center"></i>
                        <a id="msg-d-email" href="#" class="text-primary-600 hover:underline truncate"></a>
                    </div>
                    <div class="flex items-center gap-2 min-w-0">
                        <i class="fa-regular fa-clock text-gray-400 w-3.5 text-center"></i>
                        <span class="text-gray-600 truncate" id="msg-d-date"></span>
                    </div>
                    <div class="flex items-center gap-2 min-w-0" id="msg-d-ip-wrap">
                        <i class="fa-solid fa-globe text-gray-400 w-3.5 text-center"></i>
                        <span class="text-gray-500 font-mono text-[11px] truncate" id="msg-d-ip"></span>
                    </div>
                </div>
            </div>

            
            <div class="px-5 py-4">
                <pre id="msg-d-body" class="text-sm text-gray-800 leading-relaxed whitespace-pre-wrap font-sans"></pre>
            </div>

            
            <div id="msg-d-urls-wrap" class="hidden px-5 py-3 border-t border-gray-100 bg-yellow-50/50">
                <h4 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Reported Content URLs</h4>
                <ul id="msg-d-urls" class="space-y-1"></ul>
            </div>

            
            <footer class="inbox-detail-actions border-t border-gray-200 bg-gray-50 px-5 py-3 flex flex-wrap items-center justify-between gap-2">
                <div class="flex flex-wrap items-center gap-2">
                    <a id="msg-d-reply" href="#"
                       class="inline-flex items-center gap-1.5 px-3 py-2 bg-primary-600 text-white text-xs font-medium rounded-lg hover:bg-primary-700 transition-colors">
                        <i class="fa-regular fa-paper-plane text-[11px]"></i> Reply by email
                    </a>
                    <button type="button" onclick="msgToggleRead()" id="msg-d-read-btn"
                            class="inline-flex items-center gap-1.5 px-3 py-2 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded-lg hover:bg-gray-50">
                        <i class="fa-regular fa-envelope text-[11px]"></i> <span id="msg-d-read-label">Mark unread</span>
                    </button>
                </div>
                <button type="button" onclick="msgDeleteCurrent()"
                        class="hidden sm:inline-flex items-center gap-1.5 px-3 py-2 bg-white text-red-600 border border-red-200 text-xs font-medium rounded-lg hover:bg-red-50">
                    <i class="fa-regular fa-trash-can text-[11px]"></i> Delete
                </button>
            </footer>
        </article>
    </div>
</div>

<script>
(function () {
    const csrf  = '<?= Router::csrfToken() ?>';
    const preselectId = <?= (int) $selectedId ?>;
    let currentId = 0;

    
    const search = document.getElementById('msg-search');
    if (search) {
        search.addEventListener('input', () => {
            const q = search.value.toLowerCase().trim();
            let visible = 0;
            document.querySelectorAll('#msg-list .msg-row').forEach(row => {
                const match = !q || row.dataset.search.includes(q);
                row.style.display = match ? '' : 'none';
                if (match) visible++;
            });
            const c = document.getElementById('msg-count');
            if (c) c.textContent = q ? visible + ' result' + (visible !== 1 ? 's' : '') : c.textContent;
        });
    }

    
    window.msgSelectChanged = function () {
        const ids = [...document.querySelectorAll('.msg-check:checked')].map(c => c.dataset.id);
        const bar = document.getElementById('msg-bulk');
        document.getElementById('msg-bulk-count').textContent = ids.length;
        bar.classList.toggle('hidden', ids.length === 0);
        const all = document.getElementById('msg-select-all');
        const total = document.querySelectorAll('.msg-check').length;
        if (all) {
            all.checked = ids.length > 0 && ids.length === total;
            all.indeterminate = ids.length > 0 && ids.length < total;
        }
    };
    const selectAllBox = document.getElementById('msg-select-all');
    if (selectAllBox) {
        selectAllBox.addEventListener('change', () => {
            document.querySelectorAll('.msg-check').forEach(c => { c.checked = selectAllBox.checked; });
            msgSelectChanged();
        });
    }
    window.msgBulkClear = function () {
        document.querySelectorAll('.msg-check').forEach(c => { c.checked = false; });
        msgSelectChanged();
    };
    
    async function msgDeleteRequest(id) {
        try {
            const res = await fetch('/admin/messages/' + id + '/delete', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                body: 'csrf_token=' + encodeURIComponent(csrf) + '&_ajax=1',
            });
            
            if (res.redirected || res.status === 401 || res.status === 403) return 'auth';
            const data = await res.json().catch(() => null);
            if (!res.ok || !data || data.success !== true) return 'fail';
            return 'ok';
        } catch (e) {
            return 'fail';
        }
    }
    function msgSessionExpired() {
        alert('Your session has expired — please sign in again. The page will now reload.');
        location.reload();
    }
    function msgRefreshAfterDelete() {
        
        if (document.querySelectorAll('#msg-list .msg-row').length === 0) location.reload();
    }

    window.msgBulkDelete = async function () {
        const ids = [...document.querySelectorAll('.msg-check:checked')].map(c => c.dataset.id);
        if (!ids.length) return;
        if (!confirm('Delete ' + ids.length + ' message(s)? This cannot be undone.')) return;
        const results = await Promise.all(ids.map(msgDeleteRequest));
        if (results.includes('auth')) { msgSessionExpired(); return; }
        let failed = 0;
        ids.forEach((id, i) => {
            if (results[i] === 'ok') {
                const row = document.querySelector('.msg-row[data-id="' + id + '"]');
                if (row) row.remove();
                if (currentId === parseInt(id, 10)) msgClose();
            } else {
                failed++;
            }
        });
        msgSelectChanged();
        if (failed > 0) {
            alert(failed + ' message(s) could not be deleted. Reloading to refresh the list.');
            location.reload();
            return;
        }
        msgRefreshAfterDelete();
    };
    window.msgBulkRead = async function (state) {
        const ids = [...document.querySelectorAll('.msg-check:checked')].map(c => c.dataset.id);
        if (!ids.length) return;
        await Promise.all(ids.map(id => fetch('/admin/messages/' + id + '/read', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'state=' + state + '&csrf_token=' + encodeURIComponent(csrf),
        })));
        ids.forEach(id => msgRowSetRead(parseInt(id, 10), state === 1));
        msgBulkClear();
    };

    
    function msgRowSetRead(id, isRead) {
        const row = document.querySelector('.msg-row[data-id="' + id + '"]');
        if (!row) return;
        row.dataset.unread = isRead ? '0' : '1';
        const card = row.querySelector('.group');
        const accent = row.querySelector('.msg-accent');
        const dot = row.querySelector('.msg-dot');
        const nameEl = row.querySelector('.text-sm');
        const subjEl = row.querySelectorAll('.text-xs')[0];
        if (isRead) {
            card.classList.remove('bg-blue-50/30','hover:bg-blue-50/60');
            if (!card.classList.contains('bg-primary-50')) card.classList.add('hover:bg-gray-50');
            accent.classList.remove('bg-primary-400');
            if (!accent.classList.contains('bg-primary-600')) accent.classList.add('bg-transparent');
            if (dot) dot.remove();
            nameEl?.classList.remove('font-semibold','text-gray-900');
            nameEl?.classList.add('text-gray-700');
            subjEl?.classList.remove('text-gray-800','font-medium');
            subjEl?.classList.add('text-gray-600');
        } else {
            card.classList.remove('hover:bg-gray-50');
            card.classList.add('bg-blue-50/30','hover:bg-blue-50/60');
            accent.classList.remove('bg-transparent');
            if (!accent.classList.contains('bg-primary-600')) accent.classList.add('bg-primary-400');
            nameEl?.classList.add('font-semibold','text-gray-900');
            nameEl?.classList.remove('text-gray-700');
        }
    }

    function msgRowSetActive(id) {
        document.querySelectorAll('.msg-row .group').forEach(card => {
            card.classList.remove('bg-primary-50');
            const a = card.querySelector('.msg-accent');
            if (a && a.classList.contains('bg-primary-600')) {
                a.classList.remove('bg-primary-600');
                const row = card.closest('.msg-row');
                a.classList.add(row?.dataset.unread === '1' ? 'bg-primary-400' : 'bg-transparent');
            }
        });
        const row = document.querySelector('.msg-row[data-id="' + id + '"]');
        if (row) {
            const card = row.querySelector('.group');
            card.classList.add('bg-primary-50');
            card.classList.remove('hover:bg-gray-50','hover:bg-blue-50/60','bg-blue-50/30');
            const a = row.querySelector('.msg-accent');
            if (a) { a.classList.remove('bg-transparent','bg-primary-400'); a.classList.add('bg-primary-600'); }
        }
    }

    
    const shell = document.getElementById('msg-shell');
    const isMobile = () => window.innerWidth < 1024;

    window.msgOpen = function (id, evt) {
        if (evt && evt.target && (evt.target.tagName === 'INPUT' || evt.target.tagName === 'LABEL')) return;
        currentId = id;
        msgRowSetActive(id);
        document.getElementById('msg-detail-empty').classList.add('hidden');
        document.getElementById('msg-detail').classList.add('hidden');
        document.getElementById('msg-detail-loading').classList.remove('hidden');

        
        if (isMobile()) {
            if (shell) shell.dataset.pane = 'detail';
            document.getElementById('msg-back-bar').classList.remove('hidden');
            document.querySelectorAll('.inbox-toolbar, .inbox-bulk').forEach(el => el.classList.add('inbox-mobile-hide'));
            window.scrollTo({ top: 0, behavior: 'instant' });
            if (history.state?.inboxPane !== 'detail') {
                history.pushState({ inboxPane: 'detail', id }, '');
            }
        }

        fetch('/admin/messages/' + id + '/json')
            .then(r => r.json())
            .then(d => {
                document.getElementById('msg-detail-loading').classList.add('hidden');
                if (d.error) { document.getElementById('msg-detail-empty').classList.remove('hidden'); return; }

                document.getElementById('msg-d-subject').textContent = d.subject;
                const tag = document.getElementById('msg-d-tag');
                if (d.subject_type) { tag.textContent = d.subject_type; tag.classList.remove('hidden'); }
                else { tag.classList.add('hidden'); }

                document.getElementById('msg-d-name').textContent = d.name;
                const emailA = document.getElementById('msg-d-email');
                emailA.textContent = d.email;
                emailA.href = 'mailto:' + d.email;
                document.getElementById('msg-d-date').textContent = d.created_at_long + '  (' + d.created_at_rel + ')';

                const ipWrap = document.getElementById('msg-d-ip-wrap');
                if (d.ip_address) { document.getElementById('msg-d-ip').textContent = d.ip_address; ipWrap.classList.remove('hidden'); }
                else { ipWrap.classList.add('hidden'); }

                document.getElementById('msg-d-body').textContent = d.message;

                const urlsWrap = document.getElementById('msg-d-urls-wrap');
                const urlsList = document.getElementById('msg-d-urls');
                urlsList.innerHTML = '';
                if (d.content_urls && d.content_urls.length) {
                    d.content_urls.forEach(u => {
                        const li = document.createElement('li');
                        const a = document.createElement('a');
                        a.href = u; a.target = '_blank'; a.rel = 'noopener noreferrer';
                        a.className = 'text-xs text-primary-600 hover:text-primary-800 hover:underline break-all inline-flex items-center gap-1';
                        a.innerHTML = u.replace(/[&<>]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[c])) + ' <i class="fa-solid fa-up-right-from-square text-[9px]"></i>';
                        li.appendChild(a);
                        urlsList.appendChild(li);
                    });
                    urlsWrap.classList.remove('hidden');
                } else {
                    urlsWrap.classList.add('hidden');
                }

                document.getElementById('msg-d-reply').href = 'mailto:' + d.email + '?subject=Re:%20' + encodeURIComponent(d.subject);
                document.getElementById('msg-d-read-label').textContent = d.is_read ? 'Mark unread' : 'Mark read';
                document.getElementById('msg-detail').classList.remove('hidden');
                document.getElementById('msg-back-title').textContent = d.subject || 'Message';

                if (d.was_unread) msgRowSetRead(id, true);

                
                const u = new URL(window.location);
                u.searchParams.set('id', id);
                history.replaceState({ ...(history.state || {}), id }, '', u);
            })
            .catch(() => {
                document.getElementById('msg-detail-loading').classList.add('hidden');
                document.getElementById('msg-detail-empty').classList.remove('hidden');
            });
    };

    window.msgClose = function (skipHistory) {
        currentId = 0;
        document.getElementById('msg-detail').classList.add('hidden');
        document.getElementById('msg-detail-loading').classList.add('hidden');
        document.getElementById('msg-detail-empty').classList.remove('hidden');
        document.querySelectorAll('.msg-row .group').forEach(card => {
            card.classList.remove('bg-primary-50');
            const row = card.closest('.msg-row');
            if (!card.classList.contains('hover:bg-gray-50') && row?.dataset.unread !== '1') card.classList.add('hover:bg-gray-50');
        });
        if (shell) shell.dataset.pane = 'list';
        document.getElementById('msg-back-bar').classList.add('hidden');
        document.querySelectorAll('.inbox-toolbar, .inbox-bulk').forEach(el => el.classList.remove('inbox-mobile-hide'));
        const u = new URL(window.location); u.searchParams.delete('id');
        if (!skipHistory && history.state?.inboxPane === 'detail') {
            history.back();
        } else {
            history.replaceState({ inboxPane: 'list' }, '', u);
        }
    };

    
    window.addEventListener('popstate', e => {
        if (currentId && shell?.dataset.pane === 'detail') {
            msgClose(true);
        }
    });

    window.msgToggleRead = async function () {
        if (!currentId) return;
        const row = document.querySelector('.msg-row[data-id="' + currentId + '"]');
        const wasUnread = row?.dataset.unread === '1';
        const newState = wasUnread ? 1 : 0;
        await fetch('/admin/messages/' + currentId + '/read', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'state=' + newState + '&csrf_token=' + encodeURIComponent(csrf),
        });
        msgRowSetRead(currentId, newState === 1);
        document.getElementById('msg-d-read-label').textContent = newState === 1 ? 'Mark unread' : 'Mark read';
    };

    window.msgDeleteCurrent = async function () {
        if (!currentId) return;
        if (!confirm('Delete this message?')) return;
        const id = currentId;
        const result = await msgDeleteRequest(id);
        if (result === 'auth') { msgSessionExpired(); return; }
        if (result !== 'ok') { alert('The message could not be deleted. Please try again.'); return; }
        const row = document.querySelector('.msg-row[data-id="' + id + '"]');
        if (row) row.remove();
        msgClose();
        msgRefreshAfterDelete();
    };

    
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && currentId) msgClose();
    });

    
    if (preselectId) msgOpen(preselectId);
})();
</script>
