<?php
// Variables: $admins, $messages, $otherAdmin, $unreadTotal, $announcements, $upcomingMeetings
$currentAdminId = (int)$_SESSION['admin_id'];
$csrfToken = \Core\System\Csrf::token();
$lastMsgId = !empty($messages) ? (int)end($messages)['id'] : 0;
$isOnline  = !empty($otherAdmin['last_seen_at']) && (strtotime($otherAdmin['last_seen_at']) >= time() - 300);

/* ── helper: render one attachment bubble ── */
function chatRenderAttachment(array $msg, bool $isMine): string
{
    if (!empty($msg['is_deleted'])) return '';
    if (empty($msg['attachment_path'])) return '';
    $type  = (string)($msg['attachment_type'] ?? '');
    $name  = htmlspecialchars($msg['attachment_name'] ?? 'file', ENT_QUOTES);
    $path  = htmlspecialchars($msg['attachment_path'], ENT_QUOTES);
    $size  = chatFormatSize((int)($msg['attachment_size'] ?? 0));
    $dl    = $isMine ? 'btn-light' : 'btn-outline-secondary';

    if (str_starts_with($type, 'image/')) {
        return '<div class="mt-1"><a href="'.$path.'" target="_blank" rel="noopener">
            <img src="'.$path.'" alt="'.$name.'" loading="lazy"
                 class="rounded shadow-sm" style="max-width:220px;max-height:220px;object-fit:cover;cursor:pointer;display:block">
        </a></div>';
    }

    $icon = 'bi-file-earmark-fill text-secondary';
    if (str_contains($type, 'pdf'))                                           $icon = 'bi-file-pdf-fill text-danger';
    elseif (str_contains($type, 'word') || str_contains($type, 'document'))   $icon = 'bi-file-word-fill text-primary';
    elseif (str_contains($type, 'excel') || str_contains($type, 'sheet'))     $icon = 'bi-file-excel-fill text-success';
    elseif (str_contains($type, 'zip') || str_contains($type, 'compressed'))  $icon = 'bi-file-zip-fill text-warning';

    return '<div class="mt-1 d-flex align-items-center gap-2 p-2 rounded" style="background:rgba(0,0,0,.12);min-width:180px">
        <i class="bi '.$icon.' fs-4 flex-shrink-0"></i>
        <div class="flex-grow-1 overflow-hidden">
            <div class="small fw-semibold" style="word-break:break-all">'.$name.'</div>
            <div style="font-size:.65rem;opacity:.8">'.$size.'</div>
        </div>
        <a href="'.$path.'" download class="btn btn-sm '.$dl.' py-0 flex-shrink-0">
            <i class="bi bi-download"></i>
        </a>
    </div>';
}

function chatFormatSize(int $bytes): string
{
    if ($bytes >= 1048576) return round($bytes / 1048576, 1) . ' MB';
    if ($bytes >= 1024)    return round($bytes / 1024, 1) . ' KB';
    return $bytes . ' B';
}

function chatRenderStatus(array $msg, bool $isMine): string
{
    if (!$isMine) return '';
    if (!empty($msg['is_deleted'])) {
        return '<span class="ms-1 text-warning" title="' . htmlspecialchars(__('team_comm.deleted','Deleted'), ENT_QUOTES) . '"><i class="bi bi-trash3"></i></span>';
    }
    if (!empty($msg['seen_at'])) {
        return '<span class="ms-1 text-info" title="Seen"><i class="bi bi-check2-all"></i></span>';
    }
    if (!empty($msg['delivered_at'])) {
        return '<span class="ms-1" title="Delivered"><i class="bi bi-check2-all"></i></span>';
    }
    return '<span class="ms-1" title="Sent"><i class="bi bi-check2"></i></span>';
}

function chatAttachmentBadge(array $msg): string
{
    if (!empty($msg['is_deleted'])) return '';
    $kind = (string)($msg['attachment_kind'] ?? '');
    if ($kind === '') return '';
    $label = $kind === 'image' ? __('team_comm.image','Image') : __('team_comm.document','Document');
    return '<span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle ms-2" style="font-size:.6rem">' . htmlspecialchars($label, ENT_QUOTES) . '</span>';
}

