<?php
/** @var array  $meeting         */
/** @var array  $groupMsgs       */
/** @var int    $lastGroupId     */
/** @var string $csrfToken       */
/** @var int    $currentAdminId  */
/** @var bool   $isManager       */
/** @var string $myRsvp          */
/** @var array  $themeSettings   */
/** @var bool   $videoEnabled    */
/** @var string $videoProvider   */

use Core\System\Language;

$dir  = Language::direction();
$lang = Language::code();

/* ── Theme ─────────────────────────────────────── */
$adminTheme = $themeSettings['admin_theme'] ?? [];
$colors     = $adminTheme['colors'] ?? [];
$fonts      = $adminTheme['fonts']  ?? [];

$c = [
    'primary'           => $colors['primary']           ?? '#0d6efd',
    'success'           => $colors['success']           ?? '#198754',
    'danger'            => $colors['danger']            ?? '#dc3545',
    'warning'           => $colors['warning']           ?? '#ffc107',
    'info'              => $colors['info']              ?? '#0dcaf0',
    'secondary'         => $colors['secondary']         ?? '#6c757d',
    'body_bg'           => $colors['body_bg']           ?? '#f0f2f5',
    'body_text'         => $colors['body_text']         ?? '#111827',
    'card_bg'           => $colors['card_bg']           ?? '#ffffff',
    'border'            => $colors['border']            ?? '#e9edef',
    'header_bg'         => $colors['header_bg']         ?? '#ffffff',
    'sidebar_bg'        => $colors['sidebar_bg']        ?? '#202c33',
    'sidebar_text'      => $colors['sidebar_text']      ?? '#d1d7db',
    'sidebar_active_bg' => $colors['sidebar_active_bg'] ?? '#2a3942',
];

/* Font resolution — identical to header.php logic */
$fontMap = [
    'ar_cairo'     => ["'Cairo', sans-serif",            '/public/assets/fonts/cairo/cairo.css'],
    'ar_tajawal'   => ["'Tajawal', sans-serif",          '/public/assets/fonts/tajawal/tajawal.css'],
    'ar_noto_kufi' => ["'Noto Kufi Arabic', sans-serif", '/public/assets/fonts/noto-kufi-arabic/noto-kufi-arabic.css'],
    'en_poppins'   => ["'Poppins', sans-serif",          '/public/assets/fonts/poppins/poppins.css'],
    'en_roboto'    => ["'Roboto', sans-serif",           '/public/assets/fonts/roboto/roboto.css'],
];
$bodyKey    = $fonts['body']    ?? 'ar_cairo';
$headKey    = $fonts['heading'] ?? 'ar_tajawal';
$bodyFont   = $fontMap[$bodyKey][0]  ?? "'Cairo', sans-serif";
$headFont   = $fontMap[$headKey][0]  ?? "'Tajawal', sans-serif";
$fontImports = [];
foreach ([$bodyKey, $headKey] as $_k) {
    if (!empty($fontMap[$_k][1])) $fontImports[$_k] = $fontMap[$_k][1];
}

/* ── Derived data ───────────────────────────────── */
$attendees     = $meeting['attendees'] ?? [];
$acceptedCount = 0;
foreach ($attendees as $a) { if (($a['rsvp'] ?? '') === 'accepted') $acceptedCount++; }
$meetingEnded      = (($meeting['status'] ?? 'upcoming') !== 'upcoming');
$composerEnabled   = !$meetingEnded && ($isManager || $myRsvp === 'accepted');
$msgCount          = count($groupMsgs);

/* ── Helpers ────────────────────────────────────── */
function mr_avatar(?string $p): string {
    return !empty($p) ? htmlspecialchars($p, ENT_QUOTES) : '/admin/assets/adminlte-assets/img/avatar.png';
}
function mr_size(int $b): string {
    if ($b >= 1048576) return round($b/1048576,1).' MB';
    if ($b >= 1024)    return round($b/1024,1).' KB';
    return $b.' B';
}

function mr_fileicon(string $type): string {
    if (str_contains($type,'pdf'))                                         return 'bi-file-pdf-fill text-danger';
    if (str_contains($type,'word') || str_contains($type,'document'))      return 'bi-file-word-fill text-primary';
    if (str_contains($type,'excel') || str_contains($type,'sheet'))        return 'bi-file-excel-fill text-success';
    if (str_contains($type,'zip')  || str_contains($type,'compressed'))    return 'bi-file-zip-fill text-warning';
    return 'bi-file-earmark-fill text-secondary';
}

function mr_render_attach(array $msg, bool $isMine): string {
    if (empty($msg['attachment_path'])) return '';
    $type = (string)($msg['attachment_type'] ?? '');
    $kind = (string)($msg['attachment_kind'] ?? '');
    $path = htmlspecialchars($msg['attachment_path'], ENT_QUOTES);
    $name = htmlspecialchars($msg['attachment_name'] ?? 'file', ENT_QUOTES);
    $size = mr_size((int)($msg['attachment_size'] ?? 0));
    if ($kind === 'image' || str_starts_with($type, 'image/')) {
        return '<a href="'.$path.'" target="_blank" rel="noopener" class="mr-img-link">
            <img src="'.$path.'" alt="'.$name.'" class="mr-img" loading="lazy">
        </a>';
    }
    $icon = mr_fileicon($type);
    return '<div class="mr-doc-card">
        <i class="bi '.$icon.' mr-doc-icon"></i>
        <div class="mr-doc-info">
            <div class="mr-doc-name">'.$name.'</div>
            <div class="mr-doc-size">'.$size.'</div>
        </div>
        <a href="'.$path.'" download class="mr-doc-dl"><i class="bi bi-download"></i></a>
    </div>';
}

function mr_bubble(array $msg, int $myId): string {
    $isMine  = ((int)$msg['sender_id'] === $myId);
    $pinned  = !empty($msg['is_pinned']);
    $time    = date('H:i', strtotime($msg['created_at']));
    $content = (string)($msg['content'] ?? '');
    $attach  = mr_render_attach($msg, $isMine);
    ob_start();
    ?>
    <div class="mr-row <?= $isMine ? 'mr-mine' : 'mr-other' ?>" data-id="<?= (int)$msg['id'] ?>">
        <?php if (!$isMine): ?>
        <img src="<?= mr_avatar($msg['sender_avatar'] ?? null) ?>" class="mr-av" alt="">
        <?php endif; ?>
        <div class="mr-bbl-wrap">
            <?php if (!$isMine): ?>
            <div class="mr-sender-name"><?= htmlspecialchars($msg['sender_name'] ?? '', ENT_QUOTES) ?></div>
            <?php endif; ?>
            <div class="mr-bbl<?= $pinned ? ' mr-bbl-pinned' : '' ?>">
                <?php if ($pinned): ?>
                <div class="mr-pin-tag"><i class="bi bi-pin-angle-fill"></i> <?= __('meeting_room.pinned','Pinned') ?></div>
                <?php endif; ?>
                <?php if ($content !== ''): ?>
                <div class="mr-text"><?= nl2br(htmlspecialchars($content, ENT_QUOTES)) ?></div>
                <?php endif; ?>
                <?= $attach ?>
                <div class="mr-foot">
                    <button type="button" class="mr-pin-btn btn-pin" data-id="<?= (int)$msg['id'] ?>"
                            title="<?= htmlspecialchars(__('team_comm.pin_message','Pin'), ENT_QUOTES) ?>">
                        <i class="bi <?= $pinned ? 'bi-pin-angle-fill' : 'bi-pin-angle' ?>"></i>
                    </button>
                    <span class="mr-time"><?= $time ?></span>
                </div>
            </div>
        </div>
    </div>
    <?php return ob_get_clean();
}
?>
<!doctype html>
<html lang="<?= htmlspecialchars($lang, ENT_QUOTES) ?>" dir="<?= htmlspecialchars($dir, ENT_QUOTES) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= htmlspecialchars($meeting['title'] ?? __('sidebar.team_meetings','Meeting'), ENT_QUOTES) ?></title>

<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">

<!-- Custom Fonts -->
<?php foreach ($fontImports as $fi): ?>
<link rel="stylesheet" href="<?= htmlspecialchars($fi, ENT_QUOTES) ?>">
<?php endforeach; ?>

<style>
/* ═══════════════════════════════════════════════════════════
   CSS VARIABLES  — all sourced from admin theme settings
   ═══════════════════════════════════════════════════════════ */
:root {
    --p:          <?= $c['primary'] ?>;
    --s:          <?= $c['success'] ?>;
    --d:          <?= $c['danger'] ?>;
    --w:          <?= $c['warning'] ?>;
    --i:          <?= $c['info'] ?>;
    --sec:        <?= $c['secondary'] ?>;
    --bg:         <?= $c['body_bg'] ?>;
    --txt:        <?= $c['body_text'] ?>;
    --card:       <?= $c['card_bg'] ?>;
    --brd:        <?= $c['border'] ?>;
    --topbar:     <?= $c['header_bg'] ?>;
    --panel-bg:   <?= $c['sidebar_bg'] ?>;
    --panel-txt:  <?= $c['sidebar_text'] ?>;
    --panel-row:  <?= $c['sidebar_active_bg'] ?>;
    --mine-bbl:   <?= $c['primary'] ?>;
    --other-bbl:  #fff;
    --chat-bg:    #efeae2;
    --font-body:  <?= $bodyFont ?>;
    --font-head:  <?= $headFont ?>;
    --r:          8px;
    --shadow-xs:  0 1px 2px rgba(0,0,0,.09);
    --shadow-sm:  0 2px 8px rgba(0,0,0,.12);
}

