<?php
// Variables: $meeting, $groupMsgs, $lastGroupId, $unreadTotal
$currentAdminId = (int)$_SESSION['admin_id'];
$csrfToken      = \Core\System\Csrf::token();
$attendees      = $meeting['attendees'] ?? [];

function gcRenderAttach(array $msg, bool $isMine): string
{
    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 = gcFmtSize((int)($msg['attachment_size'] ?? 0));
    if (str_starts_with($type, 'image/')) {
        return '<a href="'.$path.'" target="_blank" rel="noopener" class="gc-img-link">
            <img src="'.$path.'" alt="'.$name.'" loading="lazy" class="gc-attach-img">
        </a>';
    }
    $icon = 'bi-file-earmark-fill';
    $ic   = 'text-secondary';
    if (str_contains($type,'pdf'))                                          { $icon='bi-file-pdf-fill';   $ic='text-danger';  }
    elseif (str_contains($type,'word')||str_contains($type,'document'))     { $icon='bi-file-word-fill';  $ic='text-primary'; }
    elseif (str_contains($type,'excel')||str_contains($type,'sheet'))       { $icon='bi-file-excel-fill'; $ic='text-success'; }
    elseif (str_contains($type,'zip')||str_contains($type,'compressed'))    { $icon='bi-file-zip-fill';   $ic='text-warning'; }
    return '<div class="gc-attach-doc">
        <i class="bi '.$icon.' '.$ic.'"></i>
        <div class="gc-doc-info">
            <div class="gc-doc-name">'.$name.'</div>
            <div class="gc-doc-size">'.$size.'</div>
        </div>
        <a href="'.$path.'" download class="gc-doc-dl"><i class="bi bi-download"></i></a>
    </div>';
}
function gcFmtSize(int $b): string {
    if ($b>=1048576) return round($b/1048576,1).' MB';
    if ($b>=1024)    return round($b/1024,1).' KB';
    return $b.' B';
}

/* Load theme from header.php logic */
include __DIR__ . '/../header.php';
?>
<style>
/* ════════════════════════════════════════════════════════════════
   HIDE ADMIN CHROME — this page is a full-screen chat room
   ════════════════════════════════════════════════════════════════ */
.app-sidebar,
.app-header,
.app-footer,
.sidebar-overlay { display: none !important; }
.app-main  { margin: 0 !important; padding: 0 !important; }
.app-content { padding: 0 !important; }
.content-wrapper { margin: 0 !important; padding: 0 !important; }

/* ════════════════════════════════════════════════════════════════
   CHAT APP SHELL  —  100vh, 3 rows: topbar | body | (inputbar inside body)
   ════════════════════════════════════════════════════════════════ */
#waApp {
    position: fixed; inset: 0;
    display: flex; flex-direction: column;
    background: #efeae2; /* WhatsApp-like warm background */
    font-size: 14px;
    overflow: hidden;
}

/* ────────────────────────────────────────
   TOP BAR  (like WhatsApp Web header)
   ──────────────────────────────────────── */
#waTopbar {
    height: 60px; min-height: 60px;
    background: var(--bs-card-bg, #fff);
    border-bottom: 1px solid var(--bs-border-color, #e9edef);
    display: flex; align-items: center; gap: 10px;
    padding: 0 16px;
    flex-shrink: 0;
    box-shadow: 0 1px 3px rgba(0,0,0,.07);
    z-index: 100;
}
#waTopbar .wa-back {
    width: 36px; height: 36px; border-radius: 50%; display: flex;
    align-items: center; justify-content: center; flex-shrink: 0;
    color: #54656f; text-decoration: none; font-size: 18px;
    transition: background .15s;
}
#waTopbar .wa-back:hover { background: rgba(0,0,0,.07); color: #111; }
#waTopbar .wa-av {
    width: 40px; height: 40px; border-radius: 50%; overflow: hidden; flex-shrink: 0;
    background: rgba(var(--bs-primary-rgb,13,110,253),.15);
    display: flex; align-items: center; justify-content: center;
    color: var(--bs-primary,#0d6efd); font-size: 18px;
    cursor: default;
}
#waTopbar .wa-meta { flex: 1; min-width: 0; }
#waTopbar .wa-meta .wa-name {
    font-size: 15px; font-weight: 700; line-height: 1.3;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    color: var(--bs-body-color,#111);
}
#waTopbar .wa-meta .wa-sub {
    font-size: 12px; color: #667781; white-space: nowrap;
    overflow: hidden; text-overflow: ellipsis; line-height: 1.3;
}
#waTopbar .wa-acts { display: flex; align-items: center; gap: 4px; }
#waTopbar .wa-icon-btn {
    width: 36px; height: 36px; border-radius: 50%;
    background: none; border: none; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    color: #54656f; font-size: 17px;
    transition: background .15s, color .15s;
}
#waTopbar .wa-icon-btn:hover { background: rgba(0,0,0,.07); color: #111; }
#waTopbar .wa-icon-btn.active { color: var(--bs-primary,#0d6efd); background: rgba(var(--bs-primary-rgb,13,110,253),.08); }

/* ────────────────────────────────────────
   BODY ROW  (sidebar + chat)
   ──────────────────────────────────────── */