function chatDeletedText(array $msg): string
{
    if (empty($msg['is_deleted'])) {
        return '';
    }

    $deletedBy = htmlspecialchars((string)($msg['deleted_by_name'] ?? __('team_comm.team_member','Team member')), ENT_QUOTES);
    return '<div class="fst-italic small opacity-75"><i class="bi bi-trash3 me-1"></i>'
        . htmlspecialchars(__('team_comm.deleted_message_placeholder','This message was deleted'), ENT_QUOTES)
        . ' <span class="d-block mt-1" style="font-size:.7rem">'
        . htmlspecialchars(__('team_comm.deleted_by','Deleted by'), ENT_QUOTES)
        . ': ' . $deletedBy . '</span></div>';
}

include __DIR__ . '/../header.php';
?>
<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
        <h3 class="mb-1 fw-bold">
            <i class="bi bi-chat-text-fill me-2 text-primary"></i>
            <?= htmlspecialchars($otherAdmin['username']) ?>
        </h3>
        <p class="text-muted mb-0 small">
            <?= __('team.role_'.$otherAdmin['role'], $otherAdmin['role']) ?> &bull;
            <span id="onlineStatus">
                <?php if ($isOnline): ?>
                <span class="text-success"><i class="bi bi-circle-fill me-1" style="font-size:.5rem"></i><?= __('team_comm.online','Online') ?></span>
                <?php else: ?>
                <span class="text-muted"><?= __('team_comm.offline','Offline') ?></span>
                <?php endif; ?>
            </span>
        </p>
    </div>
    <a href="/admin/team/communication" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-left me-1"></i><?= __('team_comm.back_to_messages','All Messages') ?>
    </a>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="small text-muted mb-1"><?= __('team_comm.chat_with','Chat with') ?></div>
                <div class="fw-bold fs-5"><?= htmlspecialchars($otherAdmin['username']) ?></div>
                <div class="text-muted small"><?= __('team.role_'.$otherAdmin['role'], $otherAdmin['role']) ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="small text-muted mb-1"><?= __('team_comm.conversation_messages','Conversation messages') ?></div>
                <div class="fw-bold fs-5"><?= count($messages ?? []) ?></div>
                <div class="text-muted small"><?= __('team_comm.live_sync_enabled','Live sync is active') ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="small text-muted mb-1"><?= __('team_comm.shared_space','Shared workspace') ?></div>
                <div class="fw-bold fs-5"><?= $isOnline ? __('team_comm.online','Online') : __('team_comm.offline','Offline') ?></div>
                <div class="text-muted small"><?= __('team_comm.delete_notice','Deleted messages remain visible to managers for audit') ?></div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">

    <!-- LEFT: Members sidebar -->
    <div class="col-lg-3 d-none d-lg-block">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-primary text-white py-2">
                <span class="fw-semibold small"><i class="bi bi-chat-dots-fill me-2"></i><?= __('team_comm.direct_messages','Direct Messages') ?></span>
            </div>
            <div class="list-group list-group-flush" style="max-height:calc(100vh - 280px);overflow-y:auto">
                <?php foreach ($admins as $admin): ?>
                <?php $onl = !empty($admin['last_seen_at']) && (strtotime($admin['last_seen_at']) >= time() - 300); ?>
                <a href="/admin/team/communication/<?= $admin['id'] ?>"
                   class="list-group-item list-group-item-action d-flex align-items-center gap-2 py-2 <?= ((int)$admin['id'] === (int)$otherAdmin['id']) ? 'active' : '' ?>">
                    <div class="position-relative flex-shrink-0">
                        <img src="<?= htmlspecialchars(!empty($admin['avatar']) ? $admin['avatar'] : '/admin/assets/adminlte-assets/img/avatar.png', ENT_QUOTES) ?>"
                             class="rounded-circle" width="32" height="32" style="object-fit:cover" alt="">
                        <span class="position-absolute bottom-0 end-0 rounded-circle border border-white"
                              style="width:8px;height:8px;background:<?= $onl ? '#28a745' : '#adb5bd' ?>"></span>
                    </div>
                    <div class="flex-grow-1 overflow-hidden">
                        <div class="fw-semibold text-truncate" style="font-size:.8rem"><?= htmlspecialchars($admin['username']) ?></div>
                    </div>
                    <?php if (($admin['unread_count'] ?? 0) > 0 && (int)$admin['id'] !== (int)$otherAdmin['id']): ?>
                    <span class="badge bg-danger rounded-pill" style="font-size:.65rem"><?= (int)$admin['unread_count'] ?></span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- RIGHT: Chat window -->
    <div class="col-lg-9 col-12">
        <div class="card border-0 shadow-sm d-flex flex-column" style="height:calc(100vh - 210px)">

            <!-- Chat header -->
            <div class="card-header bg-white border-bottom d-flex align-items-center gap-3 py-2">
                <a href="/admin/team/communication" class="btn btn-sm btn-light d-lg-none">
                    <i class="bi bi-arrow-left"></i>
                </a>
                <div class="position-relative flex-shrink-0">
                    <img src="<?= htmlspecialchars(!empty($otherAdmin['avatar']) ? $otherAdmin['avatar'] : '/admin/assets/adminlte-assets/img/avatar.png', ENT_QUOTES) ?>"
                         class="rounded-circle" width="38" height="38" style="object-fit:cover" alt="">
                </div>
                <div>
                    <div class="fw-semibold"><?= htmlspecialchars($otherAdmin['username']) ?></div>
                    <div class="text-muted" style="font-size:.72rem"><?= __('team.role_'.$otherAdmin['role'], $otherAdmin['role']) ?></div>
                </div>
            </div>

            <!-- Messages area -->
            <div class="card-body overflow-auto flex-grow-1 p-3" id="chatMessages"
                 style="display:flex;flex-direction:column;gap:.75rem">
                <?php foreach ($messages as $msg): ?>
                <?php $isMine = ((int)$msg['sender_id'] === $currentAdminId); ?>
                <div class="d-flex <?= $isMine ? 'justify-content-end' : 'justify-content-start' ?> msg-row"
                     data-id="<?= $msg['id'] ?>">
                    <?php if (!$isMine): ?>
                    <img src="<?= htmlspecialchars(!empty($msg['sender_avatar']) ? $msg['sender_avatar'] : '/admin/assets/adminlte-assets/img/avatar.png', ENT_QUOTES) ?>"
                         class="rounded-circle me-2 flex-shrink-0 align-self-end" width="28" height="28" style="object-fit:cover" alt="">
                    <?php endif; ?>
                    <div class="px-3 py-2 rounded-3 shadow-sm<?= !empty($msg['is_pinned']) ? ' border border-warning-subtle' : '' ?>" style="max-width:68%;word-break:break-word;
                         background:<?= !empty($msg['is_deleted']) ? '#fff3cd' : ($isMine ? 'var(--bs-primary)' : 'var(--bs-light)') ?>;
                         color:<?= (!empty($msg['is_deleted']) || !$isMine) ? 'inherit' : '#fff' ?>">
                        <div class="d-flex align-items-center justify-content-between gap-2 mb-1">
                            <div>
                                <?php if (!empty($msg['is_pinned'])): ?><span class="badge bg-warning text-dark"><i class="bi bi-pin-angle-fill"></i></span><?php endif; ?>
                                <?= chatAttachmentBadge($msg) ?>
                            </div>
                            <div class="d-flex gap-1">
                                <?php if (empty($msg['is_deleted'])): ?>
                                <button type="button" class="btn btn-sm <?= $isMine ? 'btn-light' : 'btn-outline-secondary' ?> py-0 px-1 btn-pin-msg" data-id="<?= (int)$msg['id'] ?>" title="<?= htmlspecialchars(__('team_comm.pin_message','Pin message'), ENT_QUOTES) ?>">
                                    <i class="bi bi-pin-angle"></i>
                                </button>
                                <?php endif; ?>
                                <?php if ($isMine || in_array($_SESSION['admin_role'] ?? '', ['owner','manager'], true)): ?>
                                <button type="button" class="btn btn-sm <?= !empty($msg['is_deleted']) ? 'btn-outline-secondary' : ($isMine ? 'btn-light' : 'btn-outline-secondary') ?> py-0 px-1 btn-delete-msg" data-id="<?= (int)$msg['id'] ?>" title="<?= htmlspecialchars(__('team_comm.delete_message','Delete message'), ENT_QUOTES) ?>" <?= !empty($msg['is_deleted']) ? 'disabled' : '' ?>>
                                    <i class="bi bi-trash3"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php if (!empty($msg['is_deleted'])): ?>
                        <?= chatDeletedText($msg) ?>
                        <?php elseif ($msg['content'] !== ''): ?>
                        <div style="font-size:.875rem"><?= nl2br(htmlspecialchars($msg['content'])) ?></div>
                        <?php endif; ?>
                        <?= chatRenderAttachment($msg, $isMine) ?>
                        <div class="text-end mt-1" style="font-size:.65rem;opacity:.75">
                            <?= date('H:i', strtotime($msg['created_at'])) ?><?= chatRenderStatus($msg, $isMine) ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if (empty($messages)): ?>
                <div class="text-center text-muted my-auto">
                    <i class="bi bi-chat-heart fs-2 d-block mb-2 opacity-50"></i>
                    <small><?= __('team_comm.start_conversation','Say hello!') ?></small>
                </div>
                <?php endif; ?>
            </div>

            <div id="emojiPicker" class="px-3 pt-2" style="display:none">
                <div class="d-flex flex-wrap gap-2">
                    <?php foreach (['😊','😂','👍','❤️','🎉','👋','✅','🔥','😍','🙌','🤝','📅'] as $emoji): ?>
                        <button type="button" class="btn btn-light btn-sm border emoji-item" data-emoji="<?= htmlspecialchars($emoji, ENT_QUOTES) ?>"><?= htmlspecialchars($emoji) ?></button>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Attachment preview bar -->
            <div id="attachPreview" class="px-3 pt-2" style="display:none"></div>

            <!-- Input bar -->
            <div class="card-footer bg-white p-2">
                <div id="uploadError" class="text-danger small mb-1 d-none"></div>
                <div class="d-flex gap-2 align-items-end">
                    <!-- Paperclip button -->
                    <label for="attachInput" class="btn btn-light btn-sm flex-shrink-0 mb-0" style="cursor:pointer"
                           title="<?= htmlspecialchars(__('team_comm.attach_file','Attach file'), ENT_QUOTES) ?>">
                        <i class="bi bi-paperclip fs-5"></i>
                    </label>
                    <input type="file" id="attachInput" class="d-none"
                           accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx,.txt">
                    <button class="btn btn-light btn-sm flex-shrink-0" type="button" id="emojiBtn" title="<?= htmlspecialchars(__('team_comm.emoji','Emoji'), ENT_QUOTES) ?>"><i class="bi bi-emoji-smile"></i></button>
                    <textarea class="form-control form-control-sm" id="msgInput" rows="1"
                              placeholder="<?= htmlspecialchars(__('team_comm.type_message','Type a message...'), ENT_QUOTES) ?>"
                              style="resize:none;max-height:100px;overflow-y:auto"></textarea>
                    <button class="btn btn-primary btn-sm px-3 flex-shrink-0" id="sendBtn">
                        <i class="bi bi-send-fill"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