/* ═══════════════════════════════════════════════════════════
   RESET / BASE
   ═══════════════════════════════════════════════════════════ */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
    height: 100%;
    min-height: 100dvh;
    overflow: hidden;
    font-family: var(--font-body) !important;
    font-size: 14px;
    color: var(--txt);
    background: var(--bg);
    -webkit-font-smoothing: antialiased;
}
*, button, input, textarea, select, label, .badge, .btn, span, a, div {
    font-family: var(--font-body) !important;
}
h1,h2,h3,h4,h5,h6 { font-family: var(--font-head) !important; }
a { text-decoration: none; color: var(--p); }
* { scrollbar-width: thin; scrollbar-color: rgba(0,0,0,.15) transparent; }
*::-webkit-scrollbar { width: 5px; height: 5px; }
*::-webkit-scrollbar-thumb { background: rgba(0,0,0,.15); border-radius: 4px; }

/* ═══════════════════════════════════════════════════════════
   APP LAYOUT — full screen, 2 columns
   ═══════════════════════════════════════════════════════════ */
#mrApp {
    display: flex;
    height: 100vh;
    height: 100dvh;
    min-height: 100svh;
    overflow: hidden;
    background: var(--bg);
}

/* ═══════════════════════════════════════════════════════════
   LEFT PANEL  (WhatsApp Web sidebar feel with theme sidebar colors)
   ═══════════════════════════════════════════════════════════ */
#mrPanel {
    width: 300px;
    flex-shrink: 0;
    background: var(--panel-bg);
    color: var(--panel-txt);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    border-inline-end: 1px solid rgba(255,255,255,.06);
}