#waBody { flex: 1; display: flex; overflow: hidden; }

/* ────────────────────────────────────────
   LEFT PANEL  (info sidebar — like WhatsApp info panel)
   ──────────────────────────────────────── */
#waPanel {
    width: 320px; flex-shrink: 0;
    background: var(--bs-card-bg,#fff);
    border-inline-end: 1px solid var(--bs-border-color,#e9edef);
    display: flex; flex-direction: column;
    overflow: hidden;
    transition: transform .26s cubic-bezier(.4,0,.2,1);
}
#waPanel .wp-head {
    padding: 16px 16px 10px;
    border-bottom: 1px solid var(--bs-border-color,#e9edef);
    font-size: 11px; font-weight: 700; text-transform: uppercase;
    letter-spacing: .08em; color: #aaa;
    display: flex; align-items: center; justify-content: space-between;
}
#waPanel .wp-scroll { flex: 1; overflow-y: auto; }

/* Info card */
.wp-info-card {
    margin: 12px 12px 4px;
    border-radius: 12px;
    background: rgba(var(--bs-primary-rgb,13,110,253),.05);
    border: 1px solid rgba(var(--bs-primary-rgb,13,110,253),.13);
    padding: 12px 14px;
}
.wp-info-card .wic-title {
    font-size: 14px; font-weight: 700; margin-bottom: 8px; line-height: 1.35;
    color: var(--bs-body-color,#111);
}
.wp-info-row {
    display: flex; align-items: flex-start; gap: 8px;
    font-size: 12.5px; color: #555; margin-bottom: 5px; line-height: 1.45;
}
.wp-info-row:last-child { margin: 0; }
.wp-info-row > i { color: var(--bs-primary,#0d6efd); font-size: 12px; flex-shrink:0; margin-top:2px; }
.wp-desc {
    margin: 4px 0 0; padding: 7px 10px; border-radius: 8px;
    background: rgba(0,0,0,.04); font-size: 12px; color: #555;
    line-height: 1.6; white-space: pre-wrap;
}

/* Attendees */
.wp-section-lbl {
    padding: 10px 14px 4px;
    font-size: 11px; font-weight: 700; text-transform: uppercase;
    letter-spacing: .08em; color: #aaa;
    display: flex; align-items: center; gap: 6px;
}
.wp-att-count {
    background: rgba(var(--bs-primary-rgb,13,110,253),.12);
    color: var(--bs-primary,#0d6efd);
    font-size: 10px; padding: 1px 6px; border-radius: 10px; font-weight: 700;
}
.wa-att-item {
    display: flex; align-items: center; gap: 10px;
    padding: 7px 14px;
    border-bottom: 1px solid rgba(0,0,0,.04);
    transition: background .12s;
}
.wa-att-item:last-child { border: none; }
.wa-att-item:hover { background: rgba(var(--bs-primary-rgb,13,110,253),.04); }
.wa-att-av {
    width: 36px; height: 36px; border-radius: 50%; object-fit: cover; flex-shrink: 0;
    border: 2px solid rgba(var(--bs-primary-rgb,13,110,253),.18);
}
.wa-att-info { flex: 1; min-width: 0; }
.wa-att-name {
    font-size: 13px; font-weight: 600;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    display: flex; align-items: center; gap: 5px; color: var(--bs-body-color,#111);
}
.wa-att-you {
    font-size: 9px; background: rgba(var(--bs-primary-rgb,13,110,253),.12);
    color: var(--bs-primary,#0d6efd); padding: 1px 5px; border-radius: 4px; font-weight: 700;
}
.wa-att-role { font-size: 11px; color: #999; }
.wa-rsvp-dot {
    width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0;
}
.wa-rsvp-dot.accepted { background: var(--bs-success,#25d366); }
.wa-rsvp-dot.declined { background: var(--bs-danger,#dc3545); }
.wa-rsvp-dot.pending  { background: #ccc; }

/* ────────────────────────────────────────
   CHAT AREA
   ──────────────────────────────────────── */
#waChat {
    flex: 1; display: flex; flex-direction: column; overflow: hidden;
    position: relative;
}

/* Background — WhatsApp wallpaper feel */
#waBg {
    position: absolute; inset: 0; z-index: 0;
    background-color: #efeae2;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Cpath d='M0 0h80v80H0z' fill='%23e5ddd5'/%3E%3Cpath d='M40 20c0 11-9 20-20 20S0 31 0 20 9 0 20 0s20 9 20 20zm40 40c0 11-9 20-20 20s-20-9-20-20 9-20 20-20 20 9 20 20z' fill='none' stroke='%23d4cdc6' stroke-width='.5'/%3E%3C/svg%3E");
    background-size: 80px 80px;
    pointer-events: none;
}

/* Messages scroll area */
#waMessages {
    flex: 1; overflow-y: auto; padding: 12px 5%;
    display: flex; flex-direction: column; gap: 2px;
    position: relative; z-index: 1;
}
#waMessages::-webkit-scrollbar { width: 6px; }
#waMessages::-webkit-scrollbar-track { background: transparent; }
#waMessages::-webkit-scrollbar-thumb { background: rgba(0,0,0,.15); border-radius: 6px; }

/* ── Date separator ── */
.wa-date-sep {
    display: flex; align-items: center; justify-content: center;
    margin: 8px 0;
}
.wa-date-sep span {
    background: rgba(225,245,254,.92); backdrop-filter: blur(4px);
    color: #54656f; font-size: 11.5px; font-weight: 500;
    padding: 3px 10px; border-radius: 20px;
    box-shadow: 0 1px 2px rgba(0,0,0,.1);
}

/* ── Message row ── */
.wa-row {
    display: flex; align-items: flex-end; gap: 6px;
    margin-bottom: 1px;
}
.wa-row + .wa-row.wa-new-group { margin-top: 6px; }

/* Avatar */
.wa-av-col { width: 28px; flex-shrink: 0; align-self: flex-end; }
.wa-av-col img {
    width: 28px; height: 28px; border-radius: 50%; object-fit: cover;
    display: block; border: 1.5px solid rgba(255,255,255,.9);
    box-shadow: 0 1px 3px rgba(0,0,0,.12);
}
.wa-av-col.hidden { visibility: hidden; }

/* RTL support */
.wa-row.is-mine  { flex-direction: row-reverse; }
[dir=rtl] .wa-row { flex-direction: row-reverse; }
[dir=rtl] .wa-row.is-mine { flex-direction: row; }

/* Bubble wrapper */
.wa-bbl-wrap { max-width: min(65%, 520px); }

/* Sender name (above first bubble in a group) */
.wa-sender {
    font-size: 12px; font-weight: 700;
    color: var(--bs-primary,#0d6efd);
    padding: 0 12px; margin-bottom: 2px; line-height: 1.2;
}

/* Bubble — the WhatsApp bubble shape */
.wa-bbl {
    padding: 6px 10px 4px;
    border-radius: 7.5px;
    position: relative; word-break: break-word;
    box-shadow: 0 1px 2px rgba(0,0,0,.11);
    transition: box-shadow .12s;
}
/* Tail for first bubble in group */
.wa-row:not(.wa-same-sender) .wa-bbl::before {
    content: '';
    position: absolute;
    bottom: 0; width: 0; height: 0; border-style: solid;
}
/* Other — tail left */
.wa-row:not(.is-mine):not(.wa-same-sender) .wa-bbl::before {
    inset-inline-start: -8px;
    border-width: 0 8px 8px 0;
    border-color: transparent #fff transparent transparent;
}
[dir=rtl] .wa-row:not(.is-mine):not(.wa-same-sender) .wa-bbl::before {
    border-width: 0 0 8px 8px;
    border-color: transparent transparent transparent #fff;
    inset-inline-start: auto; inset-inline-end: -8px;
}
/* Mine — tail right */
.wa-row.is-mine:not(.wa-same-sender) .wa-bbl::before {
    inset-inline-end: -8px;
    border-width: 8px 8px 0 0;
    border-color: var(--gc-mine-bubble, var(--bs-primary,#0d6efd)) transparent transparent transparent;
}
[dir=rtl] .wa-row.is-mine:not(.wa-same-sender) .wa-bbl::before {
    inset-inline-end: auto; inset-inline-start: -8px;
    border-width: 8px 0 0 8px;
    border-color: var(--gc-mine-bubble, var(--bs-primary,#0d6efd)) transparent transparent transparent;
}

/* Other bubble */
.wa-other .wa-bbl {
    background: #fff;
    color: #111;
    border-top-left-radius: 0;
}
[dir=rtl] .wa-other .wa-bbl { border-top-left-radius: 7.5px; border-top-right-radius: 0; }

/* Mine bubble */
.wa-mine .wa-bbl {
    --gc-mine-bubble: var(--bs-primary,#0d6efd);
    background: var(--gc-mine-bubble);
    color: #fff;
    border-top-right-radius: 0;
}
[dir=rtl] .wa-mine .wa-bbl { border-top-right-radius: 7.5px; border-top-left-radius: 0; }

/* Pinned indicator */
.wa-bbl.pinned { outline: 1.5px solid rgba(255,193,7,.55); outline-offset: 1px; }
.wa-pin-flag {
    display: inline-flex; align-items: center; gap: 3px;
    font-size: 10px; font-weight: 700;
    padding: 1px 6px; border-radius: 5px; margin-bottom: 3px;
    background: rgba(255,193,7,.18); color: #856404;
    border: 1px solid rgba(255,193,7,.3);
}

/* Message text */
.wa-text { font-size: 13.5px; line-height: 1.6; white-space: pre-wrap; }

/* Meta row (time + pin btn) */
.wa-meta-row {
    display: flex; align-items: center; justify-content: flex-end;
    gap: 5px; margin-top: 2px;
}
.wa-time {
    font-size: 11px; line-height: 1;
    color: rgba(0,0,0,.4);
}
.wa-mine .wa-time { color: rgba(255,255,255,.65); }
.wa-pin-btn {
    background: none; border: none; padding: 0; cursor: pointer;
    font-size: 12px; color: rgba(0,0,0,.3); border-radius: 3px;
    opacity: 0; transition: opacity .15s; display: flex; align-items: center;
    line-height: 1;
}
.wa-bbl:hover .wa-pin-btn { opacity: 1; }
.wa-mine .wa-pin-btn { color: rgba(255,255,255,.55); }

/* ── Image attachment ── */
.gc-img-link { display: block; margin-top: 4px; }
.gc-attach-img {
    max-width: 240px; max-height: 240px; width: 100%;
    object-fit: cover; border-radius: 8px; display: block;
    box-shadow: 0 1px 4px rgba(0,0,0,.15); cursor: pointer;
    transition: transform .15s;
}
.gc-attach-img:hover { transform: scale(1.02); }

/* ── File attachment ── */
.gc-attach-doc {
    display: flex; align-items: center; gap: 8px;
    margin-top: 4px; padding: 8px 10px;
    background: rgba(0,0,0,.08); border-radius: 10px;
    min-width: 180px; max-width: 240px;
}
.wa-mine .gc-attach-doc { background: rgba(0,0,0,.2); }
.gc-attach-doc > i { font-size: 1.6rem; flex-shrink: 0; }
.gc-doc-info { flex: 1; min-width: 0; }
.gc-doc-name { font-size: 12.5px; font-weight: 600; word-break: break-all; }
.gc-doc-size { font-size: 10.5px; opacity: .7; }
.gc-doc-dl {
    width: 28px; height: 28px; border-radius: 50%; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center;
    font-size: 13px; text-decoration: none;
    background: rgba(255,255,255,.2); color: inherit;
    transition: background .15s;
}
.gc-doc-dl:hover { background: rgba(255,255,255,.4); }

/* Empty state */
.wa-empty {
    flex: 1; display: flex; flex-direction: column;
    align-items: center; justify-content: center; gap: 10px;
    pointer-events: none;
}
.wa-empty-badge {
    background: rgba(225,245,254,.9); backdrop-filter: blur(4px);
    padding: 10px 20px; border-radius: 16px;
    font-size: 12.5px; color: #667781; text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,.08); max-width: 260px;
}

/* ────────────────────────────────────────
   EMOJI TRAY
   ──────────────────────────────────────── */
#waEmojiTray {
    background: var(--bs-card-bg,#fff);
    border-top: 1px solid var(--bs-border-color,#e9edef);
    padding: 8px 12px;
    display: none; flex-wrap: wrap; gap: 4px;
    position: relative; z-index: 2;
    max-height: 80px; overflow-y: auto;
}
#waEmojiTray.open { display: flex; }
.wa-emoji-item {
    background: none; border: 1px solid var(--bs-border-color,#e9edef);
    border-radius: 7px; padding: 2px 6px; cursor: pointer;
    font-size: 18px; line-height: 1.3;
    transition: background .1s, transform .1s;
}
.wa-emoji-item:hover {
    background: rgba(var(--bs-primary-rgb,13,110,253),.08);
    border-color: rgba(var(--bs-primary-rgb,13,110,253),.3);
    transform: scale(1.2);
}

/* ────────────────────────────────────────
   ATTACHMENT PREVIEW BAR
   ──────────────────────────────────────── */
#waPreviewBar {
    background: var(--bs-card-bg,#fff);
    border-top: 1px solid var(--bs-border-color,#e9edef);
    padding: 8px 14px; display: none;
    position: relative; z-index: 2;
}
#waPreviewBar.show { display: block; }
.wa-prev-inner {
    display: flex; align-items: center; gap: 10px;
    background: rgba(var(--bs-primary-rgb,13,110,253),.06);
    border: 1px solid rgba(var(--bs-primary-rgb,13,110,253),.16);
    border-radius: 12px; padding: 8px 12px;
}
.wa-prev-thumb { width: 44px; height: 44px; border-radius: 7px; object-fit: cover; flex-shrink: 0; }
.wa-prev-file-ic { font-size: 1.8rem; flex-shrink: 0; }
.wa-prev-meta { flex: 1; min-width: 0; }
.wa-prev-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.wa-prev-size { font-size: 11px; color: #888; }
.wa-prev-rm {
    background: none; border: none; cursor: pointer; color: #aaa;
    width: 26px; height: 26px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 13px; transition: background .15s, color .15s;
}
.wa-prev-rm:hover { background: rgba(220,53,69,.1); color: #dc3545; }

/* Error */
#waErr { display: none; font-size: 12px; color: #dc3545; padding: 2px 14px 0; position: relative; z-index: 2; }
#waErr.show { display: block; }

/* ────────────────────────────────────────
   INPUT BAR  (WhatsApp-exact feel)
   ──────────────────────────────────────── */
#waInputBar {
    background: var(--bs-card-bg,#f0f2f5);
    padding: 8px 14px;
    display: flex; align-items: flex-end; gap: 8px;
    flex-shrink: 0; position: relative; z-index: 2;
    border-top: 1px solid var(--bs-border-color,#e9edef);
}
.wa-ib-btn {
    width: 40px; height: 40px; border-radius: 50%; flex-shrink: 0;
    background: none; border: none; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    color: #54656f; font-size: 20px; align-self: flex-end;
    transition: color .15s;
}
.wa-ib-btn:hover, .wa-ib-btn.active { color: var(--bs-primary,#0d6efd); }
.wa-textarea-wrap {
    flex: 1; background: #fff;
    border: 1px solid var(--bs-border-color,#e9edef);
    border-radius: 22px; padding: 9px 14px;
    display: flex; align-items: flex-end; gap: 6px;
    min-height: 42px; box-shadow: 0 1px 2px rgba(0,0,0,.06);
    transition: border-color .2s, box-shadow .2s;
}
.wa-textarea-wrap:focus-within {
    border-color: rgba(var(--bs-primary-rgb,13,110,253),.45);
    box-shadow: 0 0 0 3px rgba(var(--bs-primary-rgb,13,110,253),.1);
}
#gcInput {
    flex: 1; background: none; border: none; outline: none;
    resize: none; font-size: 14px; line-height: 1.5;
    max-height: 110px; overflow-y: auto; padding: 0;
    color: var(--bs-body-color,#111);
}
#gcInput::placeholder { color: #aebac1; }
/* Send button — WhatsApp green-like but uses --bs-primary */
#gcSendBtn {
    width: 42px; height: 42px; border-radius: 50%; flex-shrink: 0;
    background: var(--bs-primary,#0d6efd); border: none; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    color: #fff; font-size: 17px; align-self: flex-end;
    box-shadow: 0 2px 8px rgba(var(--bs-primary-rgb,13,110,253),.45);
    transition: filter .15s, transform .12s;
}
#gcSendBtn:hover  { filter: brightness(1.1); transform: scale(1.07); }
#gcSendBtn:active { transform: scale(.9); }
#gcSendBtn:disabled { opacity: .5; cursor: not-allowed; transform: none; box-shadow: none; }
[dir=rtl] #gcSendBtn i { transform: scaleX(-1); }

/* ────────────────────────────────────────
   MOBILE (< 992px) — sidebar off-canvas
   ──────────────────────────────────────── */
@media (max-width: 991.98px) {
    #waPanel {
        position: fixed; inset: 0;
        z-index: 1060; width: 290px;
        transform: translateX(-100%);
        box-shadow: 4px 0 20px rgba(0,0,0,.15);
    }
    [dir=rtl] #waPanel { transform: translateX(100%); }
    #waPanel.open { transform: translateX(0); }
    #waBackdrop {
        display: none; position: fixed; inset: 0;
        background: rgba(0,0,0,.38); z-index: 1059;
    }
    #waBackdrop.show { display: block; }
    .wp-mobile-close { display: flex !important; }
}
@media (min-width: 992px) {
    #waBackdrop { display: none !important; }
    .wp-mobile-close { display: none !important; }
}
</style>

<div id="waApp">

    <!-- ══ TOP BAR ══ -->
    <div id="waTopbar">
        <a href="/admin/team/meetings" class="wa-back" title="<?= htmlspecialchars(__('team_meeting.back','Back')) ?>">
            <i class="bi bi-arrow-<?= \Core\System\Language::direction() === 'rtl' ? 'right' : 'left' ?>"></i>
        </a>
        <div class="wa-av"><i class="bi bi-people-fill"></i></div>
        <div class="wa-meta">
            <div class="wa-name"><?= htmlspecialchars($meeting['title']) ?></div>
            <div class="wa-sub">
                <?php
                $attNames = array_map(fn($a) => htmlspecialchars($a['username']), array_slice($attendees, 0, 5));
                echo implode(', ', $attNames);
                if (count($attendees) > 5) echo ' +'.( count($attendees)-5);
                ?>
            </div>
        </div>
        <div class="wa-acts">
            <button class="wa-icon-btn d-lg-none" id="waInfoBtn" title="Info">
                <i class="bi bi-info-circle"></i>
            </button>
        </div>
    </div>

    <div id="waBody">

        <!-- Backdrop -->
        <div id="waBackdrop"></div>

        <!-- ══ LEFT PANEL ══ -->
        <div id="waPanel">
            <div class="wp-head">
                <span><?= __('team_meeting.meeting_info','Meeting Info') ?></span>
                <button class="wa-icon-btn wp-mobile-close" style="display:none" id="waPanelClose">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="wp-scroll">

                <!-- Meeting card -->
                <div class="wp-info-card">
                    <div class="wic-title"><?= htmlspecialchars($meeting['title']) ?></div>
                    <div class="wp-info-row">
                        <i class="bi bi-tag-fill"></i>
                        <span><?= __('team_meeting.type_'.$meeting['meeting_type'], str_replace('_',' ',$meeting['meeting_type'])) ?></span>
                    </div>
                    <?php if (!empty($meeting['scheduled_at'])): ?>
                    <div class="wp-info-row">
                        <i class="bi bi-calendar-event-fill"></i>
                        <span><?= app_format_datetime($meeting['scheduled_at'], 'd M Y, H:i') ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($meeting['duration_minutes'])): ?>
                    <div class="wp-info-row">
                        <i class="bi bi-stopwatch-fill"></i>
                        <span><?= (int)$meeting['duration_minutes'] ?> <?= __('team_comm.minutes','min') ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($meeting['location'])): ?>
                    <div class="wp-info-row">
                        <i class="bi bi-geo-alt-fill"></i>
                        <span><?= htmlspecialchars($meeting['location']) ?></span>
                    </div>
                    <?php endif; ?>
                    <?php
                    $stColors = ['upcoming'=>'primary','completed'=>'success','cancelled'=>'secondary'];
                    $stC = $stColors[$meeting['status']] ?? 'secondary';
                    ?>
                    <div class="wp-info-row">
                        <i class="bi bi-circle-fill" style="color:var(--bs-<?= $stC ?>);font-size:8px;margin-top:4px"></i>
                        <span><?= __('team_meeting.status_'.$meeting['status'], $meeting['status']) ?></span>
                    </div>
                    <?php if (!empty($meeting['description'])): ?>
                    <div class="wp-desc"><?= nl2br(htmlspecialchars($meeting['description'])) ?></div>
                    <?php endif; ?>
                </div>

                <!-- Attendees -->
                <div class="wp-section-lbl">
                    <i class="bi bi-people-fill"></i>
                    <?= __('team_meeting.attendees','Attendees') ?>
                    <span class="wp-att-count"><?= count($attendees) ?></span>
                </div>

                <?php foreach ($attendees as $att):
                    $rv = $att['rsvp'] ?? 'pending'; ?>
                <div class="wa-att-item">
                    <img src="<?= htmlspecialchars(!empty($att['avatar']) ? $att['avatar'] : '/admin/assets/adminlte-assets/img/avatar.png', ENT_QUOTES) ?>"
                         class="wa-att-av" alt="">
                    <div class="wa-att-info">
                        <div class="wa-att-name">
                            <?= htmlspecialchars($att['username']) ?>
                            <?php if ((int)$att['admin_id'] === $currentAdminId): ?>
                            <span class="wa-att-you"><?= __('team_comm.you','You') ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="wa-att-role"><?= __('team.role_'.$att['role'], $att['role']) ?></div>
                    </div>
                    <span class="wa-rsvp-dot <?= $rv ?>" title="<?= __('team_meeting.rsvp_'.$rv, $rv) ?>"></span>
                </div>
                <?php endforeach; ?>

            </div><!-- /.wp-scroll -->
        </div><!-- /#waPanel -->

        <!-- ══ CHAT ══ -->
        <div id="waChat">
            <div id="waBg"></div>

            <div id="waMessages">
                <?php if (empty($groupMsgs)): ?>
                <div class="wa-empty" id="waEmptyState">
                    <div class="wa-empty-badge">
                        <i class="bi bi-lock-fill me-1" style="font-size:11px"></i>
                        <?= __('team_comm.group_chat_empty','No messages yet — be the first to say hello!') ?>
                    </div>
                </div>
                <?php else: ?>
                <?php
                $prevSenderId = null;
                foreach ($groupMsgs as $msg):
                    $isMine    = ((int)$msg['sender_id'] === $currentAdminId);
                    $sameSnd   = ($msg['sender_id'] == $prevSenderId);
                    $prevSenderId = $msg['sender_id'];
                ?>
                <div class="wa-row <?= $isMine ? 'is-mine wa-mine' : 'wa-other' ?> <?= $sameSnd ? 'wa-same-sender' : 'wa-new-group' ?>"
                     data-id="<?= (int)$msg['id'] ?>">

                    <?php if (!$isMine): ?>
                    <div class="wa-av-col <?= $sameSnd ? 'hidden' : '' ?>">
                        <img src="<?= htmlspecialchars(!empty($msg['sender_avatar']) ? $msg['sender_avatar'] : '/admin/assets/adminlte-assets/img/avatar.png', ENT_QUOTES) ?>" alt="">
                    </div>
                    <?php endif; ?>

                    <div class="wa-bbl-wrap">
                        <?php if (!$isMine && !$sameSnd): ?>
                        <div class="wa-sender"><?= htmlspecialchars($msg['sender_name'] ?? '') ?></div>
                        <?php endif; ?>
                        <div class="wa-bbl<?= !empty($msg['is_pinned']) ? ' pinned' : '' ?>">
                            <?php if (!empty($msg['is_pinned'])): ?>
                            <div class="wa-pin-flag"><i class="bi bi-pin-angle-fill"></i> <?= __('team_comm.pinned','Pinned') ?></div>
                            <?php endif; ?>
                            <?php if ((string)$msg['content'] !== ''): ?>
                            <div class="wa-text"><?= nl2br(htmlspecialchars($msg['content'])) ?></div>
                            <?php endif; ?>
                            <?= gcRenderAttach($msg, $isMine) ?>
                            <div class="wa-meta-row">
                                <button type="button" class="wa-pin-btn btn-pin-gc" data-id="<?= (int)$msg['id'] ?>"
                                        title="<?= htmlspecialchars(__('team_comm.pin_message','Pin')) ?>">
                                    <i class="bi <?= !empty($msg['is_pinned']) ? 'bi-pin-angle-fill' : 'bi-pin-angle' ?>"></i>
                                </button>
                                <span class="wa-time"><?= date('H:i', strtotime($msg['created_at'])) ?></span>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div><!-- /#waMessages -->

            <!-- Emoji tray -->
            <div id="waEmojiTray">
                <?php foreach (['😊','😂','👍','❤️','🎉','👋','✅','🔥','😍','🙌','🤝','📅','💬','⏰','📌','👀','🙏','💪','🎯','👏'] as $e): ?>
                <button type="button" class="wa-emoji-item" data-emoji="<?= htmlspecialchars($e, ENT_QUOTES) ?>"><?= $e ?></button>
                <?php endforeach; ?>
            </div>

            <!-- Attachment preview -->
            <div id="waPreviewBar"></div>

            <!-- Error -->
            <div id="waErr"></div>

            <!-- Input bar -->
            <div id="waInputBar">
                <label for="gcAttachInput" class="wa-ib-btn" title="<?= htmlspecialchars(__('team_comm.attach_file','Attach')) ?>">
                    <i class="bi bi-paperclip"></i>
                </label>
                <input type="file" id="gcAttachInput" class="d-none"
                       accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx,.txt">

                <div class="wa-textarea-wrap">
                    <button class="wa-ib-btn" type="button" id="gcEmojiBtn" title="Emoji" style="width:30px;height:30px;font-size:18px;align-self:flex-end;margin-bottom:0">
                        <i class="bi bi-emoji-smile"></i>
                    </button>
                    <textarea id="gcInput" rows="1"
                              placeholder="<?= htmlspecialchars(__('team_comm.type_message','Type a message')) ?>"></textarea>
                </div>

                <button id="gcSendBtn" type="button">
                    <i class="bi bi-send-fill"></i>
                </button>
            </div>

        </div><!-- /#waChat -->
    </div><!-- /#waBody -->
</div><!-- /#waApp -->

<script>
const GC_CSRF    = <?= json_encode($csrfToken) ?>;
const GC_MEETING = <?= (int)$meeting['id'] ?>;
const GC_MY_ID   = <?= $currentAdminId ?>;
let   gcLastId   = <?= (int)$lastGroupId ?>;

const waMessages = document.getElementById('waMessages');
const gcInput    = document.getElementById('gcInput');
const gcSendBtn  = document.getElementById('gcSendBtn');
const gcAttach   = document.getElementById('gcAttachInput');
const waPreview  = document.getElementById('waPreviewBar');
const waErr      = document.getElementById('waErr');

function gcScroll(smooth) {
    waMessages.scrollTo({ top: waMessages.scrollHeight, behavior: smooth ? 'smooth' : 'instant' });
}
gcScroll(false);

/* ── Textarea resize ── */
gcInput.addEventListener('input', function () {
    this.style.height = 'auto';
    this.style.height = Math.min(this.scrollHeight, 110) + 'px';
});

/* ── File select ── */
gcAttach.addEventListener('change', function () {
    waErr.classList.remove('show');
    if (!this.files.length) { waHidePreview(); return; }
    const file = this.files[0];
    if (file.size > 8 * 1024 * 1024) {
        waErr.textContent = '<?= addslashes(__('team_comm.file_too_large','File too large (max 8 MB)')) ?>';
        waErr.classList.add('show'); this.value = ''; return;
    }
    if (file.type.startsWith('image/')) {
        const r = new FileReader();
        r.onload = e => waShowPreview(`<img src="${e.target.result}" class="wa-prev-thumb">`, file);
        r.readAsDataURL(file);
    } else {
        waShowPreview(`<i class="bi ${gcGetIcon(file.type)} wa-prev-file-ic"></i>`, file);
    }
});
function waShowPreview(thumb, file) {
    waPreview.classList.add('show');
    waPreview.innerHTML = `<div class="wa-prev-inner">${thumb}
        <div class="wa-prev-meta">
            <div class="wa-prev-name">${gcEsc(file.name)}</div>
            <div class="wa-prev-size">${gcFmt(file.size)}</div>
        </div>
        <button type="button" class="wa-prev-rm" onclick="gcClear()"><i class="bi bi-x-lg"></i></button>
    </div>`;
}
function waHidePreview() { waPreview.classList.remove('show'); waPreview.innerHTML = ''; }
function gcClear() { gcAttach.value = ''; waHidePreview(); }

/* ── Send ── */
function gcSend() {
    const content = gcInput.value.trim();
    const hasFile = gcAttach.files.length > 0;
    if (!content && !hasFile) return;
    gcSendBtn.disabled = true;
    waErr.classList.remove('show');
    const fd = new FormData();
    fd.append('_csrf', GC_CSRF);
    fd.append('meeting_id', GC_MEETING);
    fd.append('content', content);
    if (hasFile) fd.append('attachment', gcAttach.files[0]);
    fetch('/admin/team/group-chat/send', { method: 'POST', body: fd })
        .then(async r => { const t = await r.text(); try{return JSON.parse(t);}catch(e){return{success:true};} })
        .then(d => {
            if (d.success) {
                gcInput.value = ''; gcInput.style.height = 'auto'; gcClear();
                const empty = document.getElementById('waEmptyState');
                if (empty) empty.remove();
                if (d.message && d.message.id) {
                    waAppend(d.message, true);
                    gcLastId = parseInt(d.message.id) || gcLastId;
                    gcScroll(true);
                } else gcPoll();
            } else {
                waErr.textContent = '<?= addslashes(__('team_comm.send_failed','Send failed')) ?>';
                waErr.classList.add('show');
            }
        })
        .catch(() => { waErr.textContent = '<?= addslashes(__('team_comm.send_failed','Send failed')) ?>'; waErr.classList.add('show'); })
        .finally(() => { gcSendBtn.disabled = false; gcInput.focus(); });
}
gcSendBtn.addEventListener('click', gcSend);
gcInput.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); gcSend(); } });

/* ── Append message ── */
function waAppend(msg, isMine) {
    const wrap = document.createElement('div');
    wrap.className = `wa-row wa-new-group ${isMine ? 'is-mine wa-mine' : 'wa-other'}`;
    wrap.dataset.id = msg.id;
    const time   = (msg.created_at || '').slice(11, 16);
    const pinned = msg.is_pinned ? `<div class="wa-pin-flag"><i class="bi bi-pin-angle-fill"></i></div>` : '';
    const sname  = !isMine ? `<div class="wa-sender">${gcEsc(msg.sender_name || '')}</div>` : '';
    const text   = (msg.content && msg.content.trim()) ? `<div class="wa-text">${gcEsc(msg.content).replace(/\n/g,'<br>')}</div>` : '';
    const attach = waAttachHtml(msg, isMine);
    const av     = msg.sender_avatar || '/admin/assets/adminlte-assets/img/avatar.png';
    const avHtml = !isMine ? `<div class="wa-av-col"><img src="${gcEsc(av)}" alt=""></div>` : '';

    wrap.innerHTML = `${avHtml}
        <div class="wa-bbl-wrap">
            ${sname}
            <div class="wa-bbl">
                ${pinned}${text}${attach}
                <div class="wa-meta-row">
                    <button type="button" class="wa-pin-btn btn-pin-gc" data-id="${msg.id}"><i class="bi bi-pin-angle"></i></button>
                    <span class="wa-time">${time}</span>
                </div>
            </div>
        </div>`;
    waMessages.appendChild(wrap);
}
function waAttachHtml(msg, isMine) {
    if (!msg.attachment_path) return '';
    const t=msg.attachment_type||'', n=gcEsc(msg.attachment_name||'file'),
          p=gcEsc(msg.attachment_path), s=gcFmt(parseInt(msg.attachment_size||0));
    if (t.startsWith('image/'))
        return `<a href="${p}" target="_blank" rel="noopener" class="gc-img-link"><img src="${p}" alt="${n}" loading="lazy" class="gc-attach-img"></a>`;
    return `<div class="gc-attach-doc">
        <i class="bi ${gcGetIcon(t)} fs-3 flex-shrink-0"></i>
        <div class="gc-doc-info"><div class="gc-doc-name">${n}</div><div class="gc-doc-size">${s}</div></div>
        <a href="${p}" download class="gc-doc-dl"><i class="bi bi-download"></i></a>
    </div>`;
}

/* ── Poll ── */
function gcPoll() {
    fetch(`/admin/team/group-chat/poll/${GC_MEETING}?last_id=${gcLastId}`)
        .then(async r => { const t=await r.text(); try{return JSON.parse(t);}catch(e){return{success:true,messages:[]};} })
        .then(d => {
            if (d.success && d.messages && d.messages.length > 0) {
                const empty = document.getElementById('waEmptyState');
                if (empty) empty.remove();
                d.messages.forEach(m => {
                    if (!document.querySelector(`.wa-row[data-id="${m.id}"]`)) {
                        waAppend(m, parseInt(m.sender_id) === GC_MY_ID);
                        gcLastId = parseInt(m.id);
                    }
                });
                gcScroll(true);
            }
        }).catch(()=>{});
}
setInterval(gcPoll, 2000);

/* ── Emoji ── */
document.getElementById('gcEmojiBtn').addEventListener('click', function () {
    const tray = document.getElementById('waEmojiTray');
    const open = tray.classList.toggle('open');
    this.classList.toggle('active', open);
});
document.getElementById('waEmojiTray').addEventListener('click', function (e) {
    const btn = e.target.closest('[data-emoji]');
    if (!btn) return;
    gcInput.value += btn.getAttribute('data-emoji');
    gcInput.dispatchEvent(new Event('input'));
    gcInput.focus();
});

/* ── Pin ── */
document.addEventListener('click', function (e) {
    const btn = e.target.closest('.btn-pin-gc');
    if (!btn) return;
    fetch(`/admin/team/group-chat/pin/${btn.dataset.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `_csrf=${encodeURIComponent(GC_CSRF)}`
    }).catch(()=>{});
});

/* ── Mobile panel ── */
function openPanel()  { document.getElementById('waPanel').classList.add('open');    document.getElementById('waBackdrop').classList.add('show'); }
function closePanel() { document.getElementById('waPanel').classList.remove('open'); document.getElementById('waBackdrop').classList.remove('show'); }
document.getElementById('waInfoBtn')?.addEventListener('click', openPanel);
document.getElementById('waPanelClose')?.addEventListener('click', closePanel);
document.getElementById('waBackdrop')?.addEventListener('click', closePanel);

/* ── Helpers ── */
function gcEsc(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function gcFmt(b) { if(b>=1048576)return(b/1048576).toFixed(1)+' MB'; if(b>=1024)return(b/1024).toFixed(1)+' KB'; return b+' B'; }
function gcGetIcon(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';
}
function renderStatusHtml(msg, isMine) { return ''; }
</script>

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