</div>
</section>
</div>

<script>
const CSRF       = <?= json_encode($csrfToken) ?>;
const RECEIVER_ID = <?= (int)$otherAdmin['id'] ?>;
const MY_ID      = <?= $currentAdminId ?>;
let lastId       = <?= $lastMsgId ?>;

const chatBox    = document.getElementById('chatMessages');
const input      = document.getElementById('msgInput');
const sendBtn    = document.getElementById('sendBtn');
const attachInput = document.getElementById('attachInput');
const previewArea = document.getElementById('attachPreview');
const errBox     = document.getElementById('uploadError');

function scrollBottom() { chatBox.scrollTop = chatBox.scrollHeight; }
scrollBottom();

// Auto-resize textarea
input.addEventListener('input', function () {
    this.style.height = 'auto';
    this.style.height = Math.min(this.scrollHeight, 100) + 'px';
});

/* ── Attachment preview ── */
attachInput.addEventListener('change', function () {
    errBox.classList.add('d-none');
    if (!this.files.length) { hidePreview(); return; }
    const file = this.files[0];
    if (file.size > 8 * 1024 * 1024) {
        showErr('<?= addslashes(__('team_comm.file_too_large','File too large (max 8 MB)')) ?>');
        this.value = '';
        return;
    }
    showPreview(file);
});