/* Panel header */
.mp-header {
    padding: 14px 16px;
    background: rgba(0,0,0,.2);
    display: flex;
    align-items: center;
    gap: 10px;
    border-bottom: 1px solid rgba(255,255,255,.07);
    flex-shrink: 0;
}
.mp-back {
    width: 34px; height: 34px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    color: var(--panel-txt); text-decoration: none; font-size: 17px;
    background: rgba(255,255,255,.07);
    transition: background .15s;
    flex-shrink: 0;
}
.mp-back:hover { background: rgba(255,255,255,.15); color: #fff; }
.mp-av {
    width: 38px; height: 38px; border-radius: 50%; overflow: hidden; flex-shrink: 0;
    background: rgba(var(--p),.25);
    display: flex; align-items: center; justify-content: center;
    font-size: 17px; color: var(--p);
}
.mp-titles { flex: 1; min-width: 0; }
.mp-title {
    font-size: 14px; font-weight: 700; color: #fff; line-height: 1.3;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.mp-sub { font-size: 11.5px; color: rgba(255,255,255,.55); line-height: 1.3; }

/* Stats row */
.mp-stats {
    display: grid; grid-template-columns: repeat(4, 1fr);
    gap: 1px; background: rgba(255,255,255,.05);
    border-bottom: 1px solid rgba(255,255,255,.07);
    flex-shrink: 0;
}
.mp-stat {
    padding: 10px 6px;
    text-align: center;
    background: rgba(0,0,0,.12);
}
.mp-stat-val {
    font-size: 1.1rem; font-weight: 800; color: #fff; line-height: 1.1;
    display: block;
}
.mp-stat-lbl { font-size: 10px; color: rgba(255,255,255,.5); }

/* Panel scroll area */
.mp-scroll { flex: 1; overflow-y: auto; }

/* Section label */
.mp-section {
    padding: 10px 16px 5px;
    font-size: 10.5px; font-weight: 700; text-transform: uppercase;
    letter-spacing: .08em; color: rgba(255,255,255,.38);
    display: flex; align-items: center; gap: 6px;
}

/* Meeting info card */
.mp-info-card {
    margin: 8px 10px 4px;
    background: rgba(255,255,255,.06);
    border: 1px solid rgba(255,255,255,.09);
    border-radius: 12px;
    padding: 11px 13px;
}
.mp-info-row {
    display: flex; align-items: flex-start; gap: 8px;
    font-size: 12px; color: rgba(255,255,255,.7);
    line-height: 1.45; margin-bottom: 5px;
}
.mp-info-row:last-child { margin: 0; }
.mp-info-row > i { font-size: 12px; color: var(--p); flex-shrink: 0; margin-top: 1px; }
.mp-desc {
    margin-top: 6px; padding: 6px 9px; border-radius: 8px;
    background: rgba(255,255,255,.05); font-size: 11.5px;
    color: rgba(255,255,255,.6); line-height: 1.6; white-space: pre-wrap;
}

/* Meeting status badge */
.mp-status-badge {
    display: inline-flex; align-items: center; gap: 5px;
    font-size: 10.5px; font-weight: 700; padding: 2px 9px;
    border-radius: 20px;
}
.mp-status-upcoming  { background: rgba(13,110,253,.25); color: #93c5fd; }
.mp-status-completed { background: rgba(25,135,84,.25);  color: #86efac; }
.mp-status-cancelled { background: rgba(108,117,125,.25); color: #cbd5e1; }

/* RSVP choices (for current user) */
.mp-rsvp-row {
    display: flex; align-items: center; gap: 7px; flex-wrap: wrap;
    padding: 6px 10px 10px;
}
.mp-rsvp-lbl { font-size: 10.5px; color: rgba(255,255,255,.45); width: 100%; }
.mp-rsvp-btn {
    flex: 1; min-width: 70px;
    display: flex; align-items: center; justify-content: center; gap: 4px;
    padding: 6px 4px; border-radius: 9px; border: 1.5px solid transparent;
    font-size: 11px; font-weight: 700; cursor: pointer;
    transition: all .18s; background: rgba(255,255,255,.06); color: rgba(255,255,255,.7);
}
.mp-rsvp-btn:hover { background: rgba(255,255,255,.12); color: #fff; }
.mp-rsvp-btn[data-rsvp="accepted"]  { border-color: rgba(25,135,84,.4); }
.mp-rsvp-btn[data-rsvp="declined"]  { border-color: rgba(220,53,69,.4); }
.mp-rsvp-btn[data-rsvp="pending"]   { border-color: rgba(255,193,7,.4); }
.mp-rsvp-btn.active[data-rsvp="accepted"] { background: var(--s); border-color: var(--s); color: #fff; box-shadow: 0 3px 10px rgba(25,135,84,.35); }
.mp-rsvp-btn.active[data-rsvp="declined"] { background: var(--d); border-color: var(--d); color: #fff; box-shadow: 0 3px 10px rgba(220,53,69,.35); }
.mp-rsvp-btn.active[data-rsvp="pending"]  { background: var(--w); border-color: var(--w); color: #000; box-shadow: 0 3px 10px rgba(255,193,7,.3); }

/* Video meeting button */
.mp-video-btn {
    display: flex; align-items: center; justify-content: center; gap: 7px;
    width: calc(100% - 20px); margin: 0 10px 8px;
    padding: 10px; border-radius: 11px; border: none; cursor: pointer;
    font-size: 12.5px; font-weight: 700; color: #fff;
    background: linear-gradient(135deg, #1a56db 0%, #0d47a1 100%);
    box-shadow: 0 3px 12px rgba(26,86,219,.4);
    transition: filter .15s, transform .12s;
    text-decoration: none;
}
.mp-video-btn:hover { filter: brightness(1.1); transform: translateY(-1px); color: #fff; }
.mp-video-btn:active { transform: scale(.97); }
.mp-video-btn.loading { opacity: .7; pointer-events: none; }

/* Video modal */
#vmModal .modal-content {
    border: none; border-radius: 16px; overflow: hidden;
    box-shadow: 0 20px 60px rgba(0,0,0,.3);
}
#vmModal .modal-header {
    background: linear-gradient(135deg, #1a56db, #0d47a1);
    color: #fff; border: none; padding: 14px 18px;
}
#vmModal .modal-header .btn-close { filter: invert(1); }
#vmIframe {
    width: 100%; border: none; display: block;
    height: calc(100vh - 200px); min-height: 480px;
}
.vm-provider-badge {
    display: inline-flex; align-items: center; gap: 4px;
    font-size: .7rem; font-weight: 700; padding: 2px 9px; border-radius: 20px;
    background: rgba(255,255,255,.2); color: rgba(255,255,255,.9);
}

/* End meeting button */
.mp-complete-btn {
    display: flex; align-items: center; justify-content: center; gap: 6px;
    width: calc(100% - 20px); margin: 0 10px 12px;
    padding: 9px; border-radius: 11px; border: none; cursor: pointer;
    font-size: 12.5px; font-weight: 700; color: #fff;
    background: var(--d); box-shadow: 0 3px 10px rgba(220,53,69,.3);
    transition: filter .15s, transform .12s;
}
.mp-complete-btn:hover { filter: brightness(1.1); transform: translateY(-1px); }

/* Attendees */
.mp-att-item {
    display: flex; align-items: center; gap: 10px;
    padding: 8px 16px;
    border-bottom: 1px solid rgba(255,255,255,.04);
    transition: background .12s;
}
.mp-att-item:hover { background: rgba(255,255,255,.04); }
.mp-att-av {
    width: 36px; height: 36px; border-radius: 50%; object-fit: cover; flex-shrink: 0;
    border: 2px solid rgba(255,255,255,.14);
}
.mp-att-info { flex: 1; min-width: 0; }
.mp-att-name {
    font-size: 13px; font-weight: 600; color: #fff; line-height: 1.3;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    display: flex; align-items: center; gap: 5px;
}
.mp-att-you {
    font-size: 9px; background: rgba(13,110,253,.3); color: #93c5fd;
    padding: 1px 5px; border-radius: 4px; font-weight: 700;
}
.mp-att-role { font-size: 11px; color: rgba(255,255,255,.45); }
.mp-rsvp-chip {
    font-size: 10px; font-weight: 700; padding: 2px 8px; border-radius: 12px;
    display: inline-flex; align-items: center; gap: 3px; flex-shrink: 0;
    white-space: nowrap;
}
.mp-rsvp-chip.accepted { background: rgba(25,135,84,.25); color: #86efac; }
.mp-rsvp-chip.declined { background: rgba(220,53,69,.25);  color: #fca5a5; }
.mp-rsvp-chip.pending  { background: rgba(255,193,7,.2);   color: #fde68a; }

/* ═══════════════════════════════════════════════════════════
   RIGHT — CHAT COLUMN
   ═══════════════════════════════════════════════════════════ */
#mrChat {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background: var(--chat-bg);
    position: relative;
}

/* Wallpaper */
#mrChat::before {
    content: '';
    position: absolute; inset: 0; z-index: 0; pointer-events: none;
    background-color: var(--chat-bg);
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Crect width='80' height='80' fill='%23e5ddd5'/%3E%3Ccircle cx='40' cy='40' r='30' fill='none' stroke='%23d4ccc4' stroke-width='.4'/%3E%3Ccircle cx='40' cy='40' r='15' fill='none' stroke='%23d4ccc4' stroke-width='.3'/%3E%3C/svg%3E");
    background-size: 80px 80px; opacity: .45;
}

/* ── Messages scroll area ── */
#mrMessages {
    flex: 1;
    overflow-y: auto;
    padding: 14px 6%;
    display: flex;
    flex-direction: column;
    gap: 2px;
    position: relative;
    z-index: 1;
}

/* ── Message row ── */
.mr-row {
    display: flex;
    align-items: flex-end;
    gap: 6px;
}
.mr-row + .mr-row { margin-top: 1px; }
.mr-row.mr-mine  { flex-direction: row-reverse; }
[dir=rtl] .mr-row       { flex-direction: row-reverse; }
[dir=rtl] .mr-row.mr-mine { flex-direction: row; }

/* Avatar */
.mr-av {
    width: 28px; height: 28px; border-radius: 50%; object-fit: cover;
    flex-shrink: 0; align-self: flex-end;
    border: 1.5px solid rgba(255,255,255,.85);
    box-shadow: var(--shadow-xs);
}

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

/* Sender name */
.mr-sender-name {
    font-size: 12px; font-weight: 700;
    color: var(--p); padding: 0 12px; margin-bottom: 2px;
}

/* ── WhatsApp bubble ── */
.mr-bbl {
    padding: 6px 10px 4px;
    border-radius: 7.5px;
    word-break: break-word;
    box-shadow: 0 1px 2px rgba(0,0,0,.12);
    position: relative;
}

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

/* Tail for other */
.mr-other .mr-bbl::before {
    content: '';
    position: absolute;
    bottom: 0; inset-inline-start: -7px;
    border: 7px solid transparent;
    border-bottom-color: var(--other-bbl);
    border-inline-start-color: transparent;
    border-top: 0;
}

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

/* Tail for mine */
.mr-mine .mr-bbl::before {
    content: '';
    position: absolute;
    bottom: 0; inset-inline-end: -7px;
    border: 7px solid transparent;
    border-bottom-color: var(--mine-bbl);
    border-inline-end-color: transparent;
    border-top: 0;
}

/* Pinned */
.mr-bbl-pinned { outline: 1.5px solid rgba(255,193,7,.5); outline-offset: 1px; }
.mr-pin-tag {
    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);
}

.mr-text { font-size: 13.5px; line-height: 1.6; white-space: pre-wrap; }

/* Bubble footer */
.mr-foot {
    display: flex; align-items: center; justify-content: flex-end;
    gap: 5px; margin-top: 2px;
}
.mr-time { font-size: 11px; color: rgba(0,0,0,.4); }
.mr-mine .mr-time { color: rgba(255,255,255,.6); }
.mr-pin-btn {
    background: none; border: none; cursor: pointer; padding: 0;
    font-size: 12px; color: rgba(0,0,0,.3); opacity: 0;
    transition: opacity .15s; display: flex; align-items: center;
}
.mr-bbl:hover .mr-pin-btn { opacity: 1; }
.mr-mine .mr-pin-btn { color: rgba(255,255,255,.55); }

/* ── Image ── */
.mr-img-link { display: block; margin-top: 3px; }
.mr-img {
    max-width: 240px; max-height: 240px; width: 100%;
    object-fit: cover; border-radius: 8px; display: block;
    box-shadow: var(--shadow-sm); cursor: pointer;
    transition: transform .15s;
}
.mr-img:hover { transform: scale(1.02); }

/* ── Doc card ── */
.mr-doc-card {
    display: flex; align-items: center; gap: 8px;
    margin-top: 4px; padding: 8px 10px;
    background: rgba(0,0,0,.1); border-radius: 9px;
    min-width: 180px; max-width: 240px;
}
.mr-mine .mr-doc-card { background: rgba(0,0,0,.2); }
.mr-doc-icon { font-size: 1.55rem; flex-shrink: 0; }
.mr-doc-info { flex: 1; min-width: 0; }
.mr-doc-name { font-size: 12.5px; font-weight: 600; word-break: break-all; }
.mr-doc-size { font-size: 10.5px; opacity: .7; }
.mr-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,.18); color: inherit;
    transition: background .15s;
}
.mr-doc-dl:hover { background: rgba(255,255,255,.35); }

/* ── Empty state ── */
.mr-empty-state {
    display: flex; align-items: center; justify-content: center;
    height: 100%; pointer-events: none;
}
.mr-empty-badge {
    background: rgba(225,245,254,.92); backdrop-filter: blur(4px);
    padding: 10px 22px; border-radius: 16px; text-align: center;
    font-size: 12.5px; color: #667781; box-shadow: var(--shadow-xs);
    max-width: 260px;
}

/* ═══════════════════════════════════════════════════════════
   EMOJI TRAY
   ═══════════════════════════════════════════════════════════ */
#mrEmojiTray {
    position: relative; z-index: 2;
    background: var(--card); border-top: 1px solid var(--brd);
    padding: 7px 14px; display: none; flex-wrap: wrap; gap: 3px;
    max-height: 78px; overflow-y: auto;
}
#mrEmojiTray.open { display: flex; }
.mr-emoji-btn {
    background: none; border: 1px solid var(--brd); border-radius: 7px;
    padding: 2px 5px; cursor: pointer; font-size: 18px; line-height: 1.3;
    transition: background .1s, transform .1s;
}
.mr-emoji-btn:hover { background: rgba(0,0,0,.05); transform: scale(1.2); }

/* ═══════════════════════════════════════════════════════════
   ATTACHMENT PREVIEW BAR
   ═══════════════════════════════════════════════════════════ */
#mrPreviewBar {
    position: relative; z-index: 2;
    background: var(--card); border-top: 1px solid var(--brd);
    padding: 7px 14px; display: none;
}
#mrPreviewBar.show { display: block; }
.mr-prev-inner {
    display: flex; align-items: center; gap: 10px;
    background: rgba(13,110,253,.07);
    border: 1px solid rgba(13,110,253,.18);
    border-radius: 11px; padding: 8px 12px;
}
.mr-prev-thumb { width: 42px; height: 42px; border-radius: 7px; object-fit: cover; flex-shrink: 0; }
.mr-prev-file-ic { font-size: 1.7rem; flex-shrink: 0; }
.mr-prev-meta { flex: 1; min-width: 0; }
.mr-prev-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mr-prev-size { font-size: 11px; color: #888; }
.mr-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;
}
.mr-prev-rm:hover { background: rgba(220,53,69,.1); color: #dc3545; }

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

/* ═══════════════════════════════════════════════════════════
   MENTION POPOVER
   ═══════════════════════════════════════════════════════════ */
#mentionPopover {
    position: absolute; bottom: 70px; inset-inline-start: 14px;
    background: var(--card); border: 1px solid var(--brd);
    border-radius: 12px; box-shadow: var(--shadow-sm);
    z-index: 100; min-width: 200px; max-width: 280px;
    overflow: hidden; display: none;
}
#mentionPopover.open { display: block; }
.mr-mention-item {
    display: flex; align-items: center; gap: 9px;
    padding: 8px 12px; cursor: pointer;
    transition: background .12s;
    font-size: 13px;
}
.mr-mention-item:hover, .mr-mention-item.active { background: rgba(13,110,253,.07); }
.mr-mention-item img { width: 30px; height: 30px; border-radius: 50%; object-fit: cover; }
.mr-mention-item .mr-drop-hint { font-size: 11px; color: #888; }

/* ═══════════════════════════════════════════════════════════
   INPUT BAR  — exact WhatsApp Web feel
   ═══════════════════════════════════════════════════════════ */
#mrInputBar {
    position: relative; z-index: 2;
    background: #f0f2f5;
    border-top: 1px solid var(--brd);
    padding: 8px 14px;
    display: flex; align-items: flex-end; gap: 8px;
    flex-wrap: nowrap;
    flex-shrink: 0;
}
.mr-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;
}
.mr-ib-btn:hover, .mr-ib-btn.active { color: var(--p); }
.mr-textarea-box {
    flex: 1; min-width: 0; background: #fff;
    border: 1px solid var(--brd);
    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;
}
.mr-textarea-box:focus-within {
    border-color: rgba(13,110,253,.4);
    box-shadow: 0 0 0 3px rgba(13,110,253,.09);
}
#messageInput {
    flex: 1; width: 100%; min-width: 0; 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(--txt);
}
#messageInput::placeholder { color: #aebac1; }
#messageInput:disabled { background: none; color: #aaa; cursor: not-allowed; }
#mrSendBtn {
    width: 42px; height: 42px; border-radius: 50%; flex-shrink: 0;
    background: var(--p); border: none; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    color: #fff; font-size: 16px; align-self: flex-end;
    box-shadow: 0 2px 8px rgba(13,110,253,.4);
    transition: filter .15s, transform .12s;
}
#mrSendBtn:hover  { filter: brightness(1.1); transform: scale(1.07); }
#mrSendBtn:active { transform: scale(.9); }
#mrSendBtn:disabled { opacity: .5; cursor: not-allowed; transform: none; box-shadow: none; }
[dir=rtl] #mrSendBtn i { transform: scaleX(-1); }

/* ═══════════════════════════════════════════════════════════
   MOBILE  — panel slides in
   ═══════════════════════════════════════════════════════════ */
@media (max-width: 991.98px) {
    html, body { min-height: 100dvh; }
    #mrApp { height: 100dvh; min-height: 100svh; }
    #mrPanel {
        position: fixed; inset: 0 auto 0 0;
        z-index: 1060; width: min(290px, 86vw); max-width: 86vw;
        transform: translateX(-100%);
        box-shadow: 4px 0 24px rgba(0,0,0,.25);
        transition: transform .26s ease;
    }
    [dir=rtl] #mrPanel {
        inset: 0 0 0 auto;
        transform: translateX(100%);
    }
    #mrPanel.open { transform: translateX(0); }
    #mrBackdrop {
        display: none; position: fixed; inset: 0;
        background: rgba(0,0,0,.4); z-index: 1059;
    }
    #mrBackdrop.show { display: block; }
    .mp-mobile-only { display: flex !important; }
    .mp-stats { grid-template-columns: repeat(2, 1fr); }
    .mp-stat { padding: 10px 8px; }
    #mrMessages { padding: 12px 14px; }
    .mr-bbl-wrap { max-width: min(80%, 420px); }
    .mr-img { max-width: min(100%, 320px); }
    #mrInputBar {
        padding: 8px 10px calc(8px + env(safe-area-inset-bottom, 0px));
        gap: 6px;
    }
    .mr-ib-btn { width: 38px; height: 38px; font-size: 18px; }
    .mr-textarea-box { padding: 8px 12px; min-height: 40px; }
    #mrSendBtn { width: 40px; height: 40px; }
    .mp-video-btn, .mp-complete-btn {
        width: calc(100% - 16px); margin-inline: 8px;
        padding: 11px 10px; flex-wrap: wrap;
    }
    .mp-att-item { padding: 8px 12px; }
}
@media (max-width: 575.98px) {
    #mrMessages { padding: 10px 10px; }
    .mr-row { gap: 4px; }
    .mr-av { width: 24px; height: 24px; }
    .mr-bbl-wrap { max-width: calc(100% - 34px); }
    .mr-bbl { padding: 6px 9px 4px; }
    .mr-sender-name { padding-inline: 8px; font-size: 11px; }
    .mr-img { max-width: min(100%, 250px); border-radius: 10px; }
    .mr-doc-card { min-width: 0; width: 100%; }
    .mp-header { padding: 12px; gap: 8px; }
    .mp-title { font-size: 13px; }
    .mp-sub { font-size: 11px; }
    .mp-info-card { margin: 8px 8px 4px; padding: 10px 11px; }
    .mp-rsvp-row { padding: 6px 8px 10px; }
    .mp-rsvp-btn { flex: 1 1 calc(50% - 6px); min-width: calc(50% - 6px); }
    .mp-att-item { align-items: flex-start; }
    .mp-att-name { white-space: normal; }
    .mp-rsvp-chip { margin-top: 2px; }
    #mrInputBar { padding-inline: 8px; }
}
@media (max-width: 420px) {
    .mp-stats { grid-template-columns: 1fr 1fr; }
    .mp-stat-val { font-size: 1rem; }
    .mr-bbl-wrap { max-width: calc(100% - 28px); }
    .mr-textarea-box { min-width: 0; }
    #messageInput { font-size: 13px; }
    .vm-provider-badge { width: 100%; justify-content: center; }
}
@media (min-width: 992px) {
    #mrBackdrop { display: none !important; }
    .mp-mobile-only { display: none !important; }
}
</style>
</head>
<body>
<div id="mrApp">

    <!-- ══════════════════════════════════════════
         LEFT PANEL
         ══════════════════════════════════════════ -->
    <div id="mrPanel">

        <!-- Header -->
        <div class="mp-header">
            <a href="/admin/team/meetings" class="mp-back" title="<?= htmlspecialchars(__('team_meeting.back','Back')) ?>">
                <i class="bi bi-arrow-<?= $dir === 'rtl' ? 'right' : 'left' ?>"></i>
            </a>
            <div class="mp-av"><i class="bi bi-people-fill"></i></div>
            <div class="mp-titles">
                <div class="mp-title"><?= htmlspecialchars($meeting['title'] ?? '') ?></div>
                <div class="mp-sub">
                    <?php
                    $status   = $meeting['status'] ?? 'upcoming';
                    $stClass  = ['upcoming'=>'mp-status-upcoming','completed'=>'mp-status-completed','cancelled'=>'mp-status-cancelled'][$status] ?? 'mp-status-cancelled';
                    ?>
                    <span class="mp-status-badge <?= $stClass ?>">
                        <i class="bi bi-circle-fill" style="font-size:7px"></i>
                        <?= __('team_meeting.status_'.$status, $status) ?>
                    </span>
                </div>
            </div>
            <!-- Mobile close -->
            <button class="mr-ib-btn mp-mobile-only" style="display:none;color:rgba(255,255,255,.6);font-size:16px" id="mrPanelClose">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>

        <!-- Stats -->
        <div class="mp-stats">
            <div class="mp-stat">
                <span class="mp-stat-val"><?= count($attendees) ?></span>
                <span class="mp-stat-lbl"><?= __('team_meeting.attendees','Attendees') ?></span>
            </div>
            <div class="mp-stat">
                <span class="mp-stat-val"><?= $acceptedCount ?></span>
                <span class="mp-stat-lbl"><?= __('team_meeting.accepted','Accepted') ?></span>
            </div>
            <div class="mp-stat">
                <span class="mp-stat-val" id="mrMsgCount"><?= $msgCount ?></span>
                <span class="mp-stat-lbl"><?= __('team_comm.messages','Messages') ?></span>
            </div>
            <div class="mp-stat">
                <span class="mp-stat-val"><?= (int)($meeting['duration_minutes'] ?? 0) ?></span>
                <span class="mp-stat-lbl"><?= __('team_comm.minutes','min') ?></span>
            </div>
        </div>

        <div class="mp-scroll">

            <!-- Meeting info -->
            <div class="mp-section"><i class="bi bi-info-circle-fill"></i><?= __('team_meeting.meeting_info','Info') ?></div>
            <div class="mp-info-card">
                <?php if (!empty($meeting['scheduled_at'])): ?>
                <div class="mp-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="mp-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="mp-info-row">
                    <i class="bi bi-geo-alt-fill"></i>
                    <span><?= htmlspecialchars($meeting['location']) ?></span>
                </div>
                <?php endif; ?>
                <div class="mp-info-row">
                    <i class="bi bi-tag-fill"></i>
                    <span><?= __('team_meeting.type_'.($meeting['meeting_type'] ?? 'other'), str_replace('_',' ', $meeting['meeting_type'] ?? 'other')) ?></span>
                </div>
                <?php if (!empty($meeting['description'])): ?>
                <div class="mp-desc"><?= nl2br(htmlspecialchars($meeting['description'])) ?></div>
                <?php endif; ?>
            </div>

            <!-- My RSVP -->
            <?php if (!$meetingEnded): ?>
            <div class="mp-section"><i class="bi bi-calendar-check-fill"></i><?= __('team_meeting.my_rsvp','My RSVP') ?></div>
            <div class="mp-rsvp-row">
                <span class="mp-rsvp-lbl"><?= __('team_meeting.your_response','Your response:') ?></span>
                <button type="button" class="mp-rsvp-btn choice <?= $myRsvp === 'accepted' ? 'active' : '' ?>" data-rsvp="accepted" id="rsvpAccept">
                    <i class="bi bi-calendar-check-fill"></i><?= __('team_meeting.rsvp_accepted','Accept') ?>
                </button>
                <button type="button" class="mp-rsvp-btn choice <?= $myRsvp === 'declined' ? 'active' : '' ?>" data-rsvp="declined" id="rsvpDecline">
                    <i class="bi bi-calendar-x-fill"></i><?= __('team_meeting.rsvp_declined','Decline') ?>
                </button>
                <button type="button" class="mp-rsvp-btn choice <?= ($myRsvp === 'pending' || !$myRsvp) ? 'active' : '' ?>" data-rsvp="pending" id="rsvpPending">
                    <i class="bi bi-hourglass-split"></i><?= __('team_meeting.rsvp_pending','Pending') ?>
                </button>
            </div>
            <?php endif; ?>

            <!-- Video Meeting button -->
            <?php
            $vmEnabled  = !empty($videoEnabled);
            $vmProvider = $videoProvider ?? '';
            $vmLabels   = ['jitsi' => 'Jitsi Meet', 'daily' => 'Daily.co', 'whereby' => 'Whereby'];
            $vmIcons    = ['jitsi' => 'bi-camera-video-fill', 'daily' => 'bi-camera-video-fill', 'whereby' => 'bi-people-fill'];
            ?>
            <?php if ($vmEnabled && !$meetingEnded): ?>
            <button type="button" class="mp-video-btn" id="btnVideoMeeting">
                <i class="bi <?= $vmIcons[$vmProvider] ?? 'bi-camera-video-fill' ?>"></i>
                <?= __('video_meeting.start_video','Start Video Meeting') ?>
                <span class="vm-provider-badge"><?= htmlspecialchars($vmLabels[$vmProvider] ?? $vmProvider) ?></span>
                <span class="spinner-border spinner-border-sm d-none" id="vmBtnSpinner" style="width:14px;height:14px"></span>
            </button>
            <?php elseif (!$vmEnabled): ?>
            <a href="/admin/integrations/video-meeting" class="mp-video-btn" style="opacity:.55;filter:grayscale(.6)">
                <i class="bi bi-camera-video-off"></i>
                <?= __('video_meeting.setup_video','Setup Video Meeting') ?>
            </a>
            <?php endif; ?>

            <!-- End meeting (manager) -->
            <?php if ($isManager && !$meetingEnded): ?>
            <button type="button" class="mp-complete-btn" id="btnCompleteMeeting">
                <i class="bi bi-check2-circle"></i>
                <?= __('team_meeting.complete','End Meeting') ?>
            </button>
            <?php endif; ?>

            <!-- Attendees -->
            <div class="mp-section">
                <i class="bi bi-people-fill"></i>
                <?= __('team_meeting.attendees','Attendees') ?>
            </div>

            <?php foreach ($attendees as $att):
                $rv = $att['rsvp'] ?? 'pending';
                $rvIcons = ['accepted'=>'bi-check2','declined'=>'bi-x-lg','pending'=>'bi-hourglass-split'];
            ?>
            <div class="mp-att-item">
                <img src="<?= mr_avatar($att['avatar'] ?? null) ?>" class="mp-att-av" alt="">
                <div class="mp-att-info">
                    <div class="mp-att-name">
                        <?= htmlspecialchars($att['username'] ?? '') ?>
                        <?php if ((int)($att['admin_id'] ?? 0) === $currentAdminId): ?>
                        <span class="mp-att-you"><?= __('team_comm.you','You') ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="mp-att-role"><?= __('team.role_'.($att['role'] ?? ''), $att['role'] ?? '') ?></div>
                </div>
                <span class="mp-rsvp-chip <?= $rv ?>">
                    <i class="bi <?= $rvIcons[$rv] ?? 'bi-hourglass-split' ?>"></i>
                    <?= __('team_meeting.rsvp_'.$rv, $rv) ?>
                </span>
            </div>
            <?php endforeach; ?>

        </div><!-- /.mp-scroll -->
    </div><!-- /#mrPanel -->

    <!-- Backdrop (mobile) -->
    <div id="mrBackdrop"></div>

    <!-- ══════════════════════════════════════════
         RIGHT — CHAT
         ══════════════════════════════════════════ -->
    <div id="mrChat">

        <!-- Messages -->
        <div id="mrMessages">
            <?php if (empty($groupMsgs)): ?>
            <div class="mr-empty-state" id="mrEmpty">
                <div class="mr-empty-badge">
                    <i class="bi bi-lock-fill me-1" style="font-size:11px"></i>
                    <?= __('meeting_room.no_messages','No messages yet — start the conversation!') ?>
                </div>
            </div>
            <?php else:
                foreach ($groupMsgs as $msg) {
                    echo mr_bubble($msg, $currentAdminId);
                }
            endif; ?>
        </div>

        <!-- Emoji tray -->
        <div id="mrEmojiTray">
            <?php foreach (['😀','😁','😂','🤣','😊','😍','😎','🤝','🙏','🔥','✅','🎯','📌','💬','🚀','👏','👍','👀','🤍','💙','💚','💛','🧠','📅'] as $e): ?>
            <button type="button" class="mr-emoji-btn" data-emoji="<?= htmlspecialchars($e, ENT_QUOTES) ?>"><?= $e ?></button>
            <?php endforeach; ?>
        </div>

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

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

        <!-- Mention popover -->
        <div id="mentionPopover"></div>

        <!-- Input bar -->
        <div id="mrInputBar">

            <!-- Mobile: open panel -->
            <button class="mr-ib-btn mp-mobile-only" style="display:none" id="mrPanelOpen">
                <i class="bi bi-layout-sidebar-inset-reverse"></i>
            </button>

            <!-- Attach file -->
            <label for="attachmentInput" class="mr-ib-btn" title="<?= htmlspecialchars(__('team_comm.attach_file','Attach')) ?>">
                <i class="bi bi-paperclip"></i>
            </label>
            <input type="file" id="attachmentInput" class="d-none" style="display:none !important;width:0 !important;height:0 !important;opacity:0 !important;position:absolute !important;pointer-events:none !important;"
                   accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx,.txt">

            <div class="mr-textarea-box">
                <!-- Emoji button inside textarea box -->
                <button class="mr-ib-btn" type="button" id="btnEmoji"
                        style="width:28px;height:28px;font-size:18px;align-self:flex-end"
                        title="Emoji">
                    <i class="bi bi-emoji-smile"></i>
                </button>
                <form id="mrForm" style="flex:1;display:flex;align-items:flex-end">
                    <textarea id="messageInput" rows="1"
                              placeholder="<?= htmlspecialchars(__('team_comm.type_message','Type a message')) ?>"
                              <?= !$composerEnabled ? 'disabled' : '' ?>
                              style="flex:1"></textarea>
                </form>
            </div>

            <button id="mrSendBtn" type="submit" form="mrForm" <?= !$composerEnabled ? 'disabled' : '' ?>>
                <i class="bi bi-send-fill"></i>
            </button>

        </div>

    </div><!-- /#mrChat -->
