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

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

$member_ids = array_map(fn($m) => (int)$m['id'], $members);
$total_members = count($members);

// Fetch department tasks for calendar and stats
$team_tasks = [];
if (!empty($member_ids)) {
    $placeholders = implode(',', array_fill(0, count($member_ids), '?'));
    $types = str_repeat('i', count($member_ids));
    $t_sql = "SELECT c.*, u.fullname, u.short_name, u.position, u.profile_photo AS avatar_url 
              FROM calendar_events c 
              JOIN users u ON c.user_id = u.id 
              WHERE c.user_id IN ($placeholders) 
                AND c.event_type = 'task' 
                AND c.deleted_at IS NULL 
              ORDER BY c.start_at DESC";
    $t_stmt = mysqli_prepare($conn, $t_sql);
    if ($t_stmt) {
        mysqli_stmt_bind_param($t_stmt, $types, ...$member_ids);
        mysqli_stmt_execute($t_stmt);
        $t_res = mysqli_stmt_get_result($t_stmt);
        $team_tasks = $t_res ? mysqli_fetch_all($t_res, MYSQLI_ASSOC) : [];
    }
}

// Fetch active events today to determine real-time availability status
$today_events = [];
if (!empty($member_ids)) {
    $placeholders = implode(',', array_fill(0, count($member_ids), '?'));
    $types = str_repeat('i', count($member_ids));
    $e_sql = "SELECT user_id, event_type, title, start_at, end_at FROM calendar_events 
              WHERE user_id IN ($placeholders) 
                AND DATE(start_at) <= CURDATE() AND DATE(end_at) >= CURDATE()
                AND deleted_at IS NULL";
    $e_stmt = mysqli_prepare($conn, $e_sql);
    if ($e_stmt) {
        mysqli_stmt_bind_param($e_stmt, $types, ...$member_ids);
        mysqli_stmt_execute($e_stmt);
        $e_res = mysqli_stmt_get_result($e_stmt);
        $today_events = $e_res ? mysqli_fetch_all($e_res, MYSQLI_ASSOC) : [];
    }
}

$status_by_user = [];
$current_time_ts = time();

foreach ($today_events as $ev) {
    $uid = (int)$ev['user_id'];
    $type = strtolower(trim((string)$ev['event_type']));
    $start_ts = !empty($ev['start_at']) ? strtotime($ev['start_at']) : 0;
    $end_ts = !empty($ev['end_at']) ? strtotime($ev['end_at']) : $start_ts;

    // 1. Cuti Rehat (Full day event for today)
    if ($type === 'leave' || $type === 'cuti') {
        $status_by_user[$uid] = ['status' => 'Cuti Rehat', 'badge' => '#fef3c7', 'color' => '#b45309', 'icon' => 'fa-umbrella-beach'];
    } 
    // 2. Time Off (Active ONLY during the exact requested time window)
    elseif ($type === 'time_off' || $type === 'timeoff') {
        if ($current_time_ts >= $start_ts && $current_time_ts <= $end_ts) {
            $time_label = date('h:i A', $start_ts) . ' - ' . date('h:i A', $end_ts);
            $status_by_user[$uid] = ['status' => "Time Off ($time_label)", 'badge' => '#e0e7ff', 'color' => '#4338ca', 'icon' => 'fa-hourglass-start'];
        }
    } 
    // 3. Mesyuarat
    elseif ($type === 'meeting' && !isset($status_by_user[$uid])) {
        if ($current_time_ts >= $start_ts && $current_time_ts <= $end_ts) {
            $status_by_user[$uid] = ['status' => 'Mesyuarat', 'badge' => '#e0f2fe', 'color' => '#0284c7', 'icon' => 'fa-video'];
        }
    } 
    // 4. Kursus / Latihan
    elseif ($type === 'kursus' && !isset($status_by_user[$uid])) {
        if ($current_time_ts >= $start_ts && $current_time_ts <= $end_ts) {
            $status_by_user[$uid] = ['status' => 'Kursus', 'badge' => '#f3e8ff', 'color' => '#9333ea', 'icon' => 'fa-graduation-cap'];
        }
    }
}