function showPreview(file) {
    previewArea.style.display = '';
    if (file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = e => {
            previewArea.innerHTML = previewHtml(
                `<img src="${e.target.result}" style="width:52px;height:52px;object-fit:cover;border-radius:6px">`,
                file
            );
        };
        reader.readAsDataURL(file);
    } else {
        previewArea.innerHTML = previewHtml(
            `<i class="bi ${getFileIcon(file.type)} fs-2"></i>`,
            file
        );
    }
}

function previewHtml(thumb, file) {
    return `<div class="d-flex align-items-center gap-2 p-2 bg-light rounded border mb-1">
        ${thumb}
        <div class="flex-grow-1">
            <div class="small fw-semibold text-truncate" style="max-width:200px">${escHtml(file.name)}</div>
            <div style="font-size:.7rem;color:#888">${formatSize(file.size)}</div>
        </div>
        <button type="button" class="btn btn-sm btn-outline-danger py-0" onclick="clearAttach()">
            <i class="bi bi-x-lg"></i>
        </button>
    </div>`;
}

function hidePreview() { previewArea.style.display = 'none'; previewArea.innerHTML = ''; }
function clearAttach() { attachInput.value = ''; hidePreview(); }
function showErr(msg) { errBox.textContent = msg; errBox.classList.remove('d-none'); }

