<?php
require_once 'auth.php';
require_once 'db.php';
requireLogin($conn);

$user_email = $_SESSION['email'] ?? '';
$user_id = (int) ($_SESSION['user_id'] ?? 0);
$role = $_SESSION['role'] ?? 'user';
$user_fullname = $_SESSION['fullname'] ?? 'Pengguna';
$user_department = currentUserDepartment($conn);

$flash_msg = '';
$flash_type = '';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create_meeting') {
        $title = trim((string) ($_POST['title'] ?? ''));
        $category = strtolower(trim((string) ($_POST['category'] ?? 'meeting')));
        $category = ($category === 'kursus') ? 'kursus' : 'meeting';
        $location = trim((string) ($_POST['location'] ?? ''));
        $date = trim((string) ($_POST['date'] ?? date('Y-m-d')));
        $start_time = trim((string) ($_POST['start_time'] ?? '09:00'));
        $end_time = trim((string) ($_POST['end_time'] ?? '11:00'));
        $notes = trim((string) ($_POST['notes'] ?? ''));

        $participants_arr = isset($_POST['participants']) && is_array($_POST['participants']) ? $_POST['participants'] : [];
        $ext_participants = trim((string) ($_POST['ext_participants'] ?? ''));
        if ($ext_participants !== '') {
            $exts = array_map('trim', explode(',', $ext_participants));
            $participants_arr = array_merge($participants_arr, $exts);
        }
        $participants_json = json_encode(array_values(array_filter($participants_arr)), JSON_UNESCAPED_UNICODE);

        if ($title !== '') {
            $start_at = "$date $start_time:00";
            $end_at = "$date $end_time:00";

            $stmt = mysqli_prepare(
                $conn,
                "INSERT INTO calendar_events
                    (user_id, event_type, title, description, location, start_at, end_at, priority, status, participants, created_by, updated_by)
                 VALUES (?, ?, ?, ?, ?, ?, ?, 'Normal', 'Scheduled', ?, ?, ?)"
            );

            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'isssssssii', $user_id, $category, $title, $notes, $location, $start_at, $end_at, $participants_json, $user_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $doc_label = ($category === 'kursus') ? 'Kursus / Latihan' : 'Mesyuarat';
                    $flash_msg = "$doc_label berjaya dijadualkan!";
                    $flash_type = 'success';
                }
            }
        }
    } elseif ($action === 'update_meeting') {
        $event_id = (int) ($_POST['event_id'] ?? 0);
        $title = trim((string) ($_POST['title'] ?? ''));
        $category = strtolower(trim((string) ($_POST['category'] ?? 'meeting')));
        $category = ($category === 'kursus') ? 'kursus' : 'meeting';
        $location = trim((string) ($_POST['location'] ?? ''));
        $date = trim((string) ($_POST['date'] ?? date('Y-m-d')));
        $start_time = trim((string) ($_POST['start_time'] ?? '09:00'));
        $end_time = trim((string) ($_POST['end_time'] ?? '11:00'));
        $notes = trim((string) ($_POST['notes'] ?? ''));

        $participants_arr = isset($_POST['participants']) && is_array($_POST['participants']) ? $_POST['participants'] : [];
        $ext_participants = trim((string) ($_POST['ext_participants'] ?? ''));
        if ($ext_participants !== '') {
            $exts = array_map('trim', explode(',', $ext_participants));
            $participants_arr = array_merge($participants_arr, $exts);
        }
        $participants_json = json_encode(array_values(array_filter($participants_arr)), JSON_UNESCAPED_UNICODE);

        if ($event_id > 0 && $title !== '') {
            $start_at = "$date $start_time:00";
            $end_at = "$date $end_time:00";

            $stmt = mysqli_prepare(
                $conn,
                "UPDATE calendar_events
                 SET event_type = ?, title = ?, description = ?, location = ?, start_at = ?, end_at = ?, participants = ?, updated_by = ?, updated_at = NOW()
                 WHERE id = ? AND user_id = ?"
            );

            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'sssssssiii', $category, $title, $notes, $location, $start_at, $end_at, $participants_json, $user_id, $event_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $doc_label = ($category === 'kursus') ? 'Kursus / Latihan' : 'Mesyuarat';
                    $flash_msg = "Maklumat $doc_label berjaya dikemaskini!";
                    $flash_type = 'success';
                }
            }
        }
    } elseif ($action === 'delete_meeting') {
        $event_id = (int) ($_POST['event_id'] ?? 0);
        if ($event_id > 0) {
            $stmt = mysqli_prepare(conn: $conn, query: "DELETE FROM calendar_events WHERE id = ? AND user_id = ? AND (event_type = 'meeting' OR event_type = 'kursus')");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'ii', $event_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = 'Aktiviti berjaya dipadam.';
                    $flash_type = 'success';
                }
            }
        }
    }
}

// Fetch user meetings & kursus ONLY
$sql = "SELECT * FROM calendar_events WHERE user_id = ? AND (event_type = 'meeting' OR event_type = 'kursus') AND deleted_at IS NULL ORDER BY start_at ASC";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'i', $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$meetings = $result ? mysqli_fetch_all($result, MYSQLI_ASSOC) : [];

$upcoming_meetings = [];
$today_meetings = [];
$past_meetings = [];

$today_str = date('Y-m-d');
$now_ts = time();

foreach ($meetings as $m) {
    $event_start_date = date('Y-m-d', strtotime($m['start_at']));
    $event_end_ts = strtotime($m['end_at'] ?: $m['start_at']);

    if ($event_start_date === $today_str) {
        $today_meetings[] = $m;
    } elseif ($event_end_ts < $now_ts) {
        $past_meetings[] = $m;
    } else {
        $upcoming_meetings[] = $m;
    }
}

$total_meetings = count($meetings);