</div><!-- /#mrApp -->

<script>
/* ════════════════════════════════════════════
   ROOM CONFIG
   ════════════════════════════════════════════ */
const ROOM = {
    meetingId:       <?= (int)($meeting['id'] ?? 0) ?>,
    currentAdminId:  <?= (int)$currentAdminId ?>,
    lastId:          <?= (int)$lastGroupId ?>,
    csrf:            <?= json_encode($csrfToken, JSON_UNESCAPED_UNICODE) ?>,
    composerEnabled: <?= $composerEnabled ? 'true' : 'false' ?>,
    isManager:       <?= $isManager ? 'true' : 'false' ?>,
    messagesCount:   <?= $msgCount ?>,
    attendees:       <?= json_encode(array_map(function($a){ return [
        'id'       => (int)($a['admin_id'] ?? 0),
        'username' => (string)($a['username'] ?? ''),
        'avatar'   => (string)($a['avatar'] ?? ''),
        'role'     => (string)($a['role'] ?? ''),
        'rsvp'     => (string)($a['rsvp'] ?? 'pending'),
    ]; }, $attendees), JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE) ?>,
    t: {
        pin:             <?= json_encode(__('team_comm.pin_message','Pin message'), JSON_UNESCAPED_UNICODE) ?>,
        pinned:          <?= json_encode(__('meeting_room.pinned','Pinned'), JSON_UNESCAPED_UNICODE) ?>,
        sendFailed:      <?= json_encode(__('team_comm.send_failed','Send failed'), JSON_UNESCAPED_UNICODE) ?>,
        completeConfirm: <?= json_encode(__('team_meeting.confirm_complete','End this meeting now?'), JSON_UNESCAPED_UNICODE) ?>,
        image:           <?= json_encode(__('team_comm.image','Image'), JSON_UNESCAPED_UNICODE) ?>,
        document:        <?= json_encode(__('team_comm.document','Document'), JSON_UNESCAPED_UNICODE) ?>,
    }
};