/* ── Send ── */
function sendMessage() {
    const content = input.value.trim();
    const hasFile = attachInput.files.length > 0;
    if (!content && !hasFile) return;

    sendBtn.disabled = true;
    errBox.classList.add('d-none');

    const fd = new FormData();
    fd.append('_csrf',       CSRF);
    fd.append('receiver_id', RECEIVER_ID);
    fd.append('content',     content);
    if (hasFile) fd.append('attachment', attachInput.files[0]);

    fetch('/admin/team/messages/send', { method: 'POST', body: fd })
        .then(async r => { const t = await r.text(); try { return JSON.parse(t); } catch (e) { return { success: true, fallback_reload: true }; } })
        .then(d => {
            if (d.success) {
                input.value = '';
                input.style.height = 'auto';
                clearAttach();
                if (d.message && d.message.id) {
                    appendMessage(d.message, true);
                    lastId = parseInt(d.message.id, 10) || lastId;
                    scrollBottom();
                } else {
                    poll();
                }
            } else {
                showErr(d.error === 'file_too_large'
                    ? '<?= addslashes(__('team_comm.file_too_large','File too large (max 8 MB)')) ?>'
                    : '<?= addslashes(__('team_comm.send_failed','Send failed, please try again')) ?>');
            }
        })
        .catch(() => showErr('<?= addslashes(__('team_comm.send_failed','Send failed, please try again')) ?>'))
        .finally(() => { sendBtn.disabled = false; input.focus(); });
}

sendBtn.addEventListener('click', sendMessage);
input.addEventListener('keydown', e => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
});