// Fetch department colleagues for participant picker
$dept_members = [];
if ($user_department !== '') {
    $dm_stmt = mysqli_prepare($conn, "SELECT id, fullname, short_name, email, position FROM users WHERE LOWER(TRIM(department)) = LOWER(TRIM(?)) AND status = 'approved' AND id <> ? ORDER BY fullname ASC");
    if ($dm_stmt) {
        mysqli_stmt_bind_param($dm_stmt, 'si', $user_department, $user_id);
        mysqli_stmt_execute($dm_stmt);
        $dm_res = mysqli_stmt_get_result($dm_stmt);
        $dept_members = $dm_res ? mysqli_fetch_all($dm_res, MYSQLI_ASSOC) : [];
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Meeting & Kursus | MAINPP WORKSPACE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <?php if (function_exists('renderAppShellAssets')) { renderAppShellAssets(); } ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --accent-teal: #0d9488; --deep-blue: #023e5f;
            --bg-light: rgba(245, 250, 253, 0.85); --bg-card: rgba(255, 255, 255, 0.78);
            --text-main: #163447; --text-muted: #486581; --border: rgba(255, 255, 255, 0.55);
            --sidebar-width: 280px;
            --success: #10b981; --danger: #ef4444; --warning: #f59e0b; --info: #3b82f6; --purple: #8b5cf6;
            --glass: rgba(255, 255, 255, 0.65);
            --glass-strong: rgba(255, 255, 255, 0.88);
            --shadow-soft: 0 16px 40px rgba(2, 62, 95, 0.08);
            --shadow-card: 0 10px 30px rgba(2, 62, 95, 0.06);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
        body {
            min-height: 100vh; display: flex; color: var(--text-main);
            background: linear-gradient(135deg, rgba(240, 249, 255, 0.95), rgba(224, 242, 254, 0.85)),
                        url('assets/auth-bg.png') center/cover no-repeat fixed;
            overflow-x: hidden;
        }

        .sidebar {
            width: var(--sidebar-width) !important;
            background: linear-gradient(180deg, rgba(2, 62, 95, 0.96), rgba(0, 119, 182, 0.88)) !important;
            border-right: 1px solid rgba(255, 255, 255, 0.22) !important;
            position: fixed; height: 100vh; padding: 20px 0 !important;
            overflow-y: auto; z-index: 1000; box-shadow: 18px 0 44px rgba(2, 38, 60, 0.20);
            transition: width 0.3s ease; display: flex; flex-direction: column;
            backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
        }
        .sidebar.collapsed { width: 70px !important; }
        .sidebar-header {
            text-align: center; padding: 0 20px 20px !important;
            border-bottom: 1px solid rgba(255, 255, 255, 0.16) !important; margin-bottom: 20px !important;
            background: transparent !important;
        }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none !important; }
        .sidebar-header img { width: 54px !important; margin: 0 auto 10px !important; filter: drop-shadow(0 10px 18px rgba(0,0,0,0.25)); }
        .sidebar-menu { list-style: none; padding: 0 10px !important; display: flex; flex-direction: column; flex: 1; }
        .sidebar-section { padding: 10px 18px 6px !important; color: rgba(255,255,255,0.58) !important; font-size: 0.72rem !important; font-weight: 800 !important; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: rgba(255,255,255,0.88) !important; text-decoration: none; border-radius: 10px; margin-bottom: 5px; transition: all 0.2s ease; font-size: 0.9rem; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: rgba(255,255,255,0.18) !important; color: #fff !important; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-toggle { position: absolute !important; right: 10px !important; top: 18px !important; width: 28px !important; height: 28px !important; background: rgba(255,255,255,0.20) !important; color: #fff !important; border: 1px solid rgba(255,255,255,0.28) !important; border-radius: 50% !important; cursor: pointer !important; display: flex !important; align-items: center !important; justify-content: center !important; font-size: 0.75rem !important; transition: transform 0.3s ease !important; z-index: 1300 !important; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg) !important; }
        .sidebar.collapsed + .main { margin-left: 70px !important; }

        .main {
            position: relative; z-index: 1; margin-left: var(--sidebar-width); flex: 1; padding: 28px 32px; transition: margin-left 0.3s ease;
        }

        /* Top Bar matching dashboard */
        .top-bar {
            background: var(--glass); padding: 18px 24px; border-radius: 18px;
            box-shadow: var(--shadow-soft); margin-bottom: 18px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border);
            backdrop-filter: blur(22px) saturate(1.25); -webkit-backdrop-filter: blur(22px) saturate(1.25);
        }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }

        /* Master Mode Switcher Bar */
        .view-mode-bar {
            background: var(--glass-strong); padding: 12px 20px; border-radius: 20px;
            box-shadow: var(--shadow-soft); margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border);
            backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); flex-wrap: wrap; gap: 14px;
        }
        .view-toggle-pills {
            display: flex; align-items: center; background: rgba(0, 119, 182, 0.08); padding: 4px; border-radius: 14px; gap: 4px;
        }
        .view-pill-btn {
            border: none; background: transparent; padding: 8px 18px; border-radius: 10px;
            font-size: 0.84rem; font-weight: 800; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease;
            display: flex; align-items: center; gap: 8px;
        }
        .view-pill-btn.active {
            background: #fff; color: var(--deep-blue); box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }
        .btn-add-meeting {
            background: linear-gradient(135deg, #0284c7, #0369a1);
            color: #fff; border: none; padding: 10px 22px; border-radius: 14px;
            font-weight: 800; font-size: 0.88rem; display: flex; align-items: center; gap: 8px;
            cursor: pointer; box-shadow: 0 8px 20px rgba(2, 132, 199, 0.30); transition: all 0.2s ease;
        }
        .btn-add-meeting:hover { transform: translateY(-2px); box-shadow: 0 12px 25px rgba(2, 132, 199, 0.40); }

        /* KPI Cards Grid */
        .meet-kpi-grid {
            display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; margin-bottom: 20px;
        }
        .meet-kpi-card {
            background: var(--glass-strong); border-radius: 20px; border: 1px solid var(--border);
            padding: 18px 20px; box-shadow: var(--shadow-card); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px);
            display: flex; align-items: center; gap: 16px;
        }
        .kpi-icon-box {
            width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center;
            font-size: 1.3rem; flex-shrink: 0;
        }
        .kpi-upcoming { background: #e0f2fe; color: #0284c7; }
        .kpi-today { background: #e0e7ff; color: #4338ca; }
        .kpi-past { background: #f1f5f9; color: #64748b; }
        .kpi-info h4 { font-size: 0.76rem; font-weight: 750; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; }
        .kpi-info .kpi-number { font-size: 1.5rem; font-weight: 850; color: var(--deep-blue); line-height: 1.1; margin-top: 2px; }

        /* Timeline Navigation Tabs */
        .timeline-tabs-container {
            display: flex; gap: 8px; margin-bottom: 20px; background: var(--glass-strong); padding: 6px; border-radius: 16px;
            border: 1px solid var(--border); width: fit-content;
        }
        .timeline-tab-btn {
            border: none; background: transparent; padding: 10px 22px; border-radius: 12px;
            font-size: 0.85rem; font-weight: 800; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease;
            display: flex; align-items: center; gap: 8px;
        }
        .timeline-tab-btn.active {
            background: var(--deep-blue); color: #fff; box-shadow: 0 4px 14px rgba(2, 62, 95, 0.20);
        }

        /* Toolbar */
        .meet-toolbar {
            background: var(--glass-strong); padding: 12px 18px; border-radius: 16px; border: 1px solid var(--border);
            margin-bottom: 22px; display: flex; justify-content: space-between; align-items: center; gap: 14px; flex-wrap: wrap;
        }
        .meet-search-box {
            display: flex; align-items: center; gap: 10px; background: #fff; padding: 8px 16px; border-radius: 12px;
            border: 1px solid rgba(0, 119, 182, 0.18); flex: 1; min-width: 240px;
        }
        .meet-search-box input { border: none; outline: none; width: 100%; font-size: 0.85rem; color: var(--text-main); font-weight: 600; }
        .category-filter-pills { display: flex; gap: 6px; align-items: center; }
        .cat-pill-btn {
            border: 1px solid rgba(0, 119, 182, 0.16); background: #fff; padding: 6px 14px; border-radius: 10px;
            font-size: 0.76rem; font-weight: 800; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease;
        }
        .cat-pill-btn.active { background: var(--deep-blue); color: #fff; border-color: var(--deep-blue); }

        /* World Class Meeting Cards */
        .meet-grid-container {
            display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px;
        }
        .world-meet-card {
            background: #fff; border-radius: 20px; border: 1px solid rgba(0, 119, 182, 0.12);
            padding: 20px; box-shadow: var(--shadow-card); display: flex; flex-direction: column; gap: 12px;
            position: relative; transition: all 0.25s ease;
        }
        .world-meet-card:hover { transform: translateY(-3px); box-shadow: 0 18px 38px rgba(2, 62, 95, 0.10); }

        .meet-badge-cat {
            font-size: 0.72rem; font-weight: 850; padding: 4px 12px; border-radius: 999px; text-transform: uppercase;
        }
        .cat-badge-mesyuarat { background: #e0f2fe; color: #0284c7; border: 1px solid #bae6fd; }
        .cat-badge-kursus { background: #faf5ff; color: #9333ea; border: 1px solid #e9d5ff; }

        .meet-card-title { font-size: 1.08rem; font-weight: 850; color: var(--deep-blue); line-height: 1.35; }
        .meet-meta-pill {
            display: inline-flex; align-items: center; gap: 8px; font-size: 0.82rem; font-weight: 750; color: #334155;
            background: #f8fafc; padding: 6px 12px; border-radius: 10px; border: 1px solid #e2e8f0; width: fit-content;
        }
        .meet-location-row {
            display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap;
        }
        .btn-join-virtual {
            background: linear-gradient(135deg, #0d9488, #0f766e); color: #fff; text-decoration: none;
            padding: 6px 14px; border-radius: 10px; font-size: 0.76rem; font-weight: 850;
            display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 4px 12px rgba(13, 148, 136, 0.25);
            transition: all 0.2s ease;
        }
        .btn-join-virtual:hover { transform: translateY(-1px); color: #fff; box-shadow: 0 6px 16px rgba(13, 148, 136, 0.35); }

        .participants-row {
            display: flex; flex-wrap: wrap; gap: 6px; margin-top: 2px;
        }
        .participant-tag {
            font-size: 0.72rem; font-weight: 750; padding: 3px 8px; border-radius: 6px;
            background: rgba(0, 119, 182, 0.08); color: var(--primary-dark); display: inline-flex; align-items: center; gap: 4px;
        }

        .meet-notes-box {
            font-size: 0.82rem; color: #475569; background: #f8fafc; padding: 10px 14px;
            border-radius: 12px; line-height: 1.45; border: 1px solid rgba(0,0,0,0.04);
        }

        .meet-bottom-actions {
            margin-top: auto; padding-top: 14px; border-top: 1px solid rgba(0, 119, 182, 0.08);
            display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap;
        }
        .btn-edit-meet-action {
            background: rgba(0, 119, 182, 0.08); color: var(--primary); border: 1px solid rgba(0, 119, 182, 0.18);
            padding: 8px 14px; border-radius: 10px; font-size: 0.78rem; font-weight: 800; cursor: pointer; transition: all 0.2s ease;
            display: inline-flex; align-items: center; gap: 5px;
        }
        .btn-edit-meet-action:hover { background: var(--primary); color: #fff; }

        /* Calendar */
        .calendar-app-card {
            background: #fff; border-radius: 24px; border: 1px solid rgba(0, 119, 182, 0.12);
            padding: 24px 28px; box-shadow: var(--shadow-soft); margin-bottom: 24px;
        }
        .cal-header-row {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 22px; flex-wrap: wrap; gap: 14px;
        }
        .cal-title-nav { display: flex; align-items: center; gap: 16px; }
        .cal-title-month { font-size: 1.45rem; font-weight: 850; color: var(--deep-blue); }
        .cal-arrows { display: flex; align-items: center; gap: 6px; }
        .cal-arrow-btn {
            width: 32px; height: 32px; border-radius: 9px; border: 1px solid rgba(0, 119, 182, 0.16); background: #fff;
            display: flex; align-items: center; justify-content: center; color: var(--deep-blue); cursor: pointer; transition: all 0.2s ease;
        }
        .cal-arrow-btn:hover { background: var(--primary); color: #fff; }
        .btn-cal-today {
            padding: 6px 14px; border-radius: 9px; font-weight: 750; font-size: 0.8rem; background: #fff; border: 1px solid rgba(0, 119, 182, 0.20); color: var(--deep-blue); cursor: pointer;
        }
        .btn-cal-today:hover { background: var(--deep-blue); color: #fff; }

        .cal-week-board {
            display: flex; flex-direction: column; border: 1px solid rgba(0, 119, 182, 0.12); border-radius: 18px; overflow: hidden; background: #fff;
        }
        .cal-week-head {
            display: grid; grid-template-columns: 75px repeat(7, 1fr);
            background: #fafcff; border-bottom: 1px solid rgba(0, 119, 182, 0.12);
        }
        .cal-head-col {
            padding: 14px 6px; text-align: center; font-size: 0.82rem; font-weight: 800; color: var(--deep-blue);
            border-left: 1px solid rgba(0, 119, 182, 0.08); display: flex; flex-direction: column; gap: 2px;
        }
        .cal-head-col.active-day { background: #f0fdf4; color: #166534; }
        .cal-head-col.active-day span::after { content: " •"; color: #10b981; }
        
        .cal-week-body { max-height: 580px; overflow-y: auto; position: relative; }
        .cal-hour-row {
            display: grid; grid-template-columns: 75px repeat(7, 1fr);
            height: 72px; min-height: 72px; border-bottom: 1px solid rgba(0, 119, 182, 0.08); position: relative;
        }
        .cal-hour-time-label {
            font-size: 0.72rem; font-weight: 700; color: var(--text-muted);
            display: flex; align-items: flex-start; justify-content: center; padding-top: 6px;
        }
        .cal-day-cell {
            border-left: 1px solid rgba(0, 119, 182, 0.08); padding: 4px; position: relative; height: 100%;
        }

        .cal-meeting-card {
            border-radius: 14px; padding: 10px 12px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.05); border: 1px solid rgba(0, 0, 0, 0.05);
            display: flex; flex-direction: column; gap: 4px; overflow: hidden;
            transition: all 0.2s ease; cursor: pointer;
        }
        .cal-meeting-card:hover { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(0,0,0,0.12); z-index: 40 !important; }
        .meeting-theme-mesyuarat { background: #e0f2fe; border-top: 3px solid #0284c7; }
        .meeting-theme-kursus { background: #faf5ff; border-top: 3px solid #9333ea; }

        /* Modal */
        .modal-overlay {
            position: fixed; inset: 0; background: rgba(2, 62, 95, 0.50); backdrop-filter: blur(8px);
            display: none; align-items: center; justify-content: center; z-index: 2000;
        }
        .modal-overlay.active { display: flex; }
        .modal-card {
            background: #fff; border-radius: 24px; width: 100%; max-width: 560px;
            box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden; animation: modalPop 0.25s ease;
            max-height: 90vh; display: flex; flex-direction: column;
        }
        @keyframes modalPop { from { transform: scale(0.92); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .modal-header { padding: 20px 24px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(0,119,182,0.12); }
        .modal-header h3 { font-size: 1.15rem; font-weight: 850; color: var(--deep-blue); display: flex; align-items: center; gap: 8px; }
        .modal-body { padding: 22px 24px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; }
        .form-group { display: flex; flex-direction: column; gap: 6px; }
        .form-group label { font-size: 0.82rem; font-weight: 750; color: var(--deep-blue); }
        .form-control {
            padding: 10px 14px; border-radius: 12px; border: 1px solid rgba(0, 119, 182, 0.20);
            font-size: 0.88rem; outline: none; background: rgba(240, 249, 255, 0.40);
        }
        .form-control:focus { background: #fff; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(0, 119, 182, 0.12); }

        .type-selector-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .type-card-opt {
            border: 2px solid rgba(0,119,182,0.15); border-radius: 16px; padding: 14px 16px;
            cursor: pointer; display: flex; align-items: center; gap: 12px; transition: all 0.2s ease;
            background: #fff;
        }
        .type-card-opt.active {
            border-color: #0284c7; background: rgba(2, 132, 199, 0.06); box-shadow: 0 4px 14px rgba(2, 132, 199, 0.15);
        }
        .type-icon-box {
            width: 38px; height: 38px; border-radius: 10px; display: flex; align-items: center; justify-content: center;
            font-size: 1.1rem;
        }
        .type-card-opt.active .type-icon-box { background: #0284c7; color: #fff; }
        .type-card-opt:not(.active) .type-icon-box { background: #f1f5f9; color: #64748b; }

        .modal-footer { padding: 16px 24px 22px; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid rgba(0,119,182,0.08); }
        .btn-save { background: linear-gradient(135deg, #0284c7, #0369a1); color: #fff; border: none; padding: 10px 24px; border-radius: 12px; font-weight: 800; cursor: pointer; }
    </style>
</head>
<body class="role-<?php echo htmlspecialchars($role); ?>">

    <!-- Sidebar matching Dashboard -->
    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu">
            <i class="fas fa-chevron-left"></i>
        </button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'my_meeting.php'); ?>
        </ul>
    </aside>

    <!-- Main Workspace -->
    <main class="main">

        <!-- Top Bar matching Dashboard -->
        <div class="top-bar">
            <h2><i class="fa-solid fa-handshake"></i> My Meeting & Kursus</h2>
            <?php renderTopBarUserMenu($conn, $role, 'my_meeting.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Modul Peribadi', 'url' => '#'],
            ['label' => 'My Meeting & Kursus', 'url' => 'my_meeting.php', 'current' => true]
        ]);
        ?>

        <!-- Master View Switcher & Add Button -->
        <div class="view-mode-bar">
            <div class="view-toggle-pills">
                <button class="view-pill-btn active" id="btnMeetList" onclick="switchMeetMasterView('list')">
                    <i class="fa-solid fa-list"></i>
                    <span>Senarai Mesyuarat / Kursus (<?php echo $total_meetings; ?>)</span>
                </button>
                <button class="view-pill-btn" id="btnMeetCalendar" onclick="switchMeetMasterView('calendar')">
                    <i class="fa-solid fa-calendar-days"></i>
                    <span>Paparan Kalendar</span>
                </button>
            </div>

            <button class="btn-add-meeting" onclick="openAddMeetingModal()">
                <i class="fa-solid fa-plus"></i>
                <span>+ Tambah Meeting / Kursus</span>
            </button>
        </div>

        <?php if (!empty($flash_msg)): ?>
            <div style="background: <?php echo $flash_type === 'success' ? '#ecfdf5' : '#fef2f2'; ?>; color: <?php echo $flash_type === 'success' ? '#065f46' : '#991b1b'; ?>; padding: 14px 20px; border-radius: 14px; margin-bottom: 20px; border: 1px solid <?php echo $flash_type === 'success' ? '#a7f3d0' : '#fecaca'; ?>; display: flex; align-items: center; gap: 10px; font-weight: 600;">
                <i class="fa-solid <?php echo $flash_type === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation'; ?>"></i>
                <span><?php echo htmlspecialchars($flash_msg); ?></span>
            </div>
        <?php endif; ?>

        <!-- ================= VIEW 1: LIST & TIMELINE SECTION ================= -->
        <div id="meetListSection">
            
            <!-- KPI Hero Cards Grid -->
            <div class="meet-kpi-grid">
                <div class="meet-kpi-card">
                    <div class="kpi-icon-box kpi-upcoming"><i class="fa-solid fa-calendar-plus"></i></div>
                    <div class="kpi-info">
                        <h4>Akan Datang</h4>
                        <div class="kpi-number"><?php echo count($upcoming_meetings); ?></div>
                    </div>
                </div>

                <div class="meet-kpi-card">
                    <div class="kpi-icon-box kpi-today"><i class="fa-solid fa-video"></i></div>
                    <div class="kpi-info">
                        <h4>Hari Ini</h4>
                        <div class="kpi-number"><?php echo count($today_meetings); ?></div>
                    </div>
                </div>

                <div class="meet-kpi-card">
                    <div class="kpi-icon-box kpi-past"><i class="fa-solid fa-calendar-check"></i></div>
                    <div class="kpi-info">
                        <h4>Selesai / Lepas</h4>
                        <div class="kpi-number"><?php echo count($past_meetings); ?></div>
                    </div>
                </div>
            </div>

            <!-- Timeline Navigation Tabs (Akan Datang, Hari Ini, Lepas) -->
            <div class="timeline-tabs-container">
                <button class="timeline-tab-btn active" data-timeline="upcoming" onclick="selectMeetTimeline('upcoming')">
                    <i class="fa-solid fa-clock"></i>
                    <span>Akan Datang (<?php echo count($upcoming_meetings); ?>)</span>
                </button>
                <button class="timeline-tab-btn" data-timeline="today" onclick="selectMeetTimeline('today')">
                    <i class="fa-solid fa-bullseye"></i>
                    <span>Hari Ini (<?php echo count($today_meetings); ?>)</span>
                </button>
                <button class="timeline-tab-btn" data-timeline="past" onclick="selectMeetTimeline('past')">
                    <i class="fa-solid fa-history"></i>
                    <span>Selesai / Lepas (<?php echo count($past_meetings); ?>)</span>
                </button>
            </div>

            <!-- Search & Category Filter Toolbar -->
            <div class="meet-toolbar">
                <div class="meet-search-box">
                    <i class="fa-solid fa-magnifying-glass text-muted"></i>
                    <input type="text" id="meetSearchInput" placeholder="Cari tajuk mesyuarat, tempat, atau agenda..." onkeyup="filterMeetingsLive()">
                </div>

                <div class="category-filter-pills">
                    <span style="font-size: 0.76rem; font-weight: 800; color: var(--deep-blue); margin-right: 4px;">Kategori:</span>
                    <button class="cat-pill-btn active" data-cat="all" onclick="filterMeetCategory('all', this)">Semua</button>
                    <button class="cat-pill-btn" data-cat="meeting" onclick="filterMeetCategory('meeting', this)"><i class="fa-solid fa-video mr-1"></i> Mesyuarat</button>
                    <button class="cat-pill-btn" data-cat="kursus" onclick="filterMeetCategory('kursus', this)"><i class="fa-solid fa-graduation-cap mr-1"></i> Kursus</button>
                </div>
            </div>

            <!-- Timeline Sections Rendering -->
            <?php
            $renderMeetTimelineGrid = function($timeline_name, $records, $is_active) {
            ?>
                <div class="meet-timeline-grid" id="meettimeline_<?php echo $timeline_name; ?>" style="<?php echo $is_active ? '' : 'display: none;'; ?>">
                    <?php if (empty($records)): ?>
                        <div style="text-align: center; padding: 48px 20px; background: var(--glass-strong); border-radius: 20px; border: 1px solid var(--border);">
                            <i class="fa-solid fa-handshake" style="font-size: 3.2rem; color: var(--primary); opacity: 0.35; margin-bottom: 12px;"></i>
                            <h3 style="font-size: 1.1rem; font-weight: 800; color: var(--deep-blue);">Tiada Mesyuarat / Kursus Pada Garis Masa Ini</h3>
                            <p style="font-size: 0.85rem; color: var(--text-muted); margin-top: 4px;">Klik "+ Tambah Meeting / Kursus" untuk menjadualkan sesi baharu.</p>
                        </div>
                    <?php else: ?>
                        <div class="meet-grid-container">
                            <?php foreach ($records as $m): 
                                $cat = strtolower($m['event_type'] ?? 'meeting');
                                $is_kursus = ($cat === 'kursus');
                                $cat_key = $is_kursus ? 'kursus' : 'meeting';

                                $loc = $m['location'] ?? '';
                                $is_virtual = (preg_match('/(https?:\/\/|meet\.google\.com|zoom\.us|teams\.microsoft)/i', $loc));
                                $virtual_url = $is_virtual ? (preg_match('/https?:\/\/[^\s]+/i', $loc, $matches) ? $matches[0] : (str_starts_with($loc, 'http') ? $loc : "https://$loc")) : '';

                                $participants_json = $m['participants'] ?? '[]';
                                $participants = json_decode($participants_json, true) ?: [];
                            ?>
                                <div class="world-meet-card" data-cat="<?php echo $cat_key; ?>" data-title="<?php echo htmlspecialchars(strtolower($m['title'] . ' ' . $loc . ' ' . $m['description'])); ?>">
                                    <div style="display: flex; justify-content: space-between; align-items: center;">
                                        <span class="meet-badge-cat <?php echo $is_kursus ? 'cat-badge-kursus' : 'cat-badge-mesyuarat'; ?>">
                                            <i class="fa-solid <?php echo $is_kursus ? 'fa-graduation-cap' : 'fa-video'; ?> mr-1"></i>
                                            <?php echo $is_kursus ? 'Kursus / Latihan' : 'Mesyuarat'; ?>
                                        </span>
                                        <span style="font-size: 0.75rem; font-weight: 800; color: var(--primary);">
                                            <i class="fa-regular fa-clock mr-1"></i> Dijadualkan
                                        </span>
                                    </div>

                                    <div class="meet-card-title"><?php echo htmlspecialchars($m['title']); ?></div>

                                    <div class="meet-meta-pill">
                                        <i class="fa-regular fa-calendar-days text-primary"></i>
                                        <span><?php echo date('d M Y (l)', strtotime($m['start_at'])); ?> • <?php echo date('h:i A', strtotime($m['start_at'])) . ' - ' . date('h:i A', strtotime($m['end_at'])); ?></span>
                                    </div>

                                    <?php if (!empty($loc)): ?>
                                        <div class="meet-location-row">
                                            <div style="display: flex; align-items: center; gap: 6px; font-size: 0.82rem; font-weight: 750; color: #475569;">
                                                <i class="fa-solid fa-location-dot text-danger"></i>
                                                <span><?php echo htmlspecialchars($loc); ?></span>
                                            </div>
                                            <?php if ($is_virtual && $virtual_url !== ''): ?>
                                                <a href="<?php echo htmlspecialchars($virtual_url); ?>" target="_blank" class="btn-join-virtual">
                                                    <i class="fa-solid fa-video"></i> Sertai Maya
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>

                                    <?php if (!empty($participants)): ?>
                                        <div class="participants-row">
                                            <?php foreach ($participants as $p_name): ?>
                                                <span class="participant-tag">
                                                    <i class="fa-solid fa-user-check"></i> <?php echo htmlspecialchars($p_name); ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>

                                    <?php if (!empty($m['description'])): ?>
                                        <div class="meet-notes-box"><?php echo htmlspecialchars($m['description']); ?></div>
                                    <?php endif; ?>

                                    <div class="meet-bottom-actions">
                                        <button type="button" class="btn-edit-meet-action" onclick='openEditMeetingModal(<?php echo json_encode($m, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); ?>)'>
                                            <i class="fa-regular fa-pen-to-square"></i> Edit
                                        </button>

                                        <form action="my_meeting.php" method="POST" onsubmit="return confirm('Adakah anda pasti mahu memadam aktiviti ini?');" style="margin: 0;">
                                            <input type="hidden" name="action" value="delete_meeting">
                                            <input type="hidden" name="event_id" value="<?php echo $m['id']; ?>">
                                            <button type="submit" style="background: none; border: none; color: #dc2626; cursor: pointer; font-size: 0.95rem;" title="Padam Aktiviti">
                                                <i class="fa-solid fa-trash-can"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php
            };
            $renderMeetTimelineGrid('upcoming', $upcoming_meetings, true);
            $renderMeetTimelineGrid('today', $today_meetings, false);
            $renderMeetTimelineGrid('past', $past_meetings, false);
            ?>

        </div>

        <!-- ================= VIEW 2: MODERN CALENDAR SECTION ================= -->
        <div id="meetCalendarSection" class="calendar-app-card" style="display: none;">
            <div class="cal-header-row">
                <div class="cal-title-nav">
                    <div class="cal-title-month" id="meetCalMonthTitle">Ogos 2026</div>
                    <div class="cal-arrows">
                        <button class="cal-arrow-btn" onclick="prevMeetWeek()"><i class="fa-solid fa-chevron-left"></i></button>
                        <button class="cal-arrow-btn" onclick="nextMeetWeek()"><i class="fa-solid fa-chevron-right"></i></button>
                        <button class="btn-cal-today" onclick="goToTodayMeet()">Hari Ini</button>
                    </div>
                </div>

                <div style="font-size: 0.82rem; font-weight: 750; color: var(--text-muted);">
                    <i class="fa-solid fa-shield-halved text-primary mr-1"></i> Klik mana-mana kad untuk edit detail
                </div>
            </div>

            <div class="cal-week-board">
                <div class="cal-week-head" id="meetWeekHeaderRow">
                    <div style="padding: 14px 6px; text-align: center; font-size: 0.78rem; font-weight: 800; color: var(--text-muted);">Masa</div>
                </div>
                <div class="cal-week-body">
                    <?php for ($hour = 7; $hour <= 18; $hour++): 
                        $time_str = sprintf('%02d:00', $hour);
                        $display_time = date('g a', strtotime("$time_str"));
                    ?>
                        <div class="cal-hour-row" data-hour="<?php echo $hour; ?>">
                            <div class="cal-hour-time-label"><?php echo $display_time; ?></div>
                            <?php for ($d = 0; $d < 7; $d++): ?>
                                <div class="cal-day-cell" data-day-index="<?php echo $d; ?>" data-hour="<?php echo $hour; ?>"></div>
                            <?php endfor; ?>
                        </div>
                    <?php endfor; ?>
                </div>
            </div>
        </div>

    </main>

    <!-- Modal 1: + Tambah Meeting / Kursus -->
    <div class="modal-overlay" id="addMeetingModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3><i class="fa-solid fa-handshake text-primary mr-2"></i> Tambah Meeting / Kursus</h3>
                    <p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Jadualkan sesi perbincangan atau latihan.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeAddMeetingModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form action="my_meeting.php" method="POST">
                <input type="hidden" name="action" value="create_meeting">
                <input type="hidden" name="category" id="meetingCategoryInput" value="meeting">

                <div class="modal-body">
                    <div class="type-selector-grid">
                        <div class="type-card-opt active" id="optMeeting" onclick="selectMeetingCat('meeting', 'create')">
                            <div class="type-icon-box"><i class="fa-solid fa-video"></i></div>
                            <div>
                                <strong>Mesyuarat</strong>
                                <span style="font-size: 0.72rem; color: var(--text-muted);">Perbincangan</span>
                            </div>
                        </div>
                        <div class="type-card-opt" id="optKursus" onclick="selectMeetingCat('kursus', 'create')">
                            <div class="type-icon-box"><i class="fa-solid fa-graduation-cap"></i></div>
                            <div>
                                <strong>Kursus / Latihan</strong>
                                <span style="font-size: 0.72rem; color: var(--text-muted);">Pembangunan Diri</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Tajuk *</label>
                        <input type="text" name="title" class="form-control" placeholder="Contoh: Mesyuarat Penyelarasan Sistem" required>
                    </div>

                    <div class="form-group">
                        <label>Tarikh *</label>
                        <input type="date" name="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Masa Mula</label>
                            <input type="time" name="start_time" class="form-control" value="09:00">
                        </div>
                        <div class="form-group">
                            <label>Masa Tamat</label>
                            <input type="time" name="end_time" class="form-control" value="11:00">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Lokasi / Pautan Maya (Google Meet / Zoom URL)</label>
                        <input type="text" name="location" class="form-control" placeholder="Contoh: Bilik Mesyuarat Utama / https://meet.google.com/xyz">
                    </div>

                    <?php if (!empty($dept_members)): ?>
                        <div class="form-group">
                            <label>Pilih Peserta Bahagian</label>
                            <div style="max-height: 120px; overflow-y: auto; border: 1px solid rgba(0,119,182,0.15); border-radius: 12px; padding: 8px 12px; background: rgba(240, 249, 255, 0.40); display: flex; flex-direction: column; gap: 6px;">
                                <?php foreach ($dept_members as $dm): ?>
                                    <label style="display: flex; align-items: center; gap: 8px; font-size: 0.8rem; cursor: pointer;">
                                        <input type="checkbox" name="participants[]" value="<?php echo htmlspecialchars($dm['fullname']); ?>" style="accent-color: var(--primary);">
                                        <span><?php echo htmlspecialchars($dm['fullname']); ?> (<?php echo htmlspecialchars($dm['position'] ?: 'Staf'); ?>)</span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label>Peserta Luar (Pilihan)</label>
                        <input type="text" name="ext_participants" class="form-control" placeholder="Contoh: En. Ahmad (JPS), Pn. Sarah (BKE)">
                    </div>

                    <div class="form-group">
                        <label>Catatan / Agenda</label>
                        <textarea name="notes" class="form-control" rows="3" placeholder="Masukkan agenda atau maklumat sesi..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-status-reopen" style="padding: 10px 18px;" onclick="closeAddMeetingModal()">Batal</button>
                    <button type="submit" class="btn-save">SIMPAN MEETING / KURSUS</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal 2: ✏️ Edit Meeting / Kursus Modal -->
    <div class="modal-overlay" id="editMeetingModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3><i class="fa-solid fa-pen-to-square text-primary mr-2"></i> Kemaskini Mesyuarat / Kursus</h3>
                    <p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Ubah maklumat dan peserta sesi.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeEditMeetingModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form action="my_meeting.php" method="POST">
                <input type="hidden" name="action" value="update_meeting">
                <input type="hidden" name="event_id" id="editMeetId">
                <input type="hidden" name="category" id="editMeetingCategoryInput" value="meeting">

                <div class="modal-body">
                    <div class="type-selector-grid">
                        <div class="type-card-opt" id="editOptMeeting" onclick="selectMeetingCat('meeting', 'edit')">
                            <div class="type-icon-box"><i class="fa-solid fa-video"></i></div>
                            <div>
                                <strong>Mesyuarat</strong>
                                <span style="font-size: 0.72rem; color: var(--text-muted);">Perbincangan</span>
                            </div>
                        </div>
                        <div class="type-card-opt" id="editOptKursus" onclick="selectMeetingCat('kursus', 'edit')">
                            <div class="type-icon-box"><i class="fa-solid fa-graduation-cap"></i></div>
                            <div>
                                <strong>Kursus / Latihan</strong>
                                <span style="font-size: 0.72rem; color: var(--text-muted);">Pembangunan Diri</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Tajuk *</label>
                        <input type="text" name="title" id="editMeetTitle" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Tarikh *</label>
                        <input type="date" name="date" id="editMeetDate" class="form-control" required>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Masa Mula</label>
                            <input type="time" name="start_time" id="editMeetStartTime" class="form-control" value="09:00">
                        </div>
                        <div class="form-group">
                            <label>Masa Tamat</label>
                            <input type="time" name="end_time" id="editMeetEndTime" class="form-control" value="11:00">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Lokasi / Pautan Maya (Google Meet / Zoom URL)</label>
                        <input type="text" name="location" id="editMeetLocation" class="form-control">
                    </div>

                    <div class="form-group">
                        <label>Catatan / Agenda</label>
                        <textarea name="notes" id="editMeetNotes" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-status-reopen" style="padding: 10px 18px;" onclick="closeEditMeetingModal()">Batal</button>
                    <button type="submit" class="btn-save">SIMPAN PERUBAHAN</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const myMeetings = <?php echo json_encode($meetings, JSON_UNESCAPED_UNICODE); ?>;
        let calCurrentMeetDate = new Date();
        let currentMeetTimeline = 'upcoming';
        let currentMeetCategory = 'all';

        function switchMeetMasterView(mode) {
            document.getElementById('btnMeetList').classList.toggle('active', mode === 'list');
            document.getElementById('btnMeetCalendar').classList.toggle('active', mode === 'calendar');
            document.getElementById('meetListSection').style.display = (mode === 'list') ? 'block' : 'none';
            document.getElementById('meetCalendarSection').style.display = (mode === 'calendar') ? 'block' : 'none';
            if (mode === 'calendar') {
                renderMeetCalendarWeek();
            }
        }

        function selectMeetTimeline(timeline) {
            currentMeetTimeline = timeline;
            document.querySelectorAll('.timeline-tab-btn').forEach(btn => {
                btn.classList.toggle('active', btn.getAttribute('data-timeline') === timeline);
            });

            document.querySelectorAll('.meet-timeline-grid').forEach(grid => {
                grid.style.display = (grid.id === `meettimeline_${timeline}`) ? 'block' : 'none';
            });

            filterMeetingsLive();
        }

        function filterMeetCategory(cat, btn) {
            currentMeetCategory = cat;
            document.querySelectorAll('.cat-pill-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            filterMeetingsLive();
        }

        function filterMeetingsLive() {
            const query = document.getElementById('meetSearchInput').value.toLowerCase().trim();
            const activeGrid = document.getElementById(`meettimeline_${currentMeetTimeline}`);
            if (!activeGrid) return;

            const cards = activeGrid.querySelectorAll('.world-meet-card');
            cards.forEach(card => {
                const cardCat = card.getAttribute('data-cat') || '';
                const cardText = card.getAttribute('data-title') || '';

                const matchesCat = (currentMeetCategory === 'all' || cardCat === currentMeetCategory);
                const matchesQuery = (query === '' || cardText.includes(query));

                card.style.display = (matchesCat && matchesQuery) ? 'flex' : 'none';
            });
        }

        function renderMeetCalendarWeek() {
            const headerRow = document.getElementById('meetWeekHeaderRow');
            const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
            const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            
            document.getElementById('meetCalMonthTitle').innerText = `${monthNames[calCurrentMeetDate.getMonth()]} ${calCurrentMeetDate.getFullYear()}`;

            const currentDayOfWeek = calCurrentMeetDate.getDay();
            const sunday = new Date(calCurrentMeetDate);
            sunday.setDate(calCurrentMeetDate.getDate() - currentDayOfWeek);

            const existingHeaders = headerRow.querySelectorAll('.cal-head-col');
            existingHeaders.forEach(h => h.remove());

            const today = new Date();

            for (let i = 0; i < 7; i++) {
                const d = new Date(sunday);
                d.setDate(sunday.getDate() + i);

                const isToday = d.toDateString() === today.toDateString();
                const colHeader = document.createElement('div');
                colHeader.className = `cal-head-col ${isToday ? 'active-day' : ''}`;
                colHeader.innerHTML = `
                    <span style="font-size: 0.72rem; color: var(--text-muted);">${dayNames[i]} ${d.getDate()}</span>
                `;
                headerRow.appendChild(colHeader);
            }

            const cells = document.querySelectorAll('.cal-day-cell');
            cells.forEach(cell => {
                cell.innerHTML = '';
                const dayIndex = parseInt(cell.getAttribute('data-day-index'));
                const hour = parseInt(cell.getAttribute('data-hour'));

                const targetDate = new Date(sunday);
                targetDate.setDate(sunday.getDate() + dayIndex);
                const targetDateStr = `${targetDate.getFullYear()}-${String(targetDate.getMonth()+1).padStart(2,'0')}-${String(targetDate.getDate()).padStart(2,'0')}`;

                const matchingMeets = myMeetings.filter(m => {
                    if (!m.start_at || !m.start_at.startsWith(targetDateStr)) return false;
                    const mHour = new Date(m.start_at).getHours();
                    return mHour === hour;
                });

                matchingMeets.forEach((m) => {
                    const isKursus = (m.event_type || 'meeting').toLowerCase() === 'kursus';

                    const startDate = new Date(m.start_at);
                    const endDate = m.end_at ? new Date(m.end_at) : new Date(startDate.getTime() + 60*60*1000);

                    const formatShortTime = (d) => {
                        let h = d.getHours();
                        let m = d.getMinutes();
                        const ampm = h >= 12 ? 'pm' : 'am';
                        h = h % 12 || 12;
                        return m > 0 ? `${h}.${String(m).padStart(2,'0')}${ampm}` : `${h}${ampm}`;
                    };

                    const timeRange = `${formatShortTime(startDate)} - ${formatShortTime(endDate)}`;
                    const themeClass = isKursus ? 'meeting-theme-kursus' : 'meeting-theme-mesyuarat';
                    const tagLabel = isKursus ? 'Kursus' : (m.location || 'Mesyuarat');

                    const diffMs = endDate.getTime() - startDate.getTime();
                    const durationHours = Math.max(0.8, diffMs / (1000 * 60 * 60));
                    const slotHeight = 72;
                    const cardHeight = Math.max(60, Math.round(durationHours * slotHeight) - 8);

                    const card = document.createElement('div');
                    card.className = `cal-meeting-card ${themeClass}`;
                    card.style.height = `${cardHeight}px`;
                    card.style.position = 'relative';
                    card.style.zIndex = '15';
                    card.onclick = () => openEditMeetingModal(m);
                    card.innerHTML = `
                        <div style="font-size: 0.7rem; font-weight: 750; color: #0284c7;">${timeRange}</div>
                        <div style="font-size: 0.84rem; font-weight: 850; color: #1e293b; line-height: 1.25;">${escapeHtml(m.title)}</div>
                        <div style="margin-top: auto; display: inline-flex; align-items: center; gap: 5px; background: rgba(255,255,255,0.9); padding: 3px 8px; border-radius: 6px; font-size: 0.68rem; font-weight: 800; color: #475569; width: fit-content;">
                            <span>${escapeHtml(tagLabel)}</span>
                        </div>
                    `;
                    cell.appendChild(card);
                });
            });
        }

        function prevMeetWeek() {
            calCurrentMeetDate.setDate(calCurrentMeetDate.getDate() - 7);
            renderMeetCalendarWeek();
        }

        function nextMeetWeek() {
            calCurrentMeetDate.setDate(calCurrentMeetDate.getDate() + 7);
            renderMeetCalendarWeek();
        }

        function goToTodayMeet() {
            calCurrentMeetDate = new Date();
            renderMeetCalendarWeek();
        }

        function selectMeetingCat(cat, mode) {
            const isEdit = (mode === 'edit');
            const catInput = document.getElementById(isEdit ? 'editMeetingCategoryInput' : 'meetingCategoryInput');
            catInput.value = cat;

            const isMeeting = (cat === 'meeting');
            document.getElementById(isEdit ? 'editOptMeeting' : 'optMeeting').classList.toggle('active', isMeeting);
            document.getElementById(isEdit ? 'editOptKursus' : 'optKursus').classList.toggle('active', !isMeeting);
        }

        function openAddMeetingModal() {
            document.getElementById('addMeetingModal').classList.add('active');
        }
        function closeAddMeetingModal() {
            document.getElementById('addMeetingModal').classList.remove('active');
        }

        function openEditMeetingModal(m) {
            document.getElementById('editMeetId').value = m.id || '';
            const cat = (m.event_type || 'meeting').toLowerCase() === 'kursus' ? 'kursus' : 'meeting';
            selectMeetingCat(cat, 'edit');

            document.getElementById('editMeetTitle').value = m.title || '';
            if (m.start_at) {
                document.getElementById('editMeetDate').value = m.start_at.substring(0, 10);
                document.getElementById('editMeetStartTime').value = m.start_at.substring(11, 16);
            }
            if (m.end_at) {
                document.getElementById('editMeetEndTime').value = m.end_at.substring(11, 16);
            }
            document.getElementById('editMeetLocation').value = m.location || '';
            document.getElementById('editMeetNotes').value = m.description || '';

            document.getElementById('editMeetingModal').classList.add('active');
        }

        function closeEditMeetingModal() {
            document.getElementById('editMeetingModal').classList.remove('active');
        }

        function escapeHtml(text) {
            if (!text) return '';
            return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }

        document.addEventListener('DOMContentLoaded', () => {
            selectMeetTimeline('upcoming');
        });

        // Sidebar behavior
        const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn && sidebar) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992 && sidebar) sidebar.classList.add('collapsed');

        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
    </script>
</body>
</html>