/* ════════════════════════════════════════════
   DOM REFS
   ════════════════════════════════════════════ */
const mrMessages   = document.getElementById('mrMessages');
const messageInput = document.getElementById('messageInput');
const mrForm       = document.getElementById('mrForm');
const mrSendBtn    = document.getElementById('mrSendBtn');
const btnEmoji     = document.getElementById('btnEmoji');
const mrEmojiTray  = document.getElementById('mrEmojiTray');
const attachInput  = document.getElementById('attachmentInput');
const mrPreviewBar = document.getElementById('mrPreviewBar');
const mrErrEl      = document.getElementById('mrErr');
const mrMsgCount   = document.getElementById('mrMsgCount');
const mentionPop   = document.getElementById('mentionPopover');

/* ════════════════════════════════════════════
   HELPERS
   ════════════════════════════════════════════ */
function esc(v) { return String(v||'').replace(/[&<>"']/g,s=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[s])); }
function nl2br(v) { return esc(v).replace(/\n/g,'<br>'); }
function fmtSize(b) { if(b>=1048576)return(b/1048576).toFixed(1)+' MB'; if(b>=1024)return(b/1024).toFixed(1)+' KB'; return b+' B'; }
function fmtTime(v) { try{const d=new Date(v.replace(' ','T')+'Z');return d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});}catch(e){return'';} }
function av(p) { return p&&p.trim()?p:'/admin/assets/adminlte-assets/img/avatar.png'; }
function fileIcon(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';
}

/* ════════════════════════════════════════════
   SCROLL
   ════════════════════════════════════════════ */
function scrollBottom(smooth) {
    mrMessages.scrollTo({ top: mrMessages.scrollHeight, behavior: smooth ? 'smooth' : 'instant' });
}
scrollBottom(false);

/* ════════════════════════════════════════════
   TEXTAREA AUTO-RESIZE
   ════════════════════════════════════════════ */
messageInput.addEventListener('input', function() {
    this.style.height = 'auto';
    this.style.height = Math.min(this.scrollHeight, 110) + 'px';
});

/* ════════════════════════════════════════════
   RENDER ATTACHMENT HTML (JS)
   ════════════════════════════════════════════ */
function renderAttach(msg, isMine) {
    if (!msg.attachment_path) return '';
    const t = msg.attachment_type||'', k = msg.attachment_kind||'',
          p = esc(msg.attachment_path), n = esc(msg.attachment_name||'file'),
          s = fmtSize(parseInt(msg.attachment_size||0,10));
    if (k==='image' || t.startsWith('image/'))
        return `<a href="${p}" target="_blank" rel="noopener" class="mr-img-link"><img src="${p}" alt="${n}" class="mr-img" loading="lazy"></a>`;
    return `<div class="mr-doc-card">
        <i class="bi ${fileIcon(t)} mr-doc-icon"></i>
        <div class="mr-doc-info"><div class="mr-doc-name">${n}</div><div class="mr-doc-size">${s}</div></div>
        <a href="${p}" download class="mr-doc-dl"><i class="bi bi-download"></i></a>
    </div>`;
}

/* ════════════════════════════════════════════
   RENDER MESSAGE (JS)
   ════════════════════════════════════════════ */
function renderMessage(msg) {
    const mine   = parseInt(msg.sender_id,10) === ROOM.currentAdminId;
    const pinned = msg.is_pinned ? 1 : 0;
    const time   = fmtTime(msg.created_at);
    const avSrc  = esc(av(msg.sender_avatar));
    const sname  = !mine ? `<div class="mr-sender-name">${esc(msg.sender_name||'')}</div>` : '';
    const pinTag = pinned ? `<div class="mr-pin-tag"><i class="bi bi-pin-angle-fill"></i> ${ROOM.t.pinned}</div>` : '';
    const text   = (msg.content&&msg.content.trim()) ? `<div class="mr-text">${nl2br(msg.content)}</div>` : '';
    const attach = renderAttach(msg, mine);
    const avCol  = !mine ? `<img src="${avSrc}" class="mr-av" alt="">` : '';
    return `<div class="mr-row ${mine?'mr-mine':'mr-other'}" data-id="${parseInt(msg.id,10)}">
        ${avCol}
        <div class="mr-bbl-wrap">
            ${sname}
            <div class="mr-bbl${pinned?' mr-bbl-pinned':''}">
                ${pinTag}${text}${attach}
                <div class="mr-foot">
                    <button type="button" class="mr-pin-btn btn-pin" data-id="${parseInt(msg.id,10)}">
                        <i class="bi ${pinned?'bi-pin-angle-fill':'bi-pin-angle'}"></i>
                    </button>
                    <span class="mr-time">${time}</span>
                </div>
            </div>
        </div>
    </div>`;
}

/* ════════════════════════════════════════════
   APPEND MESSAGE
   ════════════════════════════════════════════ */
function appendMessage(msg, stick) {
    const empty = document.getElementById('mrEmpty');
    if (empty) empty.remove();
    mrMessages.insertAdjacentHTML('beforeend', renderMessage(msg));
    ROOM.lastId = Math.max(ROOM.lastId, parseInt(msg.id,10)||0);
    ROOM.messagesCount++;
    if (mrMsgCount) mrMsgCount.textContent = ROOM.messagesCount;
    if (stick !== false) scrollBottom(true);
}

/* ════════════════════════════════════════════
   ATTACHMENT PREVIEW
   ════════════════════════════════════════════ */
attachInput.addEventListener('change', function() {
    mrErrEl.classList.remove('show');
    if (!this.files.length) { hidePreview(); return; }
    const file = this.files[0];
    if (file.size > 8*1024*1024) {
        mrErrEl.textContent = '<?= addslashes(__('team_comm.file_too_large','File too large (max 8MB)')) ?>';
        mrErrEl.classList.add('show');
        this.value = ''; return;
    }
    if (file.type.startsWith('image/')) {
        const r = new FileReader();
        r.onload = e => showPreview(`<img src="${e.target.result}" class="mr-prev-thumb">`, file);
        r.readAsDataURL(file);
    } else {
        showPreview(`<i class="bi ${fileIcon(file.type)} mr-prev-file-ic"></i>`, file);
    }
});
function showPreview(thumb, file) {
    mrPreviewBar.classList.add('show');
    mrPreviewBar.innerHTML = `<div class="mr-prev-inner">${thumb}
        <div class="mr-prev-meta">
            <div class="mr-prev-name">${esc(file.name)}</div>
            <div class="mr-prev-size">${fmtSize(file.size)}</div>
        </div>
        <button type="button" class="mr-prev-rm" onclick="clearAttach()"><i class="bi bi-x-lg"></i></button>
    </div>`;
}
function hidePreview() { mrPreviewBar.classList.remove('show'); mrPreviewBar.innerHTML = ''; }
function clearAttach() { attachInput.value=''; hidePreview(); }

/* ════════════════════════════════════════════
   SEND FORM
   ════════════════════════════════════════════ */
mrForm.addEventListener('submit', async function(e) {
    e.preventDefault();
    if (!ROOM.composerEnabled) return;
    const content = (messageInput.value||'').trim();
    const hasFile = attachInput.files && attachInput.files.length;
    if (!content && !hasFile) return;
    const fd = new FormData();
    fd.append('_csrf',      ROOM.csrf);
    fd.append('meeting_id', ROOM.meetingId);
    fd.append('content',    messageInput.value||'');
    if (hasFile) fd.append('attachment', attachInput.files[0]);
    mrSendBtn.disabled = true;
    mrErrEl.classList.remove('show');
    try {
        const res  = await fetch('/admin/team/group-chat/send', { method:'POST', body:fd, credentials:'same-origin' });
        const text = await res.text();
        let data = {};
        try { data = JSON.parse(text); } catch(err) { data = { success:true }; }
        if (!res.ok || !data.success) throw new Error(data.error || ROOM.t.sendFailed);
        if (data.message) appendMessage(data.message);
        messageInput.value = ''; messageInput.style.height = 'auto';
        clearAttach(); mentionPop.classList.remove('open');
    } catch(err) {
        mrErrEl.textContent = err.message || ROOM.t.sendFailed;
        mrErrEl.classList.add('show');
    } finally {
        mrSendBtn.disabled = false;
        messageInput.focus();
    }
});

/* ════════════════════════════════════════════
   POLLING
   ════════════════════════════════════════════ */
async function poll() {
    try {
        const res  = await fetch('/admin/team/group-chat/poll/'+ROOM.meetingId+'?last_id='+ROOM.lastId, {credentials:'same-origin'});
        const data = await res.json();
        if (data.success && Array.isArray(data.messages) && data.messages.length) {
            data.messages.forEach(m => appendMessage(m, false));
            scrollBottom(true);
        }
    } catch(e) {}
}
setInterval(poll, 3000);

/* ════════════════════════════════════════════
   PIN MESSAGE
   ════════════════════════════════════════════ */
mrMessages.addEventListener('click', async function(e) {
    const btn = e.target.closest('.btn-pin');
    if (!btn) return;
    try {
        const res  = await fetch('/admin/team/group-chat/pin/'+btn.dataset.id, {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: new URLSearchParams({_csrf:ROOM.csrf, meeting_id:ROOM.meetingId}).toString(),
            credentials: 'same-origin'
        });
        const data = await res.json();
        if (data.success) {
            const bubble = btn.closest('.mr-bbl');
            const isPinned = bubble.classList.toggle('mr-bbl-pinned');
            btn.querySelector('i').className = 'bi ' + (isPinned ? 'bi-pin-angle-fill' : 'bi-pin-angle');
            let tag = bubble.querySelector('.mr-pin-tag');
            if (isPinned && !tag) bubble.insertAdjacentHTML('afterbegin', `<div class="mr-pin-tag"><i class="bi bi-pin-angle-fill"></i> ${ROOM.t.pinned}</div>`);
            else if (!isPinned && tag) tag.remove();
        }
    } catch(e) {}
});

/* ════════════════════════════════════════════
   EMOJI
   ════════════════════════════════════════════ */
btnEmoji.addEventListener('click', function() {
    const open = mrEmojiTray.classList.toggle('open');
    this.classList.toggle('active', open);
});
mrEmojiTray.addEventListener('click', function(e) {
    const btn = e.target.closest('[data-emoji]');
    if (!btn) return;
    const pos = messageInput.selectionStart || messageInput.value.length;
    messageInput.value = messageInput.value.slice(0,pos) + btn.getAttribute('data-emoji') + messageInput.value.slice(pos);
    messageInput.dispatchEvent(new Event('input'));
    messageInput.focus();
});
document.addEventListener('click', function(e) {
    if (!mrEmojiTray.contains(e.target) && e.target !== btnEmoji && !btnEmoji.contains(e.target))
        mrEmojiTray.classList.remove('open');
    if (!mentionPop.contains(e.target) && e.target !== messageInput)
        mentionPop.classList.remove('open');
});

/* ════════════════════════════════════════════
   MENTION  (@username)
   ════════════════════════════════════════════ */
let mentionState = { start:-1, query:'', active:0, results:[] };
function collectMentions(q) {
    return ROOM.attendees.filter(a => a.username && a.username.toLowerCase().includes(q.toLowerCase())).slice(0,6);
}
function renderMentionPop() {
    if (!mentionState.results.length) { mentionPop.classList.remove('open'); return; }
    mentionPop.innerHTML = mentionState.results.map((item,i) =>
        `<div class="mr-mention-item ${i===mentionState.active?'active':''}" data-idx="${i}">
            <img src="${esc(av(item.avatar))}" alt="">
            <div><div class="fw-semibold small">${esc(item.username)}</div>
            <div class="mr-drop-hint">${esc(item.role||'')}</div></div>
        </div>`
    ).join('');
    mentionPop.classList.add('open');
}
function applyMention(idx) {
    const item = mentionState.results[idx]; if(!item) return;
    const rep = '@' + item.username + ' ';
    messageInput.value = messageInput.value.slice(0, mentionState.start) + rep + messageInput.value.slice(messageInput.selectionStart);
    messageInput.selectionStart = messageInput.selectionEnd = mentionState.start + rep.length;
    mentionPop.classList.remove('open');
    mentionState = {start:-1, query:'', active:0, results:[]};
    messageInput.focus();
}
messageInput.addEventListener('input', function() {
    const pos    = this.selectionStart || 0;
    const before = this.value.slice(0, pos);
    const match  = before.match(/(^|\s)@([\p{L}0-9_.-]{0,50})$/u);
    if (!match) { mentionPop.classList.remove('open'); mentionState={start:-1,query:'',active:0,results:[]}; return; }
    const query = match[2]||'';
    mentionState.start   = pos - query.length - 1;
    mentionState.query   = query;
    mentionState.results = collectMentions(query);
    mentionState.active  = 0;
    renderMentionPop();
});
messageInput.addEventListener('keydown', function(e) {
    if (!mentionPop.classList.contains('open')) return;
    if (e.key==='ArrowDown') { e.preventDefault(); mentionState.active=(mentionState.active+1)%mentionState.results.length; renderMentionPop(); }
    else if (e.key==='ArrowUp') { e.preventDefault(); mentionState.active=(mentionState.active-1+mentionState.results.length)%mentionState.results.length; renderMentionPop(); }
    else if (e.key==='Enter'&&!e.shiftKey) { e.preventDefault(); applyMention(mentionState.active); }
    else if (e.key==='Escape') mentionPop.classList.remove('open');
});
mentionPop.addEventListener('click', e => { const item=e.target.closest('.mr-mention-item'); if(!item) return; applyMention(parseInt(item.dataset.idx,10)); });

/* Enter to send */
messageInput.addEventListener('keydown', function(e) {
    if (e.key==='Enter' && !e.shiftKey && !mentionPop.classList.contains('open')) {
        e.preventDefault(); mrForm.dispatchEvent(new Event('submit'));
    }
});

/* ════════════════════════════════════════════
   RSVP
   ════════════════════════════════════════════ */
document.querySelectorAll('#mrPanel .choice').forEach(btn => {
    btn.addEventListener('click', async function() {
        const body = new URLSearchParams({_csrf:ROOM.csrf, rsvp:this.dataset.rsvp});
        try {
            const res  = await fetch('/admin/team/meetings/rsvp/'+ROOM.meetingId, {
                method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
                body: body.toString(), credentials:'same-origin'
            });
            const data = await res.json();
            if (data.success) {
                document.querySelectorAll('#mrPanel .choice').forEach(x => x.classList.remove('active'));
                this.classList.add('active');
                if (this.dataset.rsvp === 'accepted') {
                    ROOM.composerEnabled = true;
                    messageInput.disabled = false;
                    mrSendBtn.disabled    = false;
                } else if (!ROOM.isManager) {
                    ROOM.composerEnabled = false;
                    messageInput.disabled = true;
                    mrSendBtn.disabled    = true;
                }
            }
        } catch(e) {}
    });
});

/* ════════════════════════════════════════════
   COMPLETE MEETING
   ════════════════════════════════════════════ */
document.getElementById('btnCompleteMeeting')?.addEventListener('click', async function() {
    if (!confirm(ROOM.t.completeConfirm)) return;
    const body = new URLSearchParams({_csrf: ROOM.csrf});
    try {
        const res  = await fetch('/admin/team/meetings/complete/'+ROOM.meetingId, {
            method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body: body.toString(), credentials:'same-origin'
        });
        const data = await res.json();
        if (data.success) window.location.reload();
    } catch(e) {}
});

/* ════════════════════════════════════════════
   MOBILE PANEL TOGGLE
   ════════════════════════════════════════════ */
function openPanel()  { document.getElementById('mrPanel').classList.add('open');    document.getElementById('mrBackdrop').classList.add('show'); }
function closePanel() { document.getElementById('mrPanel').classList.remove('open'); document.getElementById('mrBackdrop').classList.remove('show'); }
document.getElementById('mrPanelOpen')?.addEventListener('click',  openPanel);
document.getElementById('mrPanelClose')?.addEventListener('click', closePanel);
document.getElementById('mrBackdrop')?.addEventListener('click',   closePanel);
</script>

<?php if (!empty($videoEnabled) && !$meetingEnded): ?>
<?php
$_vmProvider  = $videoProvider ?? 'jitsi';
$_vmMeetingId = (int)($meeting['id'] ?? 0);
$_vmLabels    = ['jitsi' => 'Jitsi Meet', 'daily' => 'Daily.co', 'whereby' => 'Whereby'];
$_vmLabel     = $_vmLabels[$_vmProvider] ?? $_vmProvider;
/* For Jitsi build the URL server-side — no AJAX needed */
$_vmJitsiUrl  = '';
if ($_vmProvider === 'jitsi') {
    $_cfg = \Core\App\Services\VideoMeetingService::getActiveConfig();
    $_ext = $_cfg['extra'] ?? [];
    $_d   = preg_replace('#^https?://#','', trim($_ext['domain'] ?? 'meet.jit.si'));
    $_d   = rtrim($_d, '/') ?: 'meet.jit.si';
    $_pfx = trim($_ext['room_prefix'] ?? 'meeting') ?: 'meeting';
    $_vmJitsiUrl = 'https://' . $_d . '/' . $_pfx . '-' . $_vmMeetingId;
}
?>
<style>
.vm-live-indicator {
    display:none; align-items:center; gap:8px;
    position:fixed; bottom:18px; left:50%; transform:translateX(-50%);
    z-index:9998; min-width:280px; max-width:420px;
    padding:10px 16px; border-radius:999px;
    background:#0d3b26; border:1.5px solid #198754;
    box-shadow:0 10px 30px rgba(0,0,0,.35);
    font-size:13px; font-weight:700; color:#6fe0a8;
    white-space:nowrap;
}
.vm-live-dot {
    width:9px; height:9px; border-radius:50%;
    background:#6fe0a8; flex-shrink:0;
    animation: vmPulse 1.4s ease-in-out infinite;
}
@keyframes vmPulse {
    0%,100%{ opacity:1; transform:scale(1); }
    50%    { opacity:.35; transform:scale(.65); }
}
.vm-rejoin-btn {
    margin-inline-start:auto; background:rgba(255,255,255,.1);
    border:1px solid rgba(110,224,168,.4); border-radius:20px;
    cursor:pointer; font-size:11px; font-weight:700; color:#6fe0a8;
    padding:3px 10px; transition:background .2s;
}
.vm-rejoin-btn:hover { background:rgba(255,255,255,.2); }

#mrVideoModal {
    position: fixed; inset: 0; z-index: 3000;
    display:none; align-items:stretch; justify-content:stretch;
    background: rgba(7,10,17,.76); backdrop-filter: blur(8px);
}
#mrVideoModal.open { display:flex; }
.body-video-open { overflow:hidden; }
.mr-video-shell {
    display:flex; flex-direction:column; width:100%; height:100%;
    background: linear-gradient(180deg, rgba(14,19,29,.98), rgba(7,10,17,.98));
}
.mr-video-topbar {
    min-height:72px; padding:14px 18px; display:flex; align-items:center; gap:14px;
    border-bottom:1px solid rgba(255,255,255,.08); color:#f8fafc;
    background:linear-gradient(180deg, rgba(255,255,255,.04), rgba(255,255,255,.01));
}
.mr-video-topbar .mr-title-wrap { min-width:0; flex:1; }
.mr-video-topbar h3 {
    font-size:18px; line-height:1.2; margin:0 0 4px; color:#fff;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.mr-video-meta {
    display:flex; align-items:center; gap:10px; flex-wrap:wrap;
    color:rgba(255,255,255,.72); font-size:12px;
}
.mr-video-provider, .mr-video-status {
    display:inline-flex; align-items:center; gap:6px; padding:5px 10px;
    border-radius:999px; background:rgba(255,255,255,.08); border:1px solid rgba(255,255,255,.1);
}
.mr-video-status i { color:#6fe0a8; font-size:8px; }
.mr-video-actions { display:flex; align-items:center; gap:10px; }
.mr-vbtn {
    min-width:42px; height:42px; border:none; border-radius:999px; cursor:pointer;
    display:inline-flex; align-items:center; justify-content:center; gap:7px;
    padding:0 14px; font-size:13px; font-weight:700; color:#fff;
    background:rgba(255,255,255,.1); border:1px solid rgba(255,255,255,.12);
    transition:transform .15s ease, background .15s ease, border-color .15s ease;
}
.mr-vbtn:hover { transform:translateY(-1px); background:rgba(255,255,255,.16); }
.mr-vbtn.danger { background:rgba(220,53,69,.18); border-color:rgba(220,53,69,.35); }
.mr-vbtn.danger:hover { background:rgba(220,53,69,.28); }
.mr-video-body { position:relative; flex:1; padding:18px; }
.mr-video-framewrap {
    width:100%; height:100%; border-radius:22px; overflow:hidden;
    background:#05070c; border:1px solid rgba(255,255,255,.08);
    box-shadow:0 16px 60px rgba(0,0,0,.4); position:relative;
}
#mrVideoFrame {
    width:100%; height:100%; border:0; background:#000; display:none;
}
#mrVideoFrame.active { display:block; }
.mr-video-placeholder {
    position:absolute; inset:0; display:flex; align-items:center; justify-content:center;
    flex-direction:column; gap:14px; color:rgba(255,255,255,.84); text-align:center; padding:30px;
}
.mr-video-placeholder .mr-pl-icon {
    width:92px; height:92px; border-radius:28px; display:flex; align-items:center; justify-content:center;
    background:rgba(255,255,255,.06); border:1px solid rgba(255,255,255,.08); font-size:42px;
    box-shadow:0 12px 32px rgba(0,0,0,.2);
}
.mr-video-placeholder p { max-width:520px; line-height:1.7; color:rgba(255,255,255,.72); }
.mr-video-loader {
    display:none; position:absolute; inset:0; align-items:center; justify-content:center;
    background:rgba(5,7,12,.45); z-index:2;
}
.mr-video-loader.show { display:flex; }
.mr-video-loader .spinner {
    width:54px; height:54px; border:4px solid rgba(255,255,255,.16); border-top-color:#fff;
    border-radius:50%; animation:vmSpin .85s linear infinite;
}
@keyframes vmSpin { to { transform: rotate(360deg); } }
@media (max-width: 991.98px) {
    .mr-video-topbar { padding:12px; min-height:unset; flex-wrap:wrap; }
    .mr-video-body { padding:12px; }
    .mr-video-actions { width:100%; justify-content:space-between; }
    .mr-vbtn span { display:none; }
    .mr-vbtn { padding:0; width:42px; }
    .vm-live-indicator { max-width:calc(100vw - 24px); min-width:unset; width:auto; }
}
@media (max-width: 575.98px) {
    .mr-video-topbar { gap:10px; }
    .mr-video-topbar h3 { font-size:15px; }
    .mr-video-meta { gap:6px; font-size:11px; }
    .mr-video-provider, .mr-video-status { padding:4px 8px; }
    .mr-video-body { padding:8px; }
    .mr-video-framewrap { border-radius:16px; }
    .mr-video-placeholder { padding:18px; gap:10px; }
    .mr-video-placeholder .mr-pl-icon { width:72px; height:72px; border-radius:22px; font-size:30px; }
    .mr-video-placeholder h4 { font-size:15px; }
    .mr-video-placeholder p { font-size:12px; line-height:1.6; }
    .vm-live-indicator {
        inset-inline: 8px;
        bottom: calc(8px + env(safe-area-inset-bottom, 0px));
        border-radius: 14px;
        padding: 10px 12px;
        gap: 8px;
        justify-content: center;
    }
    .vm-rejoin-btn { font-size: 10px; }
}
</style>