// Group tasks by user_id
$tasks_by_member = [];
$total_tasks = count($team_tasks);
$ongoing_count = 0;
$completed_count = 0;

foreach ($team_tasks as $t) {
    $u_id = (int)$t['user_id'];
    if (!isset($tasks_by_member[$u_id])) {
        $tasks_by_member[$u_id] = [];
    }
    $tasks_by_member[$u_id][] = $t;

    $st = strtolower(trim($t['status'] ?? ''));
    if ($st === 'completed' || $st === 'selesai') {
        $completed_count++;
    } else {
        $ongoing_count++;
    }
}

$efficiency_percent = ($total_tasks > 0) ? round(($completed_count / $total_tasks) * 100) : 100;
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Team | 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);
        }

        /* KPI Summary Grid */
        .kpi-grid {
            display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 20px;
        }
        .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-total { background: #e0f2fe; color: #0284c7; }
        .kpi-working { background: #d1fae5; color: #059669; }
        .kpi-tasks { background: #e0e7ff; color: #4338ca; }
        .kpi-completed { background: #fef3c7; color: #d97706; }
        .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; }

        /* Search Toolbar */
        .team-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;
        }
        .team-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; max-width: 400px;
        }
        .team-search-box input { border: none; outline: none; width: 100%; font-size: 0.85rem; color: var(--text-main); font-weight: 600; }

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

        .member-header-row { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
        .member-avatar-box {
            width: 52px; height: 52px; border-radius: 16px; background: linear-gradient(135deg, var(--primary), var(--deep-blue));
            color: #fff; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; font-weight: 850;
            flex-shrink: 0; box-shadow: 0 4px 14px rgba(0, 119, 182, 0.25);
        }
        .member-avatar-box img { width: 100%; height: 100%; object-fit: cover; border-radius: 16px; }
        
        .member-name-text strong { display: block; font-size: 1rem; font-weight: 850; color: var(--deep-blue); line-height: 1.25; }
        .member-name-text span { font-size: 0.78rem; color: var(--text-muted); font-weight: 700; }

        .pulse-status-badge {
            font-size: 0.72rem; font-weight: 850; padding: 4px 12px; border-radius: 999px; text-transform: uppercase;
            display: inline-flex; align-items: center; gap: 5px; width: fit-content;
        }

        .member-metrics-box {
            background: #f8fafc; border-radius: 14px; padding: 12px 14px; border: 1px solid #e2e8f0;
            display: flex; flex-direction: column; gap: 8px;
        }
        .metrics-count-row { display: flex; justify-content: space-between; font-size: 0.78rem; font-weight: 800; color: var(--deep-blue); }
        .progress-bar-bg { height: 6px; background: #e2e8f0; border-radius: 999px; overflow: hidden; }
        .progress-bar-fill { height: 100%; background: linear-gradient(90deg, #10b981, #059669); border-radius: 999px; }

        .member-actions-footer {
            margin-top: auto; padding-top: 12px; border-top: 1px solid rgba(0, 119, 182, 0.08);
            display: flex; justify-content: space-between; align-items: center; gap: 8px;
        }
        .btn-view-member-tasks {
            background: rgba(0, 119, 182, 0.08); color: var(--primary); border: 1px solid rgba(0, 119, 182, 0.18);
            padding: 7px 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: 6px;
        }
        .btn-view-member-tasks:hover { background: var(--primary); color: #fff; }

        .member-contact-icons { display: flex; gap: 6px; }
        .contact-icon-btn {
            width: 32px; height: 32px; border-radius: 9px; border: 1px solid #e2e8f0; background: #fff;
            display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 0.82rem;
            text-decoration: none; transition: all 0.2s ease;
        }
        .contact-icon-btn:hover { background: var(--deep-blue); color: #fff; border-color: var(--deep-blue); }

        /* 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; }

        .member-filter-bar {
            display: flex; gap: 6px; overflow-x: auto; padding-bottom: 12px; margin-bottom: 18px; align-items: center;
        }
        .member-filter-pill {
            border: 1px solid rgba(0, 119, 182, 0.18); background: #fff; padding: 6px 14px; border-radius: 999px;
            font-size: 0.78rem; font-weight: 800; color: var(--deep-blue); cursor: pointer; white-space: nowrap; transition: all 0.2s ease;
            display: inline-flex; align-items: center; gap: 6px;
        }
        .member-filter-pill.active { background: var(--deep-blue); color: #fff; border-color: var(--deep-blue); }

        .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-task-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-task-card:hover { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(0,0,0,0.12); z-index: 40 !important; }
        .task-theme-teal { background: #e6fffa; border-top: 3px solid #0d9488; }
        .task-theme-blue { background: #e0f2fe; border-top: 3px solid #0284c7; }
        .task-theme-orange { background: #fff7ed; border-top: 3px solid #ea580c; }
        .task-theme-purple { background: #f5f3ff; border-top: 3px solid #7c3aed; }
        .task-theme-rose { background: #fff1f2; border-top: 3px solid #e11d48; }

        /* Modal Member Tasks */
        .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: 580px;
            box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden; animation: modalPop 0.25s ease;
            max-height: 85vh; 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-body { padding: 22px 24px; display: flex; flex-direction: column; gap: 12px; overflow-y: 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.php'); ?>
        </ul>
    </aside>

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

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

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

        <!-- Master View Switcher -->
        <div class="view-mode-bar">
            <div class="view-toggle-pills">
                <button class="view-pill-btn active" id="btnTeamDirectory" onclick="switchTeamMasterView('directory')">
                    <i class="fa-solid fa-address-book"></i>
                    <span>Direktori & Ahli Pasukan (<?php echo $total_members; ?>)</span>
                </button>
                <button class="view-pill-btn" id="btnTeamCalendar" onclick="switchTeamMasterView('calendar')">
                    <i class="fa-solid fa-calendar-days"></i>
                    <span>Kalendar Tugasan Bahagian (<?php echo $total_tasks; ?>)</span>
                </button>
            </div>

            <div style="font-size: 0.84rem; font-weight: 750; color: var(--deep-blue);">
                <i class="fa-solid fa-building text-primary mr-1"></i> <?php echo htmlspecialchars($user_department !== '' ? $user_department : 'Bahagian Anda'); ?>
            </div>
        </div>

        <!-- ================= VIEW 1: DIRECTORY & KPI SECTION ================= -->
        <div id="teamDirectorySection">
            
            <!-- KPI Summary Cards -->
            <div class="kpi-grid">
                <div class="kpi-card">
                    <div class="kpi-icon-box kpi-total"><i class="fa-solid fa-users"></i></div>
                    <div class="kpi-info">
                        <h4>Jumlah Anggota</h4>
                        <div class="kpi-number"><?php echo $total_members; ?></div>
                    </div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-icon-box kpi-working"><i class="fa-solid fa-user-check"></i></div>
                    <div class="kpi-info">
                        <h4>Bertugas Hari Ini</h4>
                        <div class="kpi-number"><?php echo max(0, $total_members - count($status_by_user)); ?></div>
                    </div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-icon-box kpi-tasks"><i class="fa-solid fa-list-check"></i></div>
                    <div class="kpi-info">
                        <h4>Tugasan Aktif</h4>
                        <div class="kpi-number"><?php echo $ongoing_count; ?></div>
                    </div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-icon-box kpi-completed"><i class="fa-solid fa-chart-line"></i></div>
                    <div class="kpi-info">
                        <h4>Kecekapan Selesai</h4>
                        <div class="kpi-number"><?php echo $efficiency_percent; ?>%</div>
                    </div>
                </div>
            </div>

            <!-- Toolbar -->
            <div class="team-toolbar">
                <div class="team-search-box">
                    <i class="fa-solid fa-magnifying-glass text-muted"></i>
                    <input type="text" id="memberSearchInput" placeholder="Cari nama kakitangan, jawatan, atau emel..." onkeyup="filterMembersLive()">
                </div>
                <div style="font-size: 0.8rem; font-weight: 750; color: var(--text-muted);">
                    <i class="fa-solid fa-circle-info text-primary mr-1"></i> Ketersediaan masa nyata dikemaskini automatik
                </div>
            </div>

            <!-- Team Members Grid -->
            <div class="team-grid-container" id="membersGrid">
                <?php foreach ($members as $mem): 
                    $m_id = (int)$mem['id'];
                    $m_tasks = $tasks_by_member[$m_id] ?? [];
                    $m_total = count($m_tasks);
                    $m_done = count(array_filter($m_tasks, fn($x) => in_array(strtolower($x['status'] ?? ''), ['completed', 'selesai'])));
                    $m_pct = ($m_total > 0) ? round(($m_done / $m_total) * 100) : 100;

                    $status_info = $status_by_user[$m_id] ?? [
                        'status' => 'Bertugas / Aktif',
                        'badge' => '#d1fae5',
                        'color' => '#065f46',
                        'icon' => 'fa-circle-check'
                    ];

                    $initials = strtoupper(substr($mem['fullname'], 0, 2));
                ?>
                    <div class="world-member-card" data-name="<?php echo htmlspecialchars(strtolower($mem['fullname'] . ' ' . ($mem['position'] ?? '') . ' ' . $mem['email'])); ?>">
                        <div class="member-header-row">
                            <div style="display: flex; gap: 12px; align-items: center;">
                                <div class="member-avatar-box">
                                    <?php if (!empty($mem['avatar_url'])): ?>
                                        <img src="<?php echo htmlspecialchars($mem['avatar_url']); ?>" alt="<?php echo htmlspecialchars($mem['fullname']); ?>">
                                    <?php else: ?>
                                        <span><?php echo $initials; ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="member-name-text">
                                    <strong><?php echo htmlspecialchars($mem['fullname']); ?></strong>
                                    <span><?php echo htmlspecialchars($mem['position'] ?: 'Pegawai Bahagian'); ?></span>
                                </div>
                            </div>
                        </div>

                        <!-- Real-time Availability Pulse Badge -->
                        <div>
                            <span class="pulse-status-badge" style="background: <?php echo $status_info['badge']; ?>; color: <?php echo $status_info['color']; ?>; border: 1px solid <?php echo $status_info['badge']; ?>;">
                                <i class="fa-solid <?php echo $status_info['icon']; ?>"></i>
                                <?php echo htmlspecialchars($status_info['status']); ?>
                            </span>
                        </div>

                        <!-- Member Task KPI & Progress Bar -->
                        <div class="member-metrics-box">
                            <div class="metrics-count-row">
                                <span>Tugasan: <?php echo $m_done; ?> / <?php echo $m_total; ?> Selesai</span>
                                <span style="color: var(--primary);"><?php echo $m_pct; ?>%</span>
                            </div>
                            <div class="progress-bar-bg">
                                <div class="progress-bar-fill" style="width: <?php echo $m_pct; ?>%;"></div>
                            </div>
                        </div>

                        <div class="member-actions-footer">
                            <button type="button" class="btn-view-member-tasks" onclick='openMemberTasksModal(<?php echo json_encode($mem, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); ?>, <?php echo json_encode($m_tasks, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); ?>)'>
                                <i class="fa-solid fa-list-check"></i> Lihat Tugasan (<?php echo $m_total; ?>)
                            </button>

                            <div class="member-contact-icons">
                                <?php if (!empty($mem['email'])): ?>
                                    <a href="mailto:<?php echo htmlspecialchars($mem['email']); ?>" class="contact-icon-btn" title="Emel: <?php echo htmlspecialchars($mem['email']); ?>">
                                        <i class="fa-solid fa-envelope"></i>
                                    </a>
                                <?php endif; ?>
                                <?php if (!empty($mem['phone'])): ?>
                                    <a href="tel:<?php echo htmlspecialchars($mem['phone']); ?>" class="contact-icon-btn" title="Telefon: <?php echo htmlspecialchars($mem['phone']); ?>">
                                        <i class="fa-solid fa-phone"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

        </div>

        <!-- ================= VIEW 2: DEPARTMENT TASK CALENDAR SECTION ================= -->
        <div id="teamCalendarSection" class="calendar-app-card" style="display: none;">
            <div class="cal-header-row">
                <div class="cal-title-nav">
                    <div class="cal-title-month" id="teamCalMonthTitle">Ogos 2026</div>
                    <div class="cal-arrows">
                        <button class="cal-arrow-btn" onclick="prevTeamWeek()"><i class="fa-solid fa-chevron-left"></i></button>
                        <button class="cal-arrow-btn" onclick="nextTeamWeek()"><i class="fa-solid fa-chevron-right"></i></button>
                        <button class="btn-cal-today" onclick="goToTodayTeam()">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> Paparan Tugasan Ahli Unit / Bahagian Sahaja
                </div>
            </div>

            <!-- Member Filter Pill Bar -->
            <div class="member-filter-bar">
                <span style="font-size: 0.78rem; font-weight: 800; color: var(--deep-blue); margin-right: 4px;">Pilih Ahli:</span>
                <button class="member-filter-pill active" onclick="filterCalendarMember(0, this)">
                    <i class="fa-solid fa-users"></i>
                    <span>Semua Ahli (<?php echo $total_members; ?>)</span>
                </button>
                <?php foreach ($members as $m): ?>
                    <button class="member-filter-pill" onclick="filterCalendarMember(<?php echo $m['id']; ?>, this)">
                        <span><?php echo htmlspecialchars($m['short_name'] ?: $m['fullname']); ?></span>
                    </button>
                <?php endforeach; ?>
            </div>

            <div class="cal-week-board">
                <div class="cal-week-head" id="teamWeekHeaderRow">
                    <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: Member Tasks Detail -->
    <div class="modal-overlay" id="memberTasksModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3 id="modalMemberName" style="font-size: 1.15rem; font-weight: 850; color: var(--deep-blue);">Tugasan Ahli</h3>
                    <p id="modalMemberRole" style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Senarai tugasan yang sedang dikendalikan.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeMemberTasksModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div class="modal-body" id="modalTaskListBody">
                <!-- Dynamically injected -->
            </div>
        </div>
    </div>

    <script>
        const allTeamTasks = <?php echo json_encode($team_tasks, JSON_UNESCAPED_UNICODE); ?>;
        let calCurrentTeamDate = new Date();
        let selectedMemberFilter = 0;

        function switchTeamMasterView(mode) {
            document.getElementById('btnTeamDirectory').classList.toggle('active', mode === 'directory');
            document.getElementById('btnTeamCalendar').classList.toggle('active', mode === 'calendar');
            document.getElementById('teamDirectorySection').style.display = (mode === 'directory') ? 'block' : 'none';
            document.getElementById('teamCalendarSection').style.display = (mode === 'calendar') ? 'block' : 'none';
            if (mode === 'calendar') {
                renderTeamTaskCalendarWeek();
            }
        }

        function filterMembersLive() {
            const query = document.getElementById('memberSearchInput').value.toLowerCase().trim();
            const cards = document.querySelectorAll('#membersGrid .world-member-card');
            cards.forEach(card => {
                const name = card.getAttribute('data-name') || '';
                card.style.display = (query === '' || name.includes(query)) ? 'flex' : 'none';
            });
        }

        function filterCalendarMember(memberId, btn) {
            selectedMemberFilter = parseInt(memberId);
            document.querySelectorAll('.member-filter-pill').forEach(p => p.classList.remove('active'));
            btn.classList.add('active');
            renderTeamTaskCalendarWeek();
        }

        function renderTeamTaskCalendarWeek() {
            const headerRow = document.getElementById('teamWeekHeaderRow');
            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('teamCalMonthTitle').innerText = `${monthNames[calCurrentTeamDate.getMonth()]} ${calCurrentTeamDate.getFullYear()}`;

            const currentDayOfWeek = calCurrentTeamDate.getDay();
            const sunday = new Date(calCurrentTeamDate);
            sunday.setDate(calCurrentTeamDate.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('#teamCalendarSection .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 matchingTasks = allTeamTasks.filter(t => {
                    if (selectedMemberFilter > 0 && parseInt(t.user_id) !== selectedMemberFilter) return false;
                    if (!t.start_at || !t.start_at.startsWith(targetDateStr)) return false;
                    const tHour = new Date(t.start_at).getHours();
                    return tHour === hour;
                });

                matchingTasks.forEach((t, idx) => {
                    const startDate = new Date(t.start_at);
                    const endDate = t.end_at ? new Date(t.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 themes = ['task-theme-teal', 'task-theme-blue', 'task-theme-orange', 'task-theme-purple', 'task-theme-rose'];
                    const colorIndex = (t.id || idx) % themes.length;
                    const themeClass = themes[colorIndex];

                    const memberDisplayName = t.short_name || t.fullname || 'Staf';

                    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-task-card ${themeClass}`;
                    card.style.height = `${cardHeight}px`;
                    card.style.position = 'relative';
                    card.style.zIndex = '15';
                    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(t.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: 850; color: var(--deep-blue); width: fit-content;">
                            <i class="fa-solid fa-user text-primary" style="font-size: 0.62rem;"></i>
                            <span>${escapeHtml(memberDisplayName)}</span>
                        </div>
                    `;
                    cell.appendChild(card);
                });
            });
        }

        function prevTeamWeek() {
            calCurrentTeamDate.setDate(calCurrentTeamDate.getDate() - 7);
            renderTeamTaskCalendarWeek();
        }

        function nextTeamWeek() {
            calCurrentTeamDate.setDate(calCurrentTeamDate.getDate() + 7);
            renderTeamTaskCalendarWeek();
        }

        function goToTodayTeam() {
            calCurrentTeamDate = new Date();
            renderTeamTaskCalendarWeek();
        }

        function openMemberTasksModal(member, tasks) {
            document.getElementById('modalMemberName').innerText = `Tugasan: ${member.fullname}`;
            document.getElementById('modalMemberRole').innerText = `${member.position || 'Pegawai'} • ${tasks.length} Tugasan Direkodkan`;

            const body = document.getElementById('modalTaskListBody');
            body.innerHTML = '';

            if (tasks.length === 0) {
                body.innerHTML = `
                    <div style="text-align: center; padding: 30px; color: var(--text-muted);">
                        <i class="fa-solid fa-clipboard-check" style="font-size: 2.5rem; opacity: 0.35; margin-bottom: 10px;"></i>
                        <p style="font-size: 0.88rem; font-weight: 700;">Tiada tugasan direkodkan untuk ahli ini.</p>
                    </div>
                `;
            } else {
                tasks.forEach(t => {
                    const st = (t.status || 'Pending').toLowerCase();
                    const isDone = (st === 'completed' || st === 'selesai');
                    const prio = (t.priority || 'medium').toUpperCase();

                    const item = document.createElement('div');
                    item.style.cssText = 'background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 14px; padding: 12px 16px; display: flex; justify-content: space-between; align-items: center; gap: 10px;';
                    item.innerHTML = `
                        <div>
                            <div style="font-size: 0.9rem; font-weight: 800; color: var(--deep-blue); ${isDone ? 'text-decoration: line-through; opacity: 0.7;' : ''}">${escapeHtml(t.title)}</div>
                            <div style="font-size: 0.74rem; color: var(--text-muted); margin-top: 3px;">Due: ${t.due_date ? t.due_date.substring(0, 10) : 'N/A'} • Priority: ${prio}</div>
                        </div>
                        <span style="font-size: 0.72rem; font-weight: 850; padding: 3px 10px; border-radius: 999px; background: ${isDone ? '#d1fae5' : '#e0e7ff'}; color: ${isDone ? '#065f46' : '#4338ca'};">
                            ${isDone ? 'Selesai' : 'Aktif'}
                        </span>
                    `;
                    body.appendChild(item);
                });
            }

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

        function closeMemberTasksModal() {
            document.getElementById('memberTasksModal').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', () => {
            // Default view is Directory
        });

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