<?php
// Variables: $allMeetings, $announcements, $unreadTotal
$currentAdminId = (int)$_SESSION['admin_id'];
$isManager      = in_array($_SESSION['admin_role'] ?? '', ['owner','manager'], true);
$csrfToken      = \Core\System\Csrf::token();

include __DIR__ . '/../header.php';
?>

<style>
/* ── RSVP Respond button (in table cell) ── */
.btn-rsvp-respond {
    display: inline-flex; align-items: center; gap: .25rem;
    font-size: .72rem; font-weight: 600;
    padding: .28rem .7rem; border-radius: 20px;
    border: 1.5px solid rgba(var(--bs-primary-rgb, 13,110,253), .35);
    background: rgba(var(--bs-primary-rgb, 13,110,253), .07);
    color: var(--bs-primary, #0d6efd); cursor: pointer;
    transition: background .15s, border-color .15s, transform .1s;
    white-space: nowrap; line-height: 1.3;
}
.btn-rsvp-respond:hover {
    background: rgba(var(--bs-primary-rgb, 13,110,253), .15);
    border-color: var(--bs-primary, #0d6efd);
    transform: scale(1.03);
}

/* ── Current RSVP status chip ── */
.rsvp-status-chip {
    display: inline-flex; align-items: center; gap: .22rem;
    font-size: .7rem; font-weight: 600;
    padding: .22rem .55rem; border-radius: 20px;
    white-space: nowrap;
}
.rsvp-chip-accepted { background: rgba(var(--bs-success-rgb,25,135,84),.11);  color: var(--bs-success,#198754); border: 1px solid rgba(var(--bs-success-rgb,25,135,84),.25); }
.rsvp-chip-declined { background: rgba(var(--bs-danger-rgb,220,53,69),.11);   color: var(--bs-danger,#dc3545);  border: 1px solid rgba(var(--bs-danger-rgb,220,53,69),.25); }
.rsvp-chip-pending  { background: rgba(var(--bs-secondary-rgb,108,117,125),.09); color: var(--bs-secondary,#6c757d); border: 1px solid rgba(var(--bs-secondary-rgb,108,117,125),.2); }

/* ── Group chat open link ── */
.btn-gc-link {
    display: inline-flex; align-items: center; gap: .28rem;
    font-size: .72rem; font-weight: 600;
    padding: .28rem .7rem; border-radius: 20px;
    border: 1.5px solid rgba(var(--bs-success-rgb,25,135,84),.35);
    background: rgba(var(--bs-success-rgb,25,135,84),.07);
    color: var(--bs-success,#198754); text-decoration: none;
    transition: all .15s; white-space: nowrap;
}
.btn-gc-link:hover {
    background: rgba(var(--bs-success-rgb,25,135,84),.15);
    border-color: var(--bs-success,#198754); color: var(--bs-success,#198754);
}

/* ── RSVP Modal ── */
#rsvpModal .modal-content {
    border: none;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0,0,0,.14);
}
.rsvp-modal-top-bar {
    height: 5px;
    background: var(--bs-primary, #0d6efd);
}
.rsvp-modal-header-row {
    display: flex; align-items: flex-start; gap: .85rem;
    padding: 1.25rem 1.4rem .6rem;
}
.rsvp-modal-icon {
    width: 48px; height: 48px; border-radius: 14px; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.25rem;
}
.rsvp-modal-titles { flex: 1; min-width: 0; }
.rsvp-modal-title {
    font-size: .97rem; font-weight: 800;
    line-height: 1.35; margin-bottom: .25rem;
    word-break: break-word;
    color: var(--bs-body-color, #212529);
}
.rsvp-modal-type-badge {
    font-size: .63rem; font-weight: 700; padding: .12rem .48rem;
    border-radius: 8px; display: inline-flex; align-items: center; gap: .2rem;
}
/* Meta grid */
.rsvp-info-grid {
    display: grid; grid-template-columns: 1fr 1fr; gap: .5rem;
    background: var(--bs-light, #f8f9fa);
    border-radius: 14px; padding: .9rem 1rem;
    margin: 0 1.4rem .9rem;
}
.rsvp-info-cell {
    display: flex; align-items: flex-start; gap: .42rem;
}
.rsvp-info-cell > i {
    font-size: .8rem; color: var(--bs-primary,#0d6efd);
    flex-shrink: 0; margin-top: .12rem;
}
.rsvp-info-lbl {
    font-size: .63rem; color: #aaa; font-weight: 700;
    text-transform: uppercase; letter-spacing: .04em; display: block;
}
.rsvp-info-val { font-size: .8rem; color: #444; font-weight: 500; }
.rsvp-info-full { grid-column: 1 / -1; }
/* Description */
.rsvp-desc-block {
    margin: 0 1.4rem .9rem;
    background: rgba(0,0,0,.03); border-radius: 10px;
    padding: .6rem .85rem;
    font-size: .78rem; color: #555; line-height: 1.65; white-space: pre-wrap;
}
/* Divider */
.rsvp-modal-divider { border: none; border-top: 1px solid var(--bs-border-color,#dee2e6); margin: 0 0 .9rem; }
/* Current status */
.rsvp-current-wrap {
    display: flex; align-items: center; gap: .55rem; flex-wrap: wrap;
    padding: 0 1.4rem; margin-bottom: .85rem;
}
.rsvp-current-label { font-size: .72rem; font-weight: 600; color: #888; }
/* Response buttons */
.rsvp-resp-wrap {
    padding: 0 1.4rem 1.4rem;
}
.rsvp-resp-label { font-size: .72rem; font-weight: 700; color: #888; margin-bottom: .6rem; text-transform: uppercase; letter-spacing: .04em; }
.rsvp-resp-row { display: flex; gap: .55rem; flex-wrap: wrap; }
.rsvp-resp-btn {
    flex: 1; min-width: 88px;
    display: flex; flex-direction: column; align-items: center; gap: .3rem;
    padding: .85rem .5rem; border-radius: 14px;
    border: 2px solid transparent; cursor: pointer;
    font-size: .79rem; font-weight: 700;
    transition: all .18s; background: rgba(0,0,0,.03);
}
.rsvp-resp-btn i { font-size: 1.45rem; line-height: 1; }
.rsvp-resp-btn:hover { transform: translateY(-3px); box-shadow: 0 5px 16px rgba(0,0,0,.11); }
.rsvp-btn-accept  { color: var(--bs-success,#198754); border-color: rgba(var(--bs-success-rgb,25,135,84),.3); background: rgba(var(--bs-success-rgb,25,135,84),.05); }
.rsvp-btn-accept:hover, .rsvp-btn-accept.rsvp-active { background: rgba(var(--bs-success-rgb,25,135,84),.14); border-color: var(--bs-success,#198754); }
.rsvp-btn-decline { color: var(--bs-danger,#dc3545);  border-color: rgba(var(--bs-danger-rgb,220,53,69),.3);  background: rgba(var(--bs-danger-rgb,220,53,69),.05); }
.rsvp-btn-decline:hover, .rsvp-btn-decline.rsvp-active { background: rgba(var(--bs-danger-rgb,220,53,69),.14); border-color: var(--bs-danger,#dc3545); }
.rsvp-btn-maybe   { color: var(--bs-secondary,#6c757d); border-color: rgba(var(--bs-secondary-rgb,108,117,125),.3); background: rgba(var(--bs-secondary-rgb,108,117,125),.04); }
.rsvp-btn-maybe:hover, .rsvp-btn-maybe.rsvp-active { background: rgba(var(--bs-secondary-rgb,108,117,125),.13); border-color: var(--bs-secondary,#6c757d); }
.rsvp-active { box-shadow: 0 0 0 3px rgba(var(--bs-primary-rgb,13,110,253),.15) !important; }

@media (max-width: 575.98px) {
    .rsvp-info-grid { grid-template-columns: 1fr; }
}
</style>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold">
            <i class="bi bi-calendar-event-fill me-2 text-info"></i><?= __('sidebar.team_meetings','Meetings') ?>
        </h3>
        <p class="text-muted mb-0 small"><?= __('team_meeting.subtitle','Schedule and manage team meetings') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="/admin/team/communication" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-chat-dots me-1"></i><?= __('sidebar.team_communication','Messages') ?>
        </a>
        <?php if ($isManager): ?>
        <a href="/admin/team/meetings/create" class="btn btn-primary btn-sm">
            <i class="bi bi-plus-circle me-1"></i><?= __('team_meeting.create','Schedule Meeting') ?>
        </a>
        <?php endif; ?>
    </div>
</div>

<?php if (!empty($_GET['success'])): ?>
<div class="alert alert-success alert-dismissible fade show py-2 small" role="alert">
    <?= __('team_meeting.'.$_GET['success'], 'Done!') ?>
    <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Meetings Table -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom py-2 d-flex align-items-center justify-content-between">
        <span class="fw-semibold small"><?= __('team_meeting.all_meetings','All Meetings') ?></span>
        <div class="input-group input-group-sm" style="max-width:220px">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" class="form-control" id="searchMeetings"
                   placeholder="<?= htmlspecialchars(__('team_meeting.search','Search...'), ENT_QUOTES) ?>">
        </div>
    </div>
    <div class="table-responsive">
        <table class="table table-hover table-sm mb-0" id="meetingsTable">
            <thead class="table-light">
                <tr>
                    <th><?= __('team_meeting.title','Title') ?></th>
                    <th><?= __('team_meeting.type','Type') ?></th>
                    <th><?= __('team_meeting.scheduled','Scheduled') ?></th>
                    <th><?= __('team_meeting.duration','Duration') ?></th>
                    <th><?= __('team_meeting.attendees','Attendees') ?></th>
                    <th><?= __('team_meeting.status','Status') ?></th>
                    <th><?= __('team_meeting.my_rsvp','My RSVP') ?></th>
                    <?php if ($isManager): ?><th></th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($allMeetings as $m): ?>
                <?php
                    $myRsvp        = $m['my_rsvp'] ?? null;
                    $isAttendee    = (int)($m['is_attendee'] ?? 0) > 0;
                    $attendeeCount = (int)($m['attendee_count'] ?? 0);
                    $acceptedCount = (int)($m['accepted_count'] ?? 0);
                    $hasGroupChat  = !empty($m['has_group_chat']) || ($m['meeting_type'] === 'group_chat');
                    $rsvpCurrent   = $myRsvp ?? 'pending';
                    $rsvpCfg = [
                        'pending'  => ['color'=>'secondary', 'icon'=>'bi-hourglass-split',    'label'=> __('team_meeting.rsvp_pending','Pending')],
                        'accepted' => ['color'=>'success',   'icon'=>'bi-calendar-check-fill', 'label'=> __('team_meeting.rsvp_accepted','Accepted')],
                        'declined' => ['color'=>'danger',    'icon'=>'bi-calendar-x-fill',     'label'=> __('team_meeting.rsvp_declined','Declined')],
                    ];
                    $cur = $rsvpCfg[$rsvpCurrent] ?? $rsvpCfg['pending'];
                    $typeColors  = ['standup'=>'info','review'=>'primary','training'=>'success','planning'=>'warning','group_chat'=>'success'];
                    $typeColor   = $typeColors[$m['meeting_type']] ?? 'secondary';
                    $typeIcons   = ['standup'=>'bi-lightning-charge-fill','review'=>'bi-clipboard-check-fill','training'=>'bi-mortarboard-fill','planning'=>'bi-kanban-fill','group_chat'=>'bi-chat-dots-fill','other'=>'bi-calendar-event-fill'];
                    $typeIcon    = $typeIcons[$m['meeting_type']] ?? 'bi-calendar-event-fill';
                ?>
                <tr class="meeting-row"
                    data-title="<?= htmlspecialchars(strtolower($m['title']), ENT_QUOTES) ?>"
                    data-status="<?= htmlspecialchars($m['status'], ENT_QUOTES) ?>">

                    <td>
                        <div class="fw-semibold small"><?= htmlspecialchars($m['title']) ?></div>
                        <?php if (!empty($m['location'])): ?>
                        <div class="text-muted" style="font-size:.7rem">
                            <i class="bi bi-geo-alt me-1"></i><?= htmlspecialchars($m['location']) ?>
                        </div>
                        <?php endif; ?>
                    </td>

                    <td>
                        <span class="badge bg-<?= $typeColor ?> rounded-pill">
                            <?= __('team_meeting.type_'.$m['meeting_type'], str_replace('_',' ',$m['meeting_type'])) ?>
                        </span>
                    </td>

                    <td class="small">
                        <?= app_format_datetime($m['scheduled_at'], 'd M Y') ?><br>
                        <span class="text-muted"><?= app_format_datetime($m['scheduled_at'], 'H:i') ?></span>
                    </td>

                    <td class="small"><?= (int)$m['duration_minutes'] ?> <?= __('team_comm.minutes','min') ?></td>

                    <td class="small">
                        <?= $attendeeCount ?> <?= __('team_meeting.total','total') ?>
                        <?php if ($acceptedCount > 0): ?>
                        / <span class="text-success"><?= $acceptedCount ?> ✓</span>
                        <?php endif; ?>
                    </td>

                    <td>
                        <span class="badge bg-<?= ['upcoming'=>'primary','completed'=>'success','cancelled'=>'secondary'][$m['status']] ?? 'secondary' ?>">
                            <?= __('team_meeting.status_'.$m['status'], $m['status']) ?>
                        </span>
                    </td>

                    <!-- ══ RSVP COLUMN ══ -->
                    <td>
                        <?php if ($isAttendee && $m['status'] === 'upcoming'): ?>
                        <div class="d-flex flex-column gap-1 align-items-start">
                            <!-- Current status chip -->
                            <span class="rsvp-status-chip rsvp-chip-<?= $rsvpCurrent ?>">
                                <i class="bi <?= $cur['icon'] ?>"></i>
                                <?= $cur['label'] ?>
                            </span>
                            <!-- Respond button → opens modal -->
                            <button type="button"
                                    class="btn-rsvp-respond"
                                    data-id="<?= (int)$m['id'] ?>"
                                    data-title="<?= htmlspecialchars($m['title'], ENT_QUOTES) ?>"
                                    data-type="<?= htmlspecialchars($m['meeting_type'], ENT_QUOTES) ?>"
                                    data-type-label="<?= htmlspecialchars(__('team_meeting.type_'.$m['meeting_type'], str_replace('_',' ',$m['meeting_type'])), ENT_QUOTES) ?>"
                                    data-type-color="<?= htmlspecialchars($typeColor, ENT_QUOTES) ?>"
                                    data-type-icon="<?= htmlspecialchars($typeIcon, ENT_QUOTES) ?>"
                                    data-date="<?= htmlspecialchars(app_format_datetime($m['scheduled_at'], 'd M Y'), ENT_QUOTES) ?>"
                                    data-time="<?= htmlspecialchars(app_format_datetime($m['scheduled_at'], 'H:i'), ENT_QUOTES) ?>"
                                    data-duration="<?= (int)$m['duration_minutes'] ?>"
                                    data-attendees="<?= $attendeeCount ?>"
                                    data-accepted="<?= $acceptedCount ?>"
                                    data-location="<?= htmlspecialchars($m['location'] ?? '', ENT_QUOTES) ?>"
                                    data-description="<?= htmlspecialchars($m['description'] ?? '', ENT_QUOTES) ?>"
                                    data-rsvp="<?= htmlspecialchars($rsvpCurrent, ENT_QUOTES) ?>">
                                <i class="bi bi-reply-fill" style="font-size:.65rem"></i>
                                <?= __('team_meeting.respond','Respond') ?>
                            </button>
                            <?php if ($hasGroupChat && $rsvpCurrent === 'accepted'): ?>
                            <a href="/admin/team/meetings/room/<?= (int)$m['id'] ?>" class="btn-gc-link">
                                <i class="bi bi-chat-dots-fill"></i>
                                <?= __('team_meeting.open_group_chat','Group Chat') ?>
                            </a>
                            <?php endif; ?>
                        </div>

                        <?php elseif ($isAttendee): ?>
                        <span class="badge rounded-pill bg-<?= $cur['color'] ?>-subtle text-<?= $cur['color'] ?> border border-<?= $cur['color'] ?>-subtle" style="font-size:.72rem">
                            <i class="bi <?= $cur['icon'] ?> me-1"></i><?= $cur['label'] ?>
                        </span>

                        <?php elseif ($hasGroupChat && ($isManager || (int)($m['created_by'] ?? 0) === $currentAdminId)): ?>
                        <a href="/admin/team/meetings/room/<?= (int)$m['id'] ?>" class="btn-gc-link">
                            <i class="bi bi-chat-dots-fill"></i>
                            <?= __('meeting_room.open_room','Open Room') ?>
                        </a>

                        <?php else: ?>
                        <span class="text-muted" style="font-size:.75rem">—</span>
                        <?php endif; ?>
                    </td>

                    <?php if ($isManager): ?>
                    <td>
                        <div class="d-flex gap-1">
                            <?php if ($m['status'] === 'upcoming'): ?>
                            <button class="btn btn-sm btn-outline-success btn-complete-meeting"
                                    data-id="<?= (int)$m['id'] ?>"
                                    title="<?= htmlspecialchars(__('team_meeting.complete','End meeting')) ?>">
                                <i class="bi bi-check2-circle"></i>
                            </button>
                            <?php endif; ?>
                            <?php if ($m['status'] !== 'completed'): ?>
                            <a href="/admin/team/meetings/edit/<?= (int)$m['id'] ?>" class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <?php endif; ?>
                            <button class="btn btn-sm btn-outline-danger btn-del-meeting" data-id="<?= (int)$m['id'] ?>">
                                <i class="bi bi-trash3"></i>
                            </button>
                        </div>
                    </td>
                    <?php endif; ?>

                </tr>
                <?php endforeach; ?>

                <?php if (empty($allMeetings)): ?>
                <tr>
                    <td colspan="<?= $isManager ? 8 : 7 ?>" class="text-center text-muted py-4 small">
                        <i class="bi bi-calendar-x fs-3 d-block mb-2 opacity-50"></i>
                        <?= __('team_meeting.no_meetings','No meetings scheduled yet') ?>
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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


<!-- ╔═══════════════════════════════════════════╗ -->
<!-- ║         RSVP MODAL                       ║ -->
<!-- ╚═══════════════════════════════════════════╝ -->
<div class="modal fade" id="rsvpModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width:460px">
        <div class="modal-content" id="rsvpModalContent">

            <!-- Top color bar -->
            <div class="rsvp-modal-top-bar" id="rsvpTopBar"></div>

            <!-- Header -->
            <div class="rsvp-modal-header-row">
                <div class="rsvp-modal-icon" id="rsvpModalIcon"></div>
                <div class="rsvp-modal-titles">
                    <div class="rsvp-modal-title" id="rsvpModalTitle"></div>
                    <span class="rsvp-modal-type-badge" id="rsvpTypeBadge"></span>
                </div>
                <button type="button" class="btn-close flex-shrink-0" data-bs-dismiss="modal"></button>
            </div>

            <!-- Info grid -->
            <div class="rsvp-info-grid" id="rsvpInfoGrid">
                <div class="rsvp-info-cell">
                    <i class="bi bi-calendar3"></i>
                    <div>
                        <span class="rsvp-info-lbl"><?= __('team_meeting.scheduled','Date') ?></span>
                        <span class="rsvp-info-val" id="rsvpDate"></span>
                    </div>
                </div>
                <div class="rsvp-info-cell">
                    <i class="bi bi-clock"></i>
                    <div>
                        <span class="rsvp-info-lbl"><?= __('team_meeting.time','Time') ?></span>
                        <span class="rsvp-info-val" id="rsvpTime"></span>
                    </div>
                </div>
                <div class="rsvp-info-cell">
                    <i class="bi bi-stopwatch"></i>
                    <div>
                        <span class="rsvp-info-lbl"><?= __('team_meeting.duration','Duration') ?></span>
                        <span class="rsvp-info-val" id="rsvpDuration"></span>
                    </div>
                </div>
                <div class="rsvp-info-cell">
                    <i class="bi bi-people"></i>
                    <div>
                        <span class="rsvp-info-lbl"><?= __('team_meeting.attendees','Attendees') ?></span>
                        <span class="rsvp-info-val" id="rsvpAttendees"></span>
                    </div>
                </div>
                <div class="rsvp-info-cell rsvp-info-full" id="rsvpLocCell" style="display:none">
                    <i class="bi bi-geo-alt-fill"></i>
                    <div>
                        <span class="rsvp-info-lbl"><?= __('team_meeting.location','Location') ?></span>
                        <span class="rsvp-info-val" id="rsvpLocation"></span>
                    </div>
                </div>
            </div>

            <!-- Description -->
            <div class="rsvp-desc-block" id="rsvpDescBlock" style="display:none"></div>

            <hr class="rsvp-modal-divider">

            <!-- Current status -->
            <div class="rsvp-current-wrap">
                <span class="rsvp-current-label"><?= __('team_meeting.your_response','Your response:') ?></span>
                <span id="rsvpCurrentChip"></span>
            </div>

            <!-- Response buttons -->
            <div class="rsvp-resp-wrap">
                <div class="rsvp-resp-label"><?= __('team_meeting.change_response','Change your response') ?></div>
                <div class="rsvp-resp-row">
                    <button type="button" class="rsvp-resp-btn rsvp-btn-accept  modal-rsvp-action" data-rsvp="accepted">
                        <i class="bi bi-calendar-check-fill"></i>
                        <span><?= __('team_meeting.rsvp_accepted','Accept') ?></span>
                    </button>
                    <button type="button" class="rsvp-resp-btn rsvp-btn-decline modal-rsvp-action" data-rsvp="declined">
                        <i class="bi bi-calendar-x-fill"></i>
                        <span><?= __('team_meeting.rsvp_declined','Decline') ?></span>
                    </button>
                    <button type="button" class="rsvp-resp-btn rsvp-btn-maybe  modal-rsvp-action" data-rsvp="pending">
                        <i class="bi bi-hourglass-split"></i>
                        <span><?= __('team_meeting.rsvp_pending','Maybe') ?></span>
                    </button>
                </div>
            </div>

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


<script>
const CSRF = <?= json_encode($csrfToken) ?>;

/* ── Search ── */
document.getElementById('searchMeetings').addEventListener('input', function () {
    const q = this.value.toLowerCase();
    document.querySelectorAll('.meeting-row').forEach(r => {
        r.style.display = r.dataset.title.includes(q) ? '' : 'none';
    });
});

/* ── RSVP config ── */
const rsvpLabels = {
    accepted: { color: 'success',   icon: 'bi-calendar-check-fill', label: '<?= addslashes(__('team_meeting.rsvp_accepted','Accepted')) ?>' },
    declined: { color: 'danger',    icon: 'bi-calendar-x-fill',     label: '<?= addslashes(__('team_meeting.rsvp_declined','Declined')) ?>' },
    pending:  { color: 'secondary', icon: 'bi-hourglass-split',      label: '<?= addslashes(__('team_meeting.rsvp_pending','Pending'))  ?>' },
};
const bsColorMap = {
    primary: 'var(--bs-primary,#0d6efd)', secondary: 'var(--bs-secondary,#6c757d)',
    success: 'var(--bs-success,#198754)', danger: 'var(--bs-danger,#dc3545)',
    warning: 'var(--bs-warning,#ffc107)', info: 'var(--bs-info,#0dcaf0)',
};

/* ── RSVP Modal open ── */
let _rsvpMeetingId  = null;
let _rsvpTriggerBtn = null;
let _rsvpModal      = null;

document.querySelectorAll('.btn-rsvp-respond').forEach(btn => {
    btn.addEventListener('click', function () {
        _rsvpMeetingId  = this.dataset.id;
        _rsvpTriggerBtn = this;
        const d = this.dataset;
        const rsvp     = d.rsvp || 'pending';
        const rsvpCfg  = rsvpLabels[rsvp] || rsvpLabels.pending;
        const tColor   = bsColorMap[d.typeColor] || bsColorMap.primary;
        const tColorRaw= d.typeColor || 'primary';

        // Top bar color
        document.getElementById('rsvpTopBar').style.background = tColor;

        // Icon
        const iconEl = document.getElementById('rsvpModalIcon');
        iconEl.style.background = `rgba(var(--bs-${tColorRaw}-rgb),.12)`;
        iconEl.style.color = tColor;
        iconEl.innerHTML = `<i class="bi ${d.typeIcon || 'bi-calendar-event-fill'}"></i>`;

        // Title + type badge
        document.getElementById('rsvpModalTitle').textContent = d.title || '';
        const tb = document.getElementById('rsvpTypeBadge');
        tb.className = `rsvp-modal-type-badge`;
        tb.style.background = `rgba(var(--bs-${tColorRaw}-rgb),.12)`;
        tb.style.color = tColor;
        tb.textContent = d.typeLabel || '';

        // Meta values
        document.getElementById('rsvpDate').textContent      = d.date || '—';
        document.getElementById('rsvpTime').textContent      = d.time || '—';
        document.getElementById('rsvpDuration').textContent  = (d.duration || '?') + ' <?= addslashes(__('team_comm.minutes','min')) ?>';
        document.getElementById('rsvpAttendees').textContent =
            (d.attendees || '0') + ' <?= addslashes(__('team_meeting.total','total')) ?>'
            + (parseInt(d.accepted) > 0 ? ' · ' + d.accepted + ' ✓' : '');

        // Location
        const locCell = document.getElementById('rsvpLocCell');
        if (d.location) { document.getElementById('rsvpLocation').textContent = d.location; locCell.style.display = ''; }
        else locCell.style.display = 'none';

        // Description
        const descBlock = document.getElementById('rsvpDescBlock');
        if (d.description) { descBlock.textContent = d.description; descBlock.style.display = ''; }
        else descBlock.style.display = 'none';

        // Current status chip
        const chip = document.getElementById('rsvpCurrentChip');
        chip.className = `rsvp-status-chip rsvp-chip-${rsvp}`;
        chip.innerHTML = `<i class="bi ${rsvpCfg.icon}"></i>${rsvpCfg.label}`;

        // Highlight active response button
        document.querySelectorAll('.modal-rsvp-action').forEach(b => {
            b.classList.toggle('rsvp-active', b.dataset.rsvp === rsvp);
        });

        if (!_rsvpModal) _rsvpModal = new bootstrap.Modal(document.getElementById('rsvpModal'));
        _rsvpModal.show();
    });
});

/* ── RSVP Modal respond ── */
document.querySelectorAll('.modal-rsvp-action').forEach(btn => {
    btn.addEventListener('click', function () {
        if (!_rsvpMeetingId) return;
        const rsvp = this.dataset.rsvp;
        _rsvpModal?.hide();

        // Optimistic UI
        if (_rsvpTriggerBtn) {
            const cfg  = rsvpLabels[rsvp] || rsvpLabels.pending;
            const row  = _rsvpTriggerBtn.closest('tr');
            const chip = row?.querySelector('.rsvp-status-chip');
            if (chip) {
                chip.className = `rsvp-status-chip rsvp-chip-${rsvp}`;
                chip.innerHTML = `<i class="bi ${cfg.icon}"></i>${cfg.label}`;
            }
            _rsvpTriggerBtn.dataset.rsvp = rsvp;
        }

        fetch(`/admin/team/meetings/rsvp/${_rsvpMeetingId}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `_csrf=${encodeURIComponent(CSRF)}&rsvp=${rsvp}`
        })
        .then(r => r.json())
        .then(d => { if (!d.success) location.reload(); })
        .catch(() => location.reload());
    });
});

/* ── Complete Meeting (manager) ── */
<?php if ($isManager): ?>
document.querySelectorAll('.btn-complete-meeting').forEach(btn => {
    btn.addEventListener('click', function () {
        if (!confirm('<?= addslashes(__('team_meeting.confirm_complete','End this meeting now?')) ?>')) return;
        fetch(`/admin/team/meetings/complete/${this.dataset.id}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `_csrf=${encodeURIComponent(CSRF)}`
        }).then(r => r.json()).then(d => { if (d.success) location.reload(); });
    });
});

/* ── Delete Meeting (manager) ── */
document.querySelectorAll('.btn-del-meeting').forEach(btn => {
    btn.addEventListener('click', function () {
        if (!confirm('<?= addslashes(__('team_meeting.confirm_delete','Delete this meeting?')) ?>')) return;
        const id = this.dataset.id;
        fetch(`/admin/team/meetings/delete/${id}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `_csrf=${encodeURIComponent(CSRF)}`
        })
        .then(r => r.json())
        .then(d => { if (d.success) this.closest('tr').remove(); });
    });
});
<?php endif; ?>
</script>

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