<div class="vm-live-indicator" id="vmLiveIndicator">
    <span class="vm-live-dot"></span>
    <?= __('video_meeting.meeting_live','Meeting in progress') ?>
    <button type="button" class="vm-rejoin-btn" id="vmRejoinBtn">
        <?= __('video_meeting.rejoin','Rejoin') ?>
    </button>
</div>

<div id="mrVideoModal" aria-hidden="true">
    <div class="mr-video-shell">
        <div class="mr-video-topbar">
            <div class="mr-title-wrap">
                <h3><?= htmlspecialchars($meeting['title'] ?? __('sidebar.team_meetings','Meeting'), ENT_QUOTES) ?></h3>
                <div class="mr-video-meta">
                    <span class="mr-video-provider"><i class="bi bi-camera-video-fill"></i> <?= htmlspecialchars($_vmLabel, ENT_QUOTES) ?></span>
                    <span class="mr-video-status"><i class="bi bi-circle-fill"></i> <?= __('video_meeting.inside_site','Inside your site') ?></span>
                </div>
            </div>
            <div class="mr-video-actions">
                <button type="button" class="mr-vbtn" id="mrVideoReload" title="<?= htmlspecialchars(__('video_meeting.rejoin','Rejoin'), ENT_QUOTES) ?>">
                    <i class="bi bi-arrow-clockwise"></i><span><?= __('video_meeting.rejoin','Rejoin') ?></span>
                </button>
                <button type="button" class="mr-vbtn" id="mrVideoOpenNew" title="<?= htmlspecialchars(__('video_meeting.open_new_tab','Open in new tab'), ENT_QUOTES) ?>">
                    <i class="bi bi-box-arrow-up-right"></i><span><?= __('video_meeting.open_new_tab','Open in new tab') ?></span>
                </button>
                <button type="button" class="mr-vbtn danger" id="mrVideoClose" title="<?= htmlspecialchars(__('team_meeting.complete','Close'), ENT_QUOTES) ?>">
                    <i class="bi bi-x-lg"></i><span><?= __('team_comm.close','Close') ?></span>
                </button>
            </div>
        </div>
        <div class="mr-video-body">
            <div class="mr-video-framewrap">
                <div class="mr-video-loader" id="mrVideoLoader"><div class="spinner"></div></div>
                <div class="mr-video-placeholder" id="mrVideoPlaceholder">
                    <div class="mr-pl-icon"><i class="bi bi-camera-video"></i></div>
                    <h4><?= __('video_meeting.ready_inside_site','The video meeting is ready inside your site') ?></h4>
                    <p><?= __('video_meeting.ready_inside_site_desc','When you start or join the call, it will open here without moving the user to an external page.') ?></p>
                </div>
                <iframe id="mrVideoFrame" allow="camera; microphone; display-capture; autoplay; clipboard-read; clipboard-write; fullscreen" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const MEETING_ID     = <?= (int)$_vmMeetingId ?>;
    const PROVIDER       = <?= json_encode($_vmProvider, JSON_UNESCAPED_UNICODE) ?>;
    const JITSI_URL      = <?= json_encode($_vmJitsiUrl, JSON_UNESCAPED_UNICODE) ?>;
    const START_ENDPOINT = '/admin/team/meetings/video-start/' + MEETING_ID;
    const ERR_FALLBACK   = <?= json_encode(__('video_meeting.url_failed','Could not generate room URL'), JSON_UNESCAPED_UNICODE) ?>;
    const CSRF           = <?= json_encode($csrfToken, JSON_UNESCAPED_UNICODE) ?>;

    const btnVideo       = document.getElementById('btnVideoMeeting');
    const btnSpinner     = document.getElementById('vmBtnSpinner');
    const liveIndicator  = document.getElementById('vmLiveIndicator');
    const rejoinBtn      = document.getElementById('vmRejoinBtn');
    const modal          = document.getElementById('mrVideoModal');
    const iframe         = document.getElementById('mrVideoFrame');
    const placeholder    = document.getElementById('mrVideoPlaceholder');
    const loader         = document.getElementById('mrVideoLoader');
    const btnClose       = document.getElementById('mrVideoClose');
    const btnReload      = document.getElementById('mrVideoReload');
    const btnOpenNew     = document.getElementById('mrVideoOpenNew');

    let vmUrl            = null;
    let vmBaseUrl        = null;
    let vmLocallyStarted = false;

    function postChatNotification(msgData) {
        if (!msgData || typeof appendMessage !== 'function') return;
        appendMessage(msgData, true);
    }

    function showLoader(on) {
        if (!loader) return;
        loader.classList.toggle('show', !!on);
    }

    function showLive() {
        liveIndicator && (liveIndicator.style.display = 'flex');
        if (btnVideo) {
            btnVideo.style.background = 'linear-gradient(135deg,#198754,#146c43)';
            btnVideo.dataset.state = 'live';
        }
    }

    function hideLive() {
        liveIndicator && (liveIndicator.style.display = 'none');
        if (btnVideo) {
            btnVideo.style.background = '';
            delete btnVideo.dataset.state;
        }
    }

    function openEmbedded(url) {
        vmUrl = url;
        vmBaseUrl = vmBaseUrl || url.split(/[?#]/)[0];
        showLive();
        if (placeholder) placeholder.style.display = 'none';
        if (iframe) {
            showLoader(true);
            iframe.classList.add('active');
            if (iframe.src !== url) iframe.src = url;
        }
        modal && modal.classList.add('open');
        document.body.classList.add('body-video-open');
        modal?.setAttribute('aria-hidden', 'false');
    }

    function closeEmbedded() {
        modal && modal.classList.remove('open');
        document.body.classList.remove('body-video-open');
        modal?.setAttribute('aria-hidden', 'true');
        showLoader(false);
        if (iframe) {
            iframe.classList.remove('active');
            iframe.src = 'about:blank';
        }
        if (placeholder) placeholder.style.display = 'flex';
        if (vmUrl) showLive();
    }

    async function startOrJoin() {
        if (modal?.classList.contains('open') && vmUrl) return;
        if (vmUrl && !modal?.classList.contains('open')) { openEmbedded(vmUrl); return; }

        if (PROVIDER === 'jitsi' && JITSI_URL) {
            openEmbedded(JITSI_URL);
            if (!vmLocallyStarted) {
                vmLocallyStarted = true;
                try {
                    const fd = new FormData();
                    fd.append('_csrf', CSRF);
                    const res = await fetch(START_ENDPOINT, { method:'POST', body:fd, credentials:'same-origin' });
                    const data = await res.json();
                    if (data.success && data.message) postChatNotification(data.message);
                } catch (e) {}
            }
            return;
        }

        btnVideo && (btnVideo.disabled = true);
        btnSpinner && btnSpinner.classList.remove('d-none');
        try {
            const fd = new FormData();
            fd.append('_csrf', CSRF);
            const res  = await fetch(START_ENDPOINT, { method:'POST', body:fd, credentials:'same-origin' });
            const text = await res.text();
            let data   = {};
            try { data = JSON.parse(text); } catch (e) { throw new Error('Server error'); }
            if (data.success && data.url) {
                vmLocallyStarted = true;
                openEmbedded(data.url);
                if (data.message) postChatNotification(data.message);
            } else {
                alert(data.error || ERR_FALLBACK);
            }
        } catch (e) {
            alert(e.message || 'Network error — please try again');
        } finally {
            btnVideo && (btnVideo.disabled = false);
            btnSpinner && btnSpinner.classList.add('d-none');
        }
    }

    iframe?.addEventListener('load', function () {
        showLoader(false);
    });

    btnVideo?.addEventListener('click', startOrJoin);
    rejoinBtn?.addEventListener('click', function () {
        if (vmUrl) {
            openEmbedded(vmUrl);
        } else {
            startOrJoin();
        }
    });
    btnReload?.addEventListener('click', function () {
        const baseUrl = vmBaseUrl || vmUrl;
        if (!baseUrl) return startOrJoin();
        openEmbedded(baseUrl + (baseUrl.includes('?') ? '&' : '?') + '_reload=' + Date.now());
    });
    btnOpenNew?.addEventListener('click', function () {
        if (!vmUrl) return;
        window.open(vmUrl, '_blank', 'noopener');
    });
    btnClose?.addEventListener('click', closeEmbedded);
    modal?.addEventListener('click', function (e) {
        if (e.target === modal) closeEmbedded();
    });
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal?.classList.contains('open')) closeEmbedded();
    });
})();
</script>
<?php endif; ?>
</body>
</html>