/* ── Render a message bubble ── */
function appendMessage(msg, isMine) {
    const div = document.createElement('div');
    div.className = `d-flex ${isMine ? 'justify-content-end' : 'justify-content-start'} msg-row`;
    div.dataset.id = msg.id;

    const time = (msg.created_at || '').slice(11, 16);

    if (!isMine) {
        const av = document.createElement('img');
        av.src    = msg.sender_avatar || '/admin/assets/adminlte-assets/img/avatar.png';
        av.className = 'rounded-circle me-2 flex-shrink-0 align-self-end';
        av.width  = 28; av.height = 28;
        av.style.objectFit = 'cover';
        div.appendChild(av);
    }

    const bubble = document.createElement('div');
    bubble.className = 'px-3 py-2 rounded-3 shadow-sm';
    bubble.style.cssText = `max-width:68%;word-break:break-word;
        background:${msg.is_deleted ? '#fff3cd' : (isMine ? 'var(--bs-primary)' : 'var(--bs-light)')};
        color:${msg.is_deleted || !isMine ? 'inherit' : '#fff'}`;

    let inner = `<div class="d-flex align-items-center justify-content-between gap-2 mb-1"><div>${msg.is_pinned ? '<span class=\"badge bg-warning text-dark\"><i class=\"bi bi-pin-angle-fill\"></i></span>' : ''}${msg.is_deleted ? '' : (msg.attachment_kind ? `<span class=\"badge bg-secondary-subtle text-secondary border border-secondary-subtle ms-2\" style=\"font-size:.6rem\">${msg.attachment_kind === 'image' ? 'Image' : 'Document'}</span>` : '')}</div><div class="d-flex gap-1">${msg.is_deleted ? '' : `<button type="button" class="btn btn-sm ${isMine ? 'btn-light' : 'btn-outline-secondary'} py-0 px-1 btn-pin-msg" data-id="${msg.id}"><i class="bi bi-pin-angle"></i></button>`}${isMine ? `<button type="button" class="btn btn-sm ${isMine ? 'btn-light' : 'btn-outline-secondary'} py-0 px-1 btn-delete-msg" data-id="${msg.id}"><i class="bi bi-trash3"></i></button>` : ''}</div></div>`;
    if (msg.is_deleted) {
        inner += `<div class="fst-italic small opacity-75"><i class="bi bi-trash3 me-1"></i>${escHtml('<?= addslashes(__('team_comm.deleted_message_placeholder','This message was deleted')) ?>')}<span class="d-block mt-1" style="font-size:.7rem"><?= addslashes(__('team_comm.deleted_by','Deleted by')) ?>: ${escHtml(msg.deleted_by_name || '')}</span></div>`;
    } else if (msg.content && msg.content.trim()) {
        inner += `<div style="font-size:.875rem">${escHtml(msg.content).replace(/\n/g,'<br>')}</div>`;
    }
    inner += msg.is_deleted ? '' : renderAttachHtml(msg, isMine);
    inner += `<div class="text-end mt-1" style="font-size:.65rem;opacity:.75">${time}${renderStatusHtml(msg, isMine)}</div>`;
    bubble.innerHTML = inner;
    div.appendChild(bubble);
    chatBox.appendChild(div);
}

function renderAttachHtml(msg, isMine) {
    if (!msg.attachment_path) return '';
    const type = msg.attachment_type || '';
    const name = escHtml(msg.attachment_name || 'file');
    const path = escHtml(msg.attachment_path);
    const size = formatSize(parseInt(msg.attachment_size || 0));
    const dl   = isMine ? 'btn-light' : 'btn-outline-secondary';

    if (type.startsWith('image/')) {
        return `<div class="mt-1"><a href="${path}" target="_blank" rel="noopener">
            <img src="${path}" alt="${name}" loading="lazy" class="rounded shadow-sm"
                 style="max-width:220px;max-height:220px;object-fit:cover;cursor:pointer;display:block">
        </a></div>`;
    }

    return `<div class="mt-1 d-flex align-items-center gap-2 p-2 rounded" style="background:rgba(0,0,0,.12);min-width:180px">
        <i class="bi ${getFileIcon(type)} fs-4 flex-shrink-0"></i>
        <div class="flex-grow-1 overflow-hidden">
            <div class="small fw-semibold" style="word-break:break-all">${name}</div>
            <div style="font-size:.65rem;opacity:.8">${size}</div>
        </div>
        <a href="${path}" download class="btn btn-sm ${dl} py-0 flex-shrink-0">
            <i class="bi bi-download"></i>
        </a>
    </div>`;
}

