<?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);

$selected_member_id = isset($_GET['member_id']) ? (int)$_GET['member_id'] : 0;
$selected_type = isset($_GET['type']) ? trim((string)$_GET['type']) : 'all';
$start_date_param = isset($_GET['start_date']) ? trim((string)$_GET['start_date']) : '';
$end_date_param = isset($_GET['end_date']) ? trim((string)$_GET['end_date']) : '';

// Fetch all members in same department
$members = [];
if ($user_department !== '') {
    $m_stmt = mysqli_prepare($conn, "SELECT id, fullname, short_name, email, department, position, role, profile_photo FROM users WHERE LOWER(TRIM(department)) = LOWER(TRIM(?)) AND status = 'approved' ORDER BY fullname ASC");
    if ($m_stmt) {
        mysqli_stmt_bind_param($m_stmt, 's', $user_department);
        mysqli_stmt_execute($m_stmt);
        $m_res = mysqli_stmt_get_result($m_stmt);
        $members = $m_res ? mysqli_fetch_all($m_res, MYSQLI_ASSOC) : [];
    }
}

// Map member details by ID
$member_map = [];
foreach ($members as $m) {
    $member_map[(int)$m['id']] = $m;
}

// Query schedule events for department members
$events = [];
if (!empty($members)) {
    $member_ids = array_keys($member_map);
    if ($selected_member_id > 0 && isset($member_map[$selected_member_id])) {
        $target_ids = [$selected_member_id];
    } else {
        $target_ids = $member_ids;
    }

    $placeholders = implode(',', array_fill(0, count($target_ids), '?'));
    $types = str_repeat('i', count($target_ids));

    $sql = "SELECT c.*, u.fullname, u.short_name, u.position, u.role
            FROM calendar_events c 
            JOIN users u ON u.id = c.user_id 
            WHERE c.user_id IN ($placeholders)";

    $params = $target_ids;

    if ($selected_type !== 'all' && $selected_type !== '') {
        if ($selected_type === 'leave' || $selected_type === 'cuti') {
            $sql .= " AND (c.event_type = 'leave' OR c.event_type = 'cuti')";
        } elseif ($selected_type === 'time_off' || $selected_type === 'timeoff') {
            $sql .= " AND (c.event_type = 'time_off' OR c.event_type = 'timeoff')";
        } else {
            $sql .= " AND c.event_type = ?";
            $types .= 's';
            $params[] = $selected_type;
        }
    }

    if (!empty($start_date_param)) {
        $sql .= " AND DATE(c.start_at) >= ?";
        $types .= 's';
        $params[] = $start_date_param;
    }

    if (!empty($end_date_param)) {
        $sql .= " AND DATE(c.start_at) <= ?";
        $types .= 's';
        $params[] = $end_date_param;
    }

    $sql .= " AND (c.deleted_at IS NULL) ORDER BY c.start_at ASC";

    $stmt = mysqli_prepare($conn, $sql);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, $types, ...$params);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $events = $result ? mysqli_fetch_all($result, MYSQLI_ASSOC) : [];
    }
}