/* ── Poll every 3 s ── */
function poll() {
    fetch(`/admin/team/messages/poll/${RECEIVER_ID}?last_id=${lastId}`)
        .then(async r => { const t = await r.text(); try { return JSON.parse(t); } catch (e) { return { success: true, fallback_reload: true }; } })
        .then(d => {
            if (d.success && d.messages.length > 0) {
                d.messages.forEach(m => {
                    if (!document.querySelector(`.msg-row[data-id="${m.id}"]`)) {
                        appendMessage(m, parseInt(m.sender_id) === MY_ID);
                        lastId = parseInt(m.id);
                    }
                });
                scrollBottom();
                const badge = document.getElementById('nav-msg-badge');
                if (badge) {
                    badge.textContent = d.unread > 0 ? Math.min(99, d.unread) : '';
                    badge.style.display = d.unread > 0 ? '' : 'none';
                }
            }
        });
}
setInterval(poll, 2000);


function renderStatusHtml(msg, isMine) {
    if (!isMine) return '';
    if (msg.is_deleted) return ' <span class="text-warning"><i class="bi bi-trash3"></i></span>';
    if (msg.seen_at) return ' <span class="text-info"><i class="bi bi-check2-all"></i></span>';
    if (msg.delivered_at) return ' <i class="bi bi-check2-all"></i>';
    return ' <i class="bi bi-check2"></i>';
}

document.addEventListener('click', function(e){
    const btn = e.target.closest('.btn-pin-msg');
    if (!btn) return;
    fetch(`/admin/team/messages/pin/${btn.dataset.id}`, {
        method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`_csrf=${encodeURIComponent(CSRF)}&other_id=${encodeURIComponent(RECEIVER_ID)}`
    }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); });
});

document.addEventListener('click', function(e){
    const btn = e.target.closest('.btn-delete-msg');
    if (!btn || btn.disabled) return;
    if (!confirm('<?= addslashes(__('team_comm.confirm_delete_message','Delete this message?')) ?>')) return;
    fetch(`/admin/team/messages/delete/${btn.dataset.id}`, {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`_csrf=${encodeURIComponent(CSRF)}`
    }).then(r=>r.json()).then(d=>{
        if (d.success) location.reload();
    });
});

document.getElementById('emojiBtn')?.addEventListener('click', function(){
    const picker = document.getElementById('emojiPicker');
    picker.style.display = picker.style.display === 'none' ? '' : 'none';
});
document.getElementById('emojiPicker')?.addEventListener('click', function(e){
    const btn = e.target.closest('[data-emoji]');
    if (!btn) return;
    const t = btn.getAttribute('data-emoji') || '';
    if (!t) return;
    input.value += t;
    input.dispatchEvent(new Event('input'));
    input.focus();
});

/* ── Helpers ── */
function escHtml(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function formatSize(b) {
    if (b >= 1048576) return (b/1048576).toFixed(1)+' MB';
    if (b >= 1024)    return (b/1024).toFixed(1)+' KB';
    return b+' B';
}
function getFileIcon(t) {
    if (!t) return 'bi-file-earmark-fill text-secondary';
    if (t.includes('pdf'))                                        return 'bi-file-pdf-fill text-danger';
    if (t.includes('word') || t.includes('document'))             return 'bi-file-word-fill text-primary';
    if (t.includes('excel') || t.includes('sheet'))               return 'bi-file-excel-fill text-success';
    if (t.includes('zip')  || t.includes('compressed'))           return 'bi-file-zip-fill text-warning';
    return 'bi-file-earmark-fill text-secondary';
}
</script>

<?php include __DIR__ . '/../footer.php'; ?>