$total_members = count($members);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Team Schedule | 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); }

        /* Top Header */
        .top-navbar {
            background: var(--glass-strong); padding: 18px 28px; border-radius: 20px;
            box-shadow: var(--shadow-soft); margin-bottom: 24px; 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: 16px;
        }
        .dept-title-box h2 {
            font-size: 1.35rem; font-weight: 850; color: var(--deep-blue); display: flex; align-items: center; gap: 10px;
        }
        .dept-title-box p {
            font-size: 0.82rem; font-weight: 600; color: var(--text-muted); margin-top: 2px;
        }

        /* Member Filter Avatar Scroll Bar */
        .member-filter-bar {
            background: var(--glass-strong); border-radius: 20px; border: 1px solid var(--border);
            padding: 14px 20px; box-shadow: var(--shadow-card); margin-bottom: 24px;
            display: flex; align-items: center; gap: 12px; overflow-x: auto;
        }
        .member-pill-btn {
            display: flex; align-items: center; gap: 8px; padding: 6px 14px; border-radius: 999px;
            background: rgba(0, 119, 182, 0.08); border: 1px solid rgba(0, 119, 182, 0.15);
            color: var(--deep-blue); font-size: 0.82rem; font-weight: 750; text-decoration: none;
            white-space: nowrap; transition: all 0.2s ease;
        }
        .member-pill-btn:hover, .member-pill-btn.active {
            background: var(--primary); color: #fff; border-color: var(--primary);
            box-shadow: 0 4px 12px rgba(0, 119, 182, 0.25);
        }
        .member-avatar-mini {
            width: 24px; height: 24px; border-radius: 50%; background: #e0f2fe; color: #0284c7;
            display: flex; align-items: center; justify-content: center; font-size: 0.72rem; font-weight: 800;
        }
        .member-pill-btn.active .member-avatar-mini {
            background: #fff; color: var(--primary);
        }

        /* Calendar & Team Matrix Card */
        .matrix-card {
            background: var(--glass-strong); border-radius: 24px; border: 1px solid var(--border);
            padding: 24px 28px; box-shadow: var(--shadow-card);
            backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
        }

        .matrix-controls-bar {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 14px;
        }
        .cal-nav-arrows { display: flex; align-items: center; gap: 6px; }
        .cal-nav-btn {
            width: 34px; height: 34px; border-radius: 10px; 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-nav-btn:hover { background: var(--primary); color: #fff; }
        .btn-today-pill {
            padding: 6px 14px; border-radius: 10px; font-weight: 750; font-size: 0.82rem; background: #fff; border: 1px solid rgba(0, 119, 182, 0.20); color: var(--deep-blue); cursor: pointer; transition: all 0.2s ease;
        }
        .btn-today-pill:hover { background: var(--deep-blue); color: #fff; }

        /* Filter Type Tabs */
        .type-tabs {
            display: flex; align-items: center; background: rgba(0, 119, 182, 0.08); padding: 4px; border-radius: 12px; gap: 4px; flex-wrap: wrap;
        }
        .type-tab {
            padding: 6px 14px; border-radius: 9px; font-size: 0.8rem; font-weight: 750; text-decoration: none;
            color: var(--text-muted); transition: all 0.2s ease;
        }
        .type-tab.active {
            background: #fff; color: var(--deep-blue); box-shadow: 0 4px 10px rgba(0,0,0,0.06);
        }

        /* Interactive Week Grid */
        .team-week-grid {
            display: flex; flex-direction: column; border: 1px solid rgba(0, 119, 182, 0.14);
            border-radius: 16px; overflow: hidden; background: #fff;
        }
        .week-header-row {
            display: grid; grid-template-columns: 80px repeat(7, 1fr);
            background: rgba(240, 249, 255, 0.85); border-bottom: 1px solid rgba(0, 119, 182, 0.14);
        }
        .week-time-label-col { padding: 12px 8px; text-align: center; font-size: 0.78rem; font-weight: 750; color: var(--text-muted); }
        .week-day-col-header {
            padding: 12px 8px; text-align: center; font-size: 0.82rem; font-weight: 800; color: var(--deep-blue);
            border-left: 1px solid rgba(0, 119, 182, 0.10); display: flex; flex-direction: column; gap: 2px;
        }
        .week-day-col-header.active-day {
            background: #ecfdf5; color: #047857;
        }
        .week-day-col-header.active-day::before {
            content: "●"; font-size: 0.7rem; color: #10b981; margin-right: 4px;
        }
        .week-body-scroll { max-height: 560px; overflow-y: auto; position: relative; }
        .week-time-row {
            display: grid; grid-template-columns: 80px repeat(7, 1fr);
            height: 70px; min-height: 70px; border-bottom: 1px solid rgba(0, 119, 182, 0.08); position: relative;
        }
        .week-time-slot {
            font-size: 0.75rem; font-weight: 700; color: var(--text-muted);
            display: flex; align-items: flex-start; justify-content: center; padding-top: 6px;
        }
        .week-day-slot { border-left: 1px solid rgba(0, 119, 182, 0.08); padding: 4px; position: relative; height: 100%; }

        /* Dynamic Spanning Event Card */
        .team-event-card {
            background: #fff; border-radius: 12px; padding: 8px 10px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.06); border: 1px solid rgba(0, 119, 182, 0.16);
            display: flex; flex-direction: column; gap: 4px; overflow: hidden;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        .team-event-card:hover {
            transform: translateY(-2px); box-shadow: 0 8px 20px rgba(0,0,0,0.12); z-index: 50 !important;
        }
        .team-event-card.border-meeting { border-left: 4px solid #0284c7; background: #f0f9ff; }
        .team-event-card.border-kursus { border-left: 4px solid #9333ea; background: #faf5ff; }
        .team-event-card.border-leave { border-left: 4px solid #d97706; background: #fffbeb; }
        .team-event-card.border-timeoff { border-left: 4px solid #4338ca; background: #eef2ff; }
        .team-event-card.border-task { border-left: 4px solid #0d9488; background: #f0fdfa; }
        
        .team-card-top { display: flex; align-items: center; gap: 6px; }
        .card-avatar {
            width: 20px; height: 20px; border-radius: 50%; background: #e0f2fe; color: #0284c7;
            font-size: 0.65rem; font-weight: 800; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
        }
        .card-author-name { font-size: 0.72rem; font-weight: 750; color: var(--text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .team-card-title { font-size: 0.8rem; font-weight: 800; color: var(--deep-blue); line-height: 1.2; }
        .team-card-time { font-size: 0.7rem; font-weight: 600; color: var(--text-muted); margin-top: auto; }
    </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_team_schedule.php'); ?>
        </ul>
    </aside>

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

        <!-- Top Bar matching Dashboard -->
        <div class="top-bar">
            <h2><i class="fa-solid fa-calendar-week"></i> My Team Schedule</h2>
            <?php renderTopBarUserMenu($conn, $role, 'my_team_schedule.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Modul Pasukan Saya', 'url' => '#'],
            ['label' => 'My Team Schedule', 'url' => 'my_team_schedule.php', 'current' => true]
        ]);
        ?>

        <!-- Department Sub-Header -->
        <div class="top-navbar">
            <div class="dept-title-box">
                <h2>
                    <i class="fa-solid fa-users text-primary"></i>
                    <span>Jadual Pasukan: <?php echo htmlspecialchars($user_department !== '' ? $user_department : 'Semua Bahagian'); ?></span>
                </h2>
                <p>Memantau ketersediaan, mesyuarat, kursus, time off, dan cuti seluruh anggota bahagian (<?php echo $total_members; ?> Ahli Berdaftar).</p>
            </div>

            <div style="display: flex; align-items: center; gap: 12px;">
                <a href="my_schedule.php" class="member-pill-btn" style="padding: 8px 18px;">
                    <i class="fa-regular fa-calendar text-primary"></i>
                    <span>Jadual Saya</span>
                </a>
            </div>
        </div>

        <!-- Member Filter Pill Bar -->
        <div class="member-filter-bar">
            <span style="font-size: 0.82rem; font-weight: 800; color: var(--deep-blue); margin-right: 4px;">Pilih Ahli:</span>
            <a href="my_team_schedule.php?type=<?php echo urlencode($selected_type); ?>" class="member-pill-btn <?php echo $selected_member_id === 0 ? 'active' : ''; ?>">
                <i class="fa-solid fa-users"></i>
                <span>Semua Ahli (<?php echo $total_members; ?>)</span>
            </a>
            <?php foreach ($members as $mem): 
                $initial = strtoupper(substr($mem['fullname'], 0, 1));
                $is_active = $selected_member_id === (int)$mem['id'];
            ?>
                <a href="my_team_schedule.php?member_id=<?php echo $mem['id']; ?>&type=<?php echo urlencode($selected_type); ?>" class="member-pill-btn <?php echo $is_active ? 'active' : ''; ?>">
                    <span class="member-avatar-mini"><?php echo $initial; ?></span>
                    <span><?php echo htmlspecialchars($mem['short_name'] ?: $mem['fullname']); ?></span>
                </a>
            <?php endforeach; ?>
        </div>

        <!-- Main Matrix Calendar Card -->
        <div class="matrix-card">

            <div class="matrix-controls-bar">
                <div style="display: flex; align-items: center; gap: 14px;">
                    <span id="calCurrentMonthLabel" style="font-size: 1.35rem; font-weight: 850; color: var(--deep-blue);"><?php echo date('F Y'); ?></span>
                    <div class="cal-nav-arrows">
                        <button class="cal-nav-btn" onclick="prevWeek()"><i class="fa-solid fa-chevron-left"></i></button>
                        <button class="cal-nav-btn" onclick="nextWeek()"><i class="fa-solid fa-chevron-right"></i></button>
                        <button class="btn-today-pill" onclick="goToToday()">Hari Ini</button>
                    </div>
                </div>

                <!-- Event Type Filter Tabs -->
                <div class="type-tabs">
                    <a href="my_team_schedule.php?member_id=<?php echo $selected_member_id; ?>&type=all" class="type-tab <?php echo $selected_type === 'all' ? 'active' : ''; ?>">Semua</a>
                    <a href="my_team_schedule.php?member_id=<?php echo $selected_member_id; ?>&type=meeting" class="type-tab <?php echo $selected_type === 'meeting' ? 'active' : ''; ?>">Mesyuarat</a>
                    <a href="my_team_schedule.php?member_id=<?php echo $selected_member_id; ?>&type=kursus" class="type-tab <?php echo $selected_type === 'kursus' ? 'active' : ''; ?>">Kursus</a>
                    <a href="my_team_schedule.php?member_id=<?php echo $selected_member_id; ?>&type=leave" class="type-tab <?php echo ($selected_type === 'leave' || $selected_type === 'cuti') ? 'active' : ''; ?>">Cuti</a>
                    <a href="my_team_schedule.php?member_id=<?php echo $selected_member_id; ?>&type=time_off" class="type-tab <?php echo ($selected_type === 'time_off' || $selected_type === 'timeoff') ? 'active' : ''; ?>">Time Off</a>
                    <a href="my_team_schedule.php?member_id=<?php echo $selected_member_id; ?>&type=task" class="type-tab <?php echo $selected_type === 'task' ? 'active' : ''; ?>">Tugasan</a>
                </div>
            </div>

            <!-- Team Week Time-Grid -->
            <div class="team-week-grid" id="teamWeekGrid">
                <div class="week-header-row" id="teamWeekHeaderRow">
                    <div class="week-time-label-col">Masa</div>
                    <!-- Day headers generated via JS -->
                </div>
                <div class="week-body-scroll">
                    <!-- 08:00 to 18:00 rows -->
                    <?php for ($hour = 8; $hour <= 18; $hour++): 
                        $time_str = sprintf('%02d:00', $hour);
                        $display_time = date('h:i A', strtotime("$time_str"));
                    ?>
                        <div class="week-time-row" data-hour="<?php echo $hour; ?>">
                            <div class="week-time-slot"><?php echo $display_time; ?></div>
                            <?php for ($d = 0; $d < 7; $d++): ?>
                                <div class="week-day-slot" data-day-index="<?php echo $d; ?>" data-hour="<?php echo $hour; ?>"></div>
                            <?php endfor; ?>
                        </div>
                    <?php endfor; ?>
                </div>
            </div>

        </div>

    </main>

    <script>
        const teamEvents = <?php echo json_encode($events, JSON_UNESCAPED_UNICODE); ?>;
        let currentDate = new Date();

        function renderTeamWeek() {
            const headerRow = document.getElementById('teamWeekHeaderRow');
            const dayNames = ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu"];
            const monthNames = ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"];
            
            document.getElementById('calCurrentMonthLabel').innerText = `${monthNames[currentDate.getMonth()]} ${currentDate.getFullYear()}`;

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

            // Clean previous headers
            const existingHeaders = headerRow.querySelectorAll('.week-day-col-header');
            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 = `week-day-col-header ${isToday ? 'active-day' : ''}`;
                colHeader.innerHTML = `
                    <span>${dayNames[i]}</span>
                    <strong style="font-size: 1.05rem;">${d.getDate()}</strong>
                `;
                headerRow.appendChild(colHeader);
            }

            // Populate Slots
            const slots = document.querySelectorAll('.week-day-slot');
            slots.forEach(slot => {
                slot.innerHTML = '';
                const dayIndex = parseInt(slot.getAttribute('data-day-index'));
                const hour = parseInt(slot.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 matchingEvents = teamEvents.filter(ev => {
                    if (!ev.start_at || !ev.start_at.startsWith(targetDateStr)) return false;
                    const evHour = new Date(ev.start_at).getHours();
                    return evHour === hour;
                });

                matchingEvents.forEach(ev => {
                    const type = (ev.event_type || 'meeting').toLowerCase();
                    let borderClass = 'border-meeting';
                    if (type === 'kursus') borderClass = 'border-kursus';
                    else if (type === 'leave' || type === 'cuti') borderClass = 'border-leave';
                    else if (type === 'time_off' || type === 'timeoff') borderClass = 'border-timeoff';
                    else if (type === 'task') borderClass = 'border-task';

                    const startDate = new Date(ev.start_at);
                    const endDate = ev.end_at ? new Date(ev.end_at) : new Date(startDate.getTime() + 60 * 60 * 1000);
                    
                    const formatTimeStr = (d) => {
                        let h = d.getHours();
                        let m = d.getMinutes();
                        const ampm = h >= 12 ? 'PM' : 'AM';
                        h = h % 12;
                        h = h ? h : 12;
                        return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')} ${ampm}`;
                    };

                    const startTime = formatTimeStr(startDate);
                    const endTime = formatTimeStr(endDate);
                    const timeDisplay = (ev.end_at && ev.end_at !== ev.start_at) ? `${startTime} - ${endTime}` : startTime;

                    const initial = (ev.short_name || ev.fullname || 'P').charAt(0).toUpperCase();

                    // Calculate duration in hours to span card height across the grid rows!
                    const diffMs = endDate.getTime() - startDate.getTime();
                    const durationHours = Math.max(0.75, diffMs / (1000 * 60 * 60));
                    const slotHeight = 70; // 70px per hour row
                    const cardHeight = Math.max(56, Math.round(durationHours * slotHeight) - 8);

                    const card = document.createElement('div');
                    card.className = `team-event-card ${borderClass}`;
                    card.style.height = `${cardHeight}px`;
                    card.style.position = 'relative';
                    card.style.zIndex = '10';
                    card.innerHTML = `
                        <div class="team-card-top">
                            <span class="card-avatar">${initial}</span>
                            <span class="card-author-name">${escapeHtml(ev.short_name || ev.fullname)}</span>
                        </div>
                        <div class="team-card-title">${escapeHtml(ev.title)}</div>
                        <div class="team-card-time"><i class="fa-regular fa-clock mr-1"></i> ${timeDisplay}</div>
                    `;
                    slot.appendChild(card);
                });
            });
        }

        function prevWeek() {
            currentDate.setDate(currentDate.getDate() - 7);
            renderTeamWeek();
        }

        function nextWeek() {
            currentDate.setDate(currentDate.getDate() + 7);
            renderTeamWeek();
        }

        function goToToday() {
            currentDate = new Date();
            renderTeamWeek();
        }

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

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

        // 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>
