<?php
require_once 'auth.php';
ensureAdminAuth();
$adminName = $_SESSION['admin_name'] ?? 'Admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Space+Grotesk:wght@500;600;700;800&display=swap">
<link rel="stylesheet" href="../assets/ushs-global-theme.css">
<link rel="stylesheet" href="../assets/ushs-header.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
:root {
  --cm-bg:       oklch(0.13 0.035 260);
  --cm-bg2:      oklch(0.11 0.032 261);
  --cm-card:     oklch(0.18 0.038 262);
  --cm-card2:    oklch(0.16 0.035 261);
  --cm-border:   oklch(0.98 0.005 250 / 0.12);
  --cm-border2:  oklch(0.98 0.005 250 / 0.20);
  --cm-text:     oklch(0.98 0.005 250);
  --cm-muted:    oklch(0.72 0.02 260);
  --cm-blue:     oklch(0.62 0.22 255);
  --cm-cyan:     oklch(0.72 0.18 195);
  --cm-green:    oklch(0.72 0.18 155);
  --cm-purple:   oklch(0.72 0.18 300);
  --cm-yellow:   oklch(0.82 0.16 85);
  --cm-red:      oklch(0.68 0.22 27);
  --cm-header-h: 62px;
}
*,*::before,*::after{box-sizing:border-box;}
html,body{margin:0;min-height:100%;font-family:'Inter',system-ui,sans-serif;background:radial-gradient(circle at 18% 0%, oklch(0.62 0.22 255 / 0.13), transparent 34%),linear-gradient(135deg,var(--cm-bg) 0%,var(--cm-bg2) 100%) fixed;color:var(--cm-text);overflow-x:hidden;}
body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:-1;background-image:linear-gradient(oklch(0.98 0.005 250 / 0.022) 1px,transparent 1px),linear-gradient(90deg,oklch(0.98 0.005 250 / 0.016) 1px,transparent 1px);background-size:44px 44px;}
.main-content,.cm-main{padding:calc(var(--cm-header-h) + 16px) 20px 28px;min-height:100vh;width:100%;}
.cm-page-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px;}
.cm-page-kicker{color:var(--cm-cyan);font-size:.72rem;font-weight:900;letter-spacing:.12em;text-transform:uppercase;margin-bottom:3px;}
.cm-page-title{font-family:'Space Grotesk',system-ui,sans-serif;font-size:1.7rem;font-weight:900;margin:0;}
.cm-page-subtitle{color:var(--cm-muted);font-size:.9rem;font-weight:600;margin:3px 0 0;}
.cm-btn{display:inline-flex;align-items:center;gap:7px;padding:8px 14px;border-radius:10px;border:1px solid var(--cm-border);background:var(--cm-card);color:var(--cm-text)!important;font-size:.82rem;font-weight:700;text-decoration:none!important;cursor:pointer;transition:background .18s,border-color .18s,transform .18s;white-space:nowrap;}
.cm-btn:hover{background:oklch(0.62 0.22 255 / 0.16);border-color:oklch(0.62 0.22 255 / 0.45);transform:translateY(-1px);}
.cm-btn--primary{background:var(--cm-blue);border-color:transparent;color:#fff!important;}
.cm-btn--active{background:oklch(0.62 0.22 255 / 0.22);border-color:oklch(0.62 0.22 255 / 0.55);}
.cm-card{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:16px;padding:16px;}
.cm-card__title{font-family:'Space Grotesk',system-ui,sans-serif;font-size:.88rem;font-weight:800;color:var(--cm-muted);margin-bottom:12px;letter-spacing:.02em;display:flex;align-items:center;gap:8px;}
.cm-card__title i{color:var(--cm-cyan);}
.cm-badge{display:inline-flex;align-items:center;justify-content:center;padding:3px 8px;border-radius:999px;font-size:.7rem;font-weight:900;}
.cm-badge--yellow{background:oklch(0.82 0.16 85 / 0.18);color:var(--cm-yellow);border:1px solid oklch(0.82 0.16 85 / 0.4);}
.cm-skeleton{background:linear-gradient(90deg,oklch(0.98 0.005 250 / .05),oklch(0.98 0.005 250 / .10),oklch(0.98 0.005 250 / .05));}

/* ── Stat bar ─────────────────────────────────────────────── */
.cm-section-title {
  font-family:'Space Grotesk',system-ui,sans-serif;
  font-weight:900;
  font-size:1rem;
  margin: 4px 0 10px;
  color: var(--cm-text);
}
.cm-section-title small { color: var(--cm-muted); font-family:'Inter',system-ui,sans-serif; font-weight:700; margin-left:8px; }
.cm-stat-bar {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.cm-stat-tile {
  background: var(--cm-card);
  border: 1px solid var(--cm-border);
  border-radius: 14px;
  padding: 16px 10px 12px;
  text-align: center;
  transition: border-color .2s, transform .2s;
}
.cm-stat-tile:hover { border-color: var(--cm-border2); transform: translateY(-2px); }
.cm-stat-tile__icon { font-size: 18px; margin-bottom: 6px; color: var(--cm-muted); }
/* PATCH 2026-06-09 REMODIFIED: admin dashboard number font colors only */
.cm-stat-tile__val  {
  font-family: 'Space Grotesk', system-ui, sans-serif;
  font-size: 1.9rem; font-weight: 800; line-height: 1; margin-bottom: 4px;
}
.cm-stat-tile__lbl  { font-size: .62rem; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: var(--cm-muted); }

/* Number/font color only - copied from CSR Manager dashboard */
.cm-stat-tile--handled   .cm-stat-tile__val { color: var(--cm-cyan) !important; }
.cm-stat-tile--assigned  .cm-stat-tile__val { color: var(--cm-blue) !important; }
.cm-stat-tile--progress  .cm-stat-tile__val { color: var(--cm-purple) !important; }
.cm-stat-tile--completed .cm-stat-tile__val { color: var(--cm-green) !important; }
.cm-stat-tile--cancelled .cm-stat-tile__val { color: var(--cm-red) !important; }
.cm-stat-tile--calls     .cm-stat-tile__val { color: var(--cm-text) !important; }
.cm-stat-tile--scheduled .cm-stat-tile__val { color: var(--cm-cyan) !important; }
.cm-stat-tile--connected .cm-stat-tile__val { color: var(--cm-green) !important; }
.cm-stat-tile--missed    .cm-stat-tile__val { color: var(--cm-yellow) !important; }
.cm-stat-tile--updates   .cm-stat-tile__val { color: var(--cm-purple) !important; }
.cm-stat-tile--warn      .cm-stat-tile__val { color: var(--cm-yellow) !important; }
.cm-stat-tile--mistakes  .cm-stat-tile__val { color: var(--cm-red) !important; }

/* ── Quick-action bar ─────────────────────────────────────── */
.cm-quick-bar {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

/* ── Charts row ───────────────────────────────────────────── */
.cm-charts-row {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

/* ── Top CX usage charts ─────────────────────────────────── */
.cm-top-usage-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}


/* ── Bottom row ───────────────────────────────────────────── */
.cm-bottom-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
}

.cm-team-cards-area {
  grid-column: span 2;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

/* Team card */
.cm-team-card {
  background: var(--cm-card);
  border: 1px solid var(--cm-border);
  border-radius: 14px;
  padding: 14px 16px;
  cursor: pointer;
  transition: transform .16s ease, border-color .16s ease, box-shadow .16s ease;
}
.cm-team-card:hover {
  transform: translateY(-2px);
  border-color: var(--cm-border2);
  box-shadow: 0 12px 28px rgba(0,0,0,.22);
}
.cm-team-card__hint { font-size:.65rem;color:var(--cm-muted);font-weight:700;margin-left:auto;text-transform:uppercase;letter-spacing:.05em; }
.cm-team-card__head {display:flex;align-items:center;gap:8px;margin-bottom:10px;}
.cm-team-card__name {
  font-size: .7rem; font-weight: 800; text-transform: uppercase;
  letter-spacing: .08em; margin:0;
}
.cm-team-grid { display:grid; grid-template-columns:1fr 1fr; gap:0 14px; }
.cm-tsr { display: flex; justify-content: space-between; padding: 4px 0; font-size: .76rem; border-bottom: 1px solid var(--cm-border); }
.cm-tsr:last-child { border-bottom: none; }
.cm-tsr__l { color: var(--cm-muted); }
.cm-tsr__v { font-weight: 700; }

/* Mistakes panel */
.cm-mistakes-panel {
  background: var(--cm-card);
  border: 1px solid var(--cm-border);
  border-radius: 14px;
  padding: 14px 16px;
}
.cm-mistakes-hdr {
  display: flex; align-items: center; gap: 8px; margin-bottom: 12px;
}
.cm-mistakes-title {
  font-family: 'Space Grotesk', system-ui, sans-serif;
  font-size: .92rem; font-weight: 800; flex: 1;
}
.cm-mistake-row {
  display: flex; align-items: center; gap: 10px;
  padding: 8px 0; border-bottom: 1px solid var(--cm-border);
}
.cm-mistake-row:last-child { border-bottom: none; }
.cm-mistake-team { font-size: .62rem; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; color: var(--cm-blue); display: block; }
.cm-mistake-name { font-size: .84rem; font-weight: 700; }
.cm-mistake-metric { font-size: .74rem; color: var(--cm-muted); }
.cm-mistake-badge {
  margin-left: auto;
  background: oklch(0.82 0.16 85 / 0.18);
  border: 1px solid oklch(0.82 0.16 85 / 0.45);
  color: var(--cm-yellow);
  font-size: .7rem; font-weight: 800; padding: 3px 8px; border-radius: 8px;
  white-space: nowrap; flex-shrink: 0;
}
.cm-mistake-badge.danger {
  background: oklch(0.68 0.22 27 / 0.18);
  border-color: oklch(0.68 0.22 27 / 0.45);
  color: var(--cm-red);
}




.cm-team-card.is-clickable,
.cm-mistake-row.is-clickable { cursor:pointer; }
.cm-team-card.is-clickable:hover,
.cm-mistake-row.is-clickable:hover { background:oklch(0.98 0.005 250 / 0.045); }
.cm-detail-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.62);display:none;align-items:center;justify-content:center;z-index:9999;padding:18px;}
.cm-detail-backdrop.is-open{display:flex;}
.cm-detail-modal{width:min(760px,96vw);max-height:86vh;overflow:auto;background:var(--cm-card);border:1px solid var(--cm-border2);border-radius:18px;box-shadow:0 22px 80px rgba(0,0,0,.5);}
.cm-detail-head{display:flex;align-items:flex-start;gap:12px;justify-content:space-between;padding:16px 18px;border-bottom:1px solid var(--cm-border);}
.cm-detail-title{font-family:'Space Grotesk',system-ui,sans-serif;font-size:1.05rem;font-weight:900;margin:0;}
.cm-detail-sub{color:var(--cm-muted);font-size:.78rem;font-weight:700;margin-top:3px;}
.cm-detail-close{border:1px solid var(--cm-border);background:transparent;color:var(--cm-text)!important;border-radius:10px;width:34px;height:34px;font-weight:900;}
.cm-detail-body{padding:16px 18px;}
.cm-detail-item{border:1px solid var(--cm-border);border-radius:13px;padding:12px;margin-bottom:10px;background:oklch(0.98 0.005 250 / 0.028);}
.cm-detail-item:last-child{margin-bottom:0;}
.cm-detail-line{display:flex;gap:10px;justify-content:space-between;align-items:center;margin-bottom:6px;}
.cm-detail-item-title{font-weight:900;font-size:.9rem;}
.cm-detail-pill{font-size:.65rem;font-weight:900;text-transform:uppercase;border-radius:999px;padding:3px 8px;border:1px solid var(--cm-border2);color:var(--cm-yellow);}
.cm-detail-message{color:var(--cm-text);font-size:.84rem;line-height:1.45;white-space:pre-wrap;}
.cm-detail-meta{color:var(--cm-muted);font-size:.72rem;font-weight:700;margin-top:8px;}
.cm-detail-table{width:100%;border-collapse:collapse;font-size:.82rem;}
.cm-detail-table td{border-bottom:1px solid var(--cm-border);padding:7px 4px;}
.cm-detail-table td:last-child{text-align:right;font-weight:900;}

.cm-disc-filter{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0 10px;}
.cm-disc-filter select,.cm-disc-filter input{height:32px;border:1px solid var(--cm-border);border-radius:10px;background:oklch(0.18 0.04 262 / .92);color:var(--cm-text)!important;-webkit-text-fill-color:var(--cm-text)!important;font-size:.74rem;font-weight:800;padding:0 10px;outline:none;}
.cm-disc-filter input{min-width:150px;flex:1;}
.cm-disc-filter select:focus,.cm-disc-filter input:focus{border-color:var(--cm-cyan);box-shadow:0 0 0 2px rgba(34,211,238,.12);}
.cm-disc-filter select option{background:#0f172a;color:#e5e7eb;}
.cm-disc-empty{text-align:center;color:var(--cm-muted);font-size:.8rem;padding:16px 0;}


/* FINAL PATCH: Admin dashboard VALUE FONT + ICON COLORS ONLY (no container color) */
#cmOHandledToday, #cmSHandledToday { color:#00d4e8 !important; }
#cmOAssignedTickets, #cmSAssignedTickets { color:#1e90ff !important; }
#cmOInProgress, #cmSInProgress { color:#a78bfa !important; }
#cmOCompletedToday, #cmSCompletedToday { color:#10b981 !important; }
#cmOCancelledToday, #cmSCancelledToday { color:#ff4d4f !important; }
#cmOTotalCalls, #cmSTotalCalls { color:#f8fafc !important; }
#cmOCallsScheduled, #cmSCallsScheduled { color:#00d4e8 !important; }
#cmOConnected, #cmSConnected { color:#10b981 !important; }
#cmOMissedAbsent, #cmSMissedAbsent { color:#fbbf24 !important; }
#cmOUpdates, #cmSUpdates { color:#a78bfa !important; }
#cmOWarnings, #cmSWarnings { color:#fbbf24 !important; }
#cmOMistakes, #cmSMistakes { color:#ff4d4f !important; }
.cm-stat-tile--handled .cm-stat-tile__icon, .cm-stat-tile--handled .cm-stat-tile__icon i { color:#00d4e8 !important; }
.cm-stat-tile--assigned .cm-stat-tile__icon, .cm-stat-tile--assigned .cm-stat-tile__icon i { color:#1e90ff !important; }
.cm-stat-tile--progress .cm-stat-tile__icon, .cm-stat-tile--progress .cm-stat-tile__icon i { color:#a78bfa !important; }
.cm-stat-tile--completed .cm-stat-tile__icon, .cm-stat-tile--completed .cm-stat-tile__icon i { color:#10b981 !important; }
.cm-stat-tile--cancelled .cm-stat-tile__icon, .cm-stat-tile--cancelled .cm-stat-tile__icon i { color:#ff4d4f !important; }
.cm-stat-tile--calls .cm-stat-tile__icon, .cm-stat-tile--calls .cm-stat-tile__icon i { color:#f8fafc !important; }
.cm-stat-tile--scheduled .cm-stat-tile__icon, .cm-stat-tile--scheduled .cm-stat-tile__icon i { color:#00d4e8 !important; }
.cm-stat-tile--connected .cm-stat-tile__icon, .cm-stat-tile--connected .cm-stat-tile__icon i { color:#10b981 !important; }
.cm-stat-tile--missed .cm-stat-tile__icon, .cm-stat-tile--missed .cm-stat-tile__icon i { color:#fbbf24 !important; }
.cm-stat-tile--updates .cm-stat-tile__icon, .cm-stat-tile--updates .cm-stat-tile__icon i { color:#a78bfa !important; }
.cm-stat-tile--warn .cm-stat-tile__icon, .cm-stat-tile--warn .cm-stat-tile__icon i { color:#fbbf24 !important; }
.cm-stat-tile--mistakes .cm-stat-tile__icon, .cm-stat-tile--mistakes .cm-stat-tile__icon i { color:#ff4d4f !important; }

@media (max-width: 960px) {
  .cm-stat-bar { grid-template-columns: repeat(4, 1fr); }
  .cm-charts-row { grid-template-columns: 1fr; }
  .cm-top-usage-row { grid-template-columns: 1fr; }
  .cm-bottom-row { grid-template-columns: 1fr; }
  .cm-team-cards-area { grid-column: span 1; grid-template-columns: 1fr; }
}
@media (max-width: 540px) {
  .cm-stat-bar { grid-template-columns: repeat(2, 1fr); }
}


/* ADMIN NUMBER FONT COLORS ONLY - matches CSR Manager dashboard */
#cmOHandledToday.cm-stat-tile__val, #cmSHandledToday.cm-stat-tile__val { color: var(--cm-cyan) !important; }
#cmOAssignedTickets.cm-stat-tile__val, #cmSAssignedTickets.cm-stat-tile__val { color: var(--cm-blue) !important; }
#cmOInProgress.cm-stat-tile__val, #cmSInProgress.cm-stat-tile__val { color: var(--cm-purple) !important; }
#cmOCompletedToday.cm-stat-tile__val, #cmSCompletedToday.cm-stat-tile__val { color: var(--cm-green) !important; }
#cmOCancelledToday.cm-stat-tile__val, #cmSCancelledToday.cm-stat-tile__val { color: var(--cm-red) !important; }
#cmOTotalCalls.cm-stat-tile__val, #cmSTotalCalls.cm-stat-tile__val { color: var(--cm-text) !important; }
#cmOCallsScheduled.cm-stat-tile__val, #cmSCallsScheduled.cm-stat-tile__val { color: var(--cm-cyan) !important; }
#cmOConnected.cm-stat-tile__val, #cmSConnected.cm-stat-tile__val { color: var(--cm-green) !important; }
#cmOMissedAbsent.cm-stat-tile__val, #cmSMissedAbsent.cm-stat-tile__val { color: var(--cm-yellow) !important; }
#cmOUpdates.cm-stat-tile__val, #cmSUpdates.cm-stat-tile__val { color: var(--cm-purple) !important; }
#cmOWarnings.cm-stat-tile__val, #cmSWarnings.cm-stat-tile__val { color: var(--cm-yellow) !important; }
#cmOMistakes.cm-stat-tile__val, #cmSMistakes.cm-stat-tile__val { color: var(--cm-red) !important; }


/* ADMIN DASHBOARD COLOR FIX — must beat global white text-fill override */
.cm-main .cm-stat-tile--handled .cm-stat-tile__val,
.cm-main .cm-stat-tile--handled .cm-stat-tile__icon,
.cm-main .cm-stat-tile--handled .cm-stat-tile__icon i,
.cm-main .admin-color-handled { color:#00d4e8 !important; -webkit-text-fill-color:#00d4e8 !important; }

.cm-main .cm-stat-tile--assigned .cm-stat-tile__val,
.cm-main .cm-stat-tile--assigned .cm-stat-tile__icon,
.cm-main .cm-stat-tile--assigned .cm-stat-tile__icon i,
.cm-main .admin-color-assigned { color:#1e90ff !important; -webkit-text-fill-color:#1e90ff !important; }

.cm-main .cm-stat-tile--progress .cm-stat-tile__val,
.cm-main .cm-stat-tile--progress .cm-stat-tile__icon,
.cm-main .cm-stat-tile--progress .cm-stat-tile__icon i,
.cm-main .admin-color-progress { color:#a78bfa !important; -webkit-text-fill-color:#a78bfa !important; }

.cm-main .cm-stat-tile--completed .cm-stat-tile__val,
.cm-main .cm-stat-tile--completed .cm-stat-tile__icon,
.cm-main .cm-stat-tile--completed .cm-stat-tile__icon i,
.cm-main .admin-color-completed { color:#10b981 !important; -webkit-text-fill-color:#10b981 !important; }

.cm-main .cm-stat-tile--cancelled .cm-stat-tile__val,
.cm-main .cm-stat-tile--cancelled .cm-stat-tile__icon,
.cm-main .cm-stat-tile--cancelled .cm-stat-tile__icon i,
.cm-main .admin-color-cancelled { color:#ff4d4f !important; -webkit-text-fill-color:#ff4d4f !important; }

.cm-main .cm-stat-tile--calls .cm-stat-tile__val,
.cm-main .cm-stat-tile--calls .cm-stat-tile__icon,
.cm-main .cm-stat-tile--calls .cm-stat-tile__icon i,
.cm-main .admin-color-calls { color:#f8fafc !important; -webkit-text-fill-color:#f8fafc !important; }

.cm-main .cm-stat-tile--scheduled .cm-stat-tile__val,
.cm-main .cm-stat-tile--scheduled .cm-stat-tile__icon,
.cm-main .cm-stat-tile--scheduled .cm-stat-tile__icon i,
.cm-main .admin-color-scheduled { color:#00d4e8 !important; -webkit-text-fill-color:#00d4e8 !important; }

.cm-main .cm-stat-tile--connected .cm-stat-tile__val,
.cm-main .cm-stat-tile--connected .cm-stat-tile__icon,
.cm-main .cm-stat-tile--connected .cm-stat-tile__icon i,
.cm-main .admin-color-connected { color:#10b981 !important; -webkit-text-fill-color:#10b981 !important; }

.cm-main .cm-stat-tile--missed .cm-stat-tile__val,
.cm-main .cm-stat-tile--missed .cm-stat-tile__icon,
.cm-main .cm-stat-tile--missed .cm-stat-tile__icon i,
.cm-main .admin-color-missed { color:#fbbf24 !important; -webkit-text-fill-color:#fbbf24 !important; }

.cm-main .cm-stat-tile--updates .cm-stat-tile__val,
.cm-main .cm-stat-tile--updates .cm-stat-tile__icon,
.cm-main .cm-stat-tile--updates .cm-stat-tile__icon i,
.cm-main .admin-color-updates { color:#a78bfa !important; -webkit-text-fill-color:#a78bfa !important; }

.cm-main .cm-stat-tile--warn .cm-stat-tile__val,
.cm-main .cm-stat-tile--warn .cm-stat-tile__icon,
.cm-main .cm-stat-tile--warn .cm-stat-tile__icon i,
.cm-main .admin-color-warn { color:#fbbf24 !important; -webkit-text-fill-color:#fbbf24 !important; }

.cm-main .cm-stat-tile--mistakes .cm-stat-tile__val,
.cm-main .cm-stat-tile--mistakes .cm-stat-tile__icon,
.cm-main .cm-stat-tile--mistakes .cm-stat-tile__icon i,
.cm-main .admin-color-mistakes { color:#ff4d4f !important; -webkit-text-fill-color:#ff4d4f !important; }

</style>
</head>
<body>
<?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar('dashboard.php'); ?>
<main class="cm-main main-content">
  <div class="cm-page-head">
    <div>
      <div class="cm-page-kicker">Administrator overview</div>
      <h1 class="cm-page-title">Admin Dashboard</h1>
      <p class="cm-page-subtitle">Admin-wide overview of all CSR teams, requests, calls, updates, warnings, and mistakes across the whole operation.</p>
    </div>
    <button class="cm-btn cm-btn--primary" id="cmDashRefreshBtnTop" onclick="cmDashLoad()"><i class="fas fa-sync-alt"></i> Refresh</button>
  </div>


<!-- Quick-action bar (matches screenshot exactly) -->
<div class="cm-quick-bar">
  <button type="button" class="cm-btn" onclick="cmGoBack()"><i class="fas fa-arrow-left"></i> Back</button>
  <a href="requests.php"       class="cm-btn"><i class="fas fa-clipboard-list"></i> Requests</a>
  <a href="staff.php"         class="cm-btn"><i class="fas fa-user-tie"></i> Staff</a>
  <a href="announcements.php" class="cm-btn"><i class="fas fa-bullhorn"></i> Announcements</a>
  <a href="mistake.php" class="cm-btn"><i class="fas fa-circle-exclamation"></i> Mistake</a>
  <a href="warning.php" class="cm-btn"><i class="fas fa-triangle-exclamation"></i> Warning</a>

  <div style="margin-left:auto;display:flex;gap:8px;flex-wrap:wrap;">
    <a href="activity_logs.php"   class="cm-btn"><i class="fas fa-clock-rotate-left"></i> Activity Logs</a>
    <button class="cm-btn" id="cmDashRefreshBtn" onclick="cmDashLoad()">
      <i class="fas fa-sync-alt" id="cmRefreshIcon"></i> Refresh
    </button>
  </div>
</div>

<!-- Overall Total stat bar -->
<div class="cm-section-title"><i class="fas fa-layer-group me-1"></i> Overall Total <small>All teams · all available records</small></div>
<div class="cm-stat-bar">
  <div class="cm-stat-tile cm-stat-tile--handled">
    <div class="cm-stat-tile__icon"><i class="fas fa-clipboard-check"></i></div>
    <div class="cm-stat-tile__val" id="cmOHandledToday" style="color:#00d4e8!important;">—</div>
    <div class="cm-stat-tile__lbl">Total Handled</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--assigned">
    <div class="cm-stat-tile__icon"><i class="fas fa-ticket-alt"></i></div>
    <div class="cm-stat-tile__val" id="cmOAssignedTickets" style="color:#1e90ff!important;">—</div>
    <div class="cm-stat-tile__lbl">Assigned Tickets</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--progress">
    <div class="cm-stat-tile__icon"><i class="fas fa-spinner"></i></div>
    <div class="cm-stat-tile__val" id="cmOInProgress" style="color:#a78bfa!important;">—</div>
    <div class="cm-stat-tile__lbl">In Progress</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--completed">
    <div class="cm-stat-tile__icon"><i class="fas fa-circle-check"></i></div>
    <div class="cm-stat-tile__val" id="cmOCompletedToday" style="color:#10b981!important;">—</div>
    <div class="cm-stat-tile__lbl">Completed Tickets</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--cancelled">
    <div class="cm-stat-tile__icon"><i class="fas fa-ban"></i></div>
    <div class="cm-stat-tile__val" id="cmOCancelledToday" style="color:#ff4d4f!important;">—</div>
    <div class="cm-stat-tile__lbl">Cancelled Tickets</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--calls">
    <div class="cm-stat-tile__icon"><i class="fas fa-phone-volume"></i></div>
    <div class="cm-stat-tile__val" id="cmOTotalCalls" style="color:#f8fafc!important;">—</div>
    <div class="cm-stat-tile__lbl">Total Calls</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--scheduled">
    <div class="cm-stat-tile__icon"><i class="fas fa-calendar-check"></i></div>
    <div class="cm-stat-tile__val" id="cmOCallsScheduled" style="color:#00d4e8!important;">—</div>
    <div class="cm-stat-tile__lbl">Calls Scheduled</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--connected">
    <div class="cm-stat-tile__icon"><i class="fas fa-headset"></i></div>
    <div class="cm-stat-tile__val" id="cmOConnected" style="color:#10b981!important;">—</div>
    <div class="cm-stat-tile__lbl">Connected</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--missed">
    <div class="cm-stat-tile__icon"><i class="fas fa-phone-slash"></i></div>
    <div class="cm-stat-tile__val" id="cmOMissedAbsent" style="color:#fbbf24!important;">—</div>
    <div class="cm-stat-tile__lbl">Missed / Absent</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--updates">
    <div class="cm-stat-tile__icon"><i class="fas fa-comment-dots"></i></div>
    <div class="cm-stat-tile__val" id="cmOUpdates" style="color:#a78bfa!important;">—</div>
    <div class="cm-stat-tile__lbl">Updates</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--warn">
    <div class="cm-stat-tile__icon"><i class="fas fa-triangle-exclamation"></i></div>
    <div class="cm-stat-tile__val" id="cmOWarnings" style="color:#fbbf24!important;">—</div>
    <div class="cm-stat-tile__lbl">Warnings</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--mistakes">
    <div class="cm-stat-tile__icon"><i class="fas fa-clock-rotate-left"></i></div>
    <div class="cm-stat-tile__val" id="cmOMistakes" style="color:#ff4d4f!important;">—</div>
    <div class="cm-stat-tile__lbl">Mistakes</div>
  </div>
</div>

<!-- Today stat bar -->
<div class="cm-section-title"><i class="fas fa-calendar-day me-1"></i> Today <small>All teams · today only</small></div>
<div class="cm-stat-bar">
  <div class="cm-stat-tile cm-stat-tile--handled">
    <div class="cm-stat-tile__icon"><i class="fas fa-clipboard-check"></i></div>
    <div class="cm-stat-tile__val" id="cmSHandledToday" style="color:#00d4e8!important;">—</div>
    <div class="cm-stat-tile__lbl">Handled Today</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--assigned">
    <div class="cm-stat-tile__icon"><i class="fas fa-ticket-alt"></i></div>
    <div class="cm-stat-tile__val" id="cmSAssignedTickets" style="color:#1e90ff!important;">—</div>
    <div class="cm-stat-tile__lbl">Assigned Tickets</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--progress">
    <div class="cm-stat-tile__icon"><i class="fas fa-spinner"></i></div>
    <div class="cm-stat-tile__val" id="cmSInProgress" style="color:#a78bfa!important;">—</div>
    <div class="cm-stat-tile__lbl">In Progress</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--completed">
    <div class="cm-stat-tile__icon"><i class="fas fa-circle-check"></i></div>
    <div class="cm-stat-tile__val" id="cmSCompletedToday" style="color:#10b981!important;">—</div>
    <div class="cm-stat-tile__lbl">Completed Today</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--cancelled">
    <div class="cm-stat-tile__icon"><i class="fas fa-ban"></i></div>
    <div class="cm-stat-tile__val" id="cmSCancelledToday" style="color:#ff4d4f!important;">—</div>
    <div class="cm-stat-tile__lbl">Cancelled Today</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--calls">
    <div class="cm-stat-tile__icon"><i class="fas fa-phone-volume"></i></div>
    <div class="cm-stat-tile__val" id="cmSTotalCalls" style="color:#f8fafc!important;">—</div>
    <div class="cm-stat-tile__lbl">Total Calls</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--scheduled">
    <div class="cm-stat-tile__icon"><i class="fas fa-calendar-check"></i></div>
    <div class="cm-stat-tile__val" id="cmSCallsScheduled" style="color:#00d4e8!important;">—</div>
    <div class="cm-stat-tile__lbl">Calls Scheduled</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--connected">
    <div class="cm-stat-tile__icon"><i class="fas fa-headset"></i></div>
    <div class="cm-stat-tile__val" id="cmSConnected" style="color:#10b981!important;">—</div>
    <div class="cm-stat-tile__lbl">Connected</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--missed">
    <div class="cm-stat-tile__icon"><i class="fas fa-phone-slash"></i></div>
    <div class="cm-stat-tile__val" id="cmSMissedAbsent" style="color:#fbbf24!important;">—</div>
    <div class="cm-stat-tile__lbl">Missed / Absent</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--updates">
    <div class="cm-stat-tile__icon"><i class="fas fa-comment-dots"></i></div>
    <div class="cm-stat-tile__val" id="cmSUpdates" style="color:#a78bfa!important;">—</div>
    <div class="cm-stat-tile__lbl">Updates</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--warn">
    <div class="cm-stat-tile__icon"><i class="fas fa-triangle-exclamation"></i></div>
    <div class="cm-stat-tile__val" id="cmSWarnings" style="color:#fbbf24!important;">—</div>
    <div class="cm-stat-tile__lbl">Warnings</div>
  </div>
  <div class="cm-stat-tile cm-stat-tile--mistakes">
    <div class="cm-stat-tile__icon"><i class="fas fa-clock-rotate-left"></i></div>
    <div class="cm-stat-tile__val" id="cmSMistakes" style="color:#ff4d4f!important;">—</div>
    <div class="cm-stat-tile__lbl">Mistakes</div>
  </div>
</div>

<!-- Charts row -->
<div class="cm-charts-row">
  <div class="cm-card">
    <div class="cm-card__title">Team Performance</div>
    <div style="position:relative;height:220px;">
      <canvas id="cmTeamPerfChart"></canvas>
    </div>
  </div>
  <div class="cm-card">
    <div class="cm-card__title">Task Status</div>
    <div style="position:relative;height:220px;">
      <canvas id="cmTaskStatusChart"></canvas>
    </div>
  </div>
</div>

<!-- Top CX usage graphs -->
<div class="cm-top-usage-row">
  <div class="cm-card">
    <div class="cm-card__title"><i class="fas fa-map-location-dot"></i> Top City Used by CX <span style="color:var(--cm-muted);font-size:.72rem;font-weight:700;">(by region)</span></div>
    <div style="position:relative;height:220px;">
      <canvas id="cmTopCityChart"></canvas>
    </div>
  </div>
  <div class="cm-card">
    <div class="cm-card__title"><i class="fas fa-tags"></i> Top Brands</div>
    <div style="position:relative;height:220px;">
      <canvas id="cmTopBrandsChart"></canvas>
    </div>
  </div>
  <div class="cm-card">
    <div class="cm-card__title"><i class="fas fa-screwdriver-wrench"></i> Top Appliance</div>
    <div style="position:relative;height:220px;">
      <canvas id="cmTopApplianceChart"></canvas>
    </div>
  </div>
</div>

<!-- Admin old-dashboard graphs integrated into CSR Manager layout -->
<div class="cm-charts-row">
  <div class="cm-card">
    <div class="cm-card__title"><i class="fas fa-bolt"></i> Urgency Distribution</div>
    <div style="position:relative;height:220px;">
      <canvas id="cmUrgencyChart"></canvas>
    </div>
  </div>
  <div class="cm-card">
    <div class="cm-card__title"><i class="fas fa-clock"></i> Peak Hours</div>
    <div style="position:relative;height:220px;">
      <canvas id="cmPeakHoursChart"></canvas>
    </div>
  </div>
</div>

<!-- Bottom row: team cards + warnings + mistakes -->
<div class="cm-bottom-row">
  <div class="cm-team-cards-area" id="cmTeamCardsArea">
    <div class="cm-team-card cm-skeleton" style="height:160px;"></div>
    <div class="cm-team-card cm-skeleton" style="height:160px;"></div>
  </div>
  <div class="cm-mistakes-panel">
    <div class="cm-mistakes-hdr">
      <i class="fas fa-triangle-exclamation" style="color:var(--cm-yellow);"></i>
      <span class="cm-mistakes-title">Recent Warnings</span>
      <span id="cmWarningBadge" class="cm-badge cm-badge--yellow">0</span>
    </div>
    <div class="cm-disc-filter">
      <select id="cmWarningDateFilter" aria-label="Warning date filter">
        <option value="all">All dates</option>
        <option value="today">Today</option>
        <option value="7">Last 7 days</option>
        <option value="30">Last 30 days</option>
      </select>
      <input id="cmWarningSearchFilter" type="search" placeholder="Search team / name / title">
    </div>
    <div id="cmWarningsBoard">
      <div style="text-align:center;color:var(--cm-muted);font-size:.8rem;padding:20px 0;">Loading…</div>
    </div>
  </div>

  <div class="cm-mistakes-panel">
    <div class="cm-mistakes-hdr">
      <i class="fas fa-circle-exclamation" style="color:var(--cm-red);"></i>
      <span class="cm-mistakes-title">Recent Mistakes</span>
      <span id="cmMistakeBadge" class="cm-badge cm-badge--yellow">0</span>
    </div>
    <div class="cm-disc-filter">
      <select id="cmMistakeDateFilter" aria-label="Mistake date filter">
        <option value="all">All dates</option>
        <option value="today">Today</option>
        <option value="7">Last 7 days</option>
        <option value="30">Last 30 days</option>
      </select>
      <input id="cmMistakeSearchFilter" type="search" placeholder="Search team / name / title">
    </div>
    <div id="cmMistakesBoard">
      <div style="text-align:center;color:var(--cm-muted);font-size:.8rem;padding:20px 0;">Loading…</div>
    </div>
  </div>
</div>


<div class="cm-detail-backdrop" id="cmDetailModal" onclick="cmCloseDetailModal(event)">
  <div class="cm-detail-modal" onclick="event.stopPropagation()">
    <div class="cm-detail-head">
      <div>
        <h3 class="cm-detail-title" id="cmDetailTitle">Details</h3>
        <div class="cm-detail-sub" id="cmDetailSub"></div>
      </div>
      <button type="button" class="cm-detail-close" onclick="cmCloseDetailModal()">×</button>
    </div>
    <div class="cm-detail-body" id="cmDetailBody"></div>
  </div>
</div>


<script>
function cmGoBack() {
  if (window.history.length > 1) {
    window.history.back();
    return;
  }
  window.location.href = 'dashboard.php';
}
/* ============================================================
   Dashboard data + charts
   ============================================================ */
const CM = {
  gh:       'rgba(96,165,250,.85)',
  sched:    'rgba(52,211,153,.90)',
  attempt:  'rgba(167,139,250,.85)',
  mistake:  'rgba(248,113,113,.85)',
  grid:     'rgba(255,255,255,.05)',
  tick:     'rgba(255,255,255,.55)',
  fs:       11,
};

let _teamPerf = null, _taskStatus = null, _topCity = null, _topBrands = null, _topAppliance = null, _urgency = null, _peakHours = null;
let _cmWarningRows = [], _cmMistakeRows = [];

function cmDashLoad() {
  const icon = document.getElementById('cmRefreshIcon');
  if (icon) icon.classList.add('fa-spin');

  $.ajax({
    url: 'ajax/get_admin_manager_dashboard.php',
    method: 'GET',
    dataType: 'json',
    success: function(res) {
      if (!res.success) { console.warn(res.message); return; }
      cmRenderOverallStats(res.summary_overall || res.summary || {});
      cmRenderStats(res.summary_today || res.summary || {});
      cmRenderTeamPerf(res.team_stats_overall || res.team_stats || []);
      cmRenderTaskStatus(res.task_status || []);
      cmRenderTopUsageCharts(res);
      cmRenderAdminExtraCharts(res);
      cmRenderTeamCards(res.team_stats_overall || res.team_stats);
      cmRenderWarnings(res.warning_records || []);
      cmRenderMistakes(res.mistakes || []);
      cmApplyAllNumberColors();
    },
    complete: function() {
      if (icon) icon.classList.remove('fa-spin');
      cmApplyAllNumberColors();
    }
  });
}

function cmRenderOverallStats(s) {
  const map = {
    cmOHandledToday:    s.handled_today,
    cmOAssignedTickets: s.assigned_tickets,
    cmOInProgress:      s.in_progress,
    cmOCompletedToday:  s.completed_today,
    cmOCancelledToday:  s.cancelled_today,
    cmOTotalCalls:      s.total_calls,
    cmOCallsScheduled:  s.calls_scheduled,
    cmOConnected:       s.connected,
    cmOMissedAbsent:    s.missed_absent,
    cmOUpdates:         s.updates,
    cmOWarnings:        s.warnings,
    cmOMistakes:        s.mistakes
  };
  Object.entries(map).forEach(([id, val]) => cmAnimCount(id, val || 0));
}

function cmRenderStats(s) {
  const map = {
    cmSHandledToday:    s.handled_today,
    cmSAssignedTickets: s.assigned_tickets,
    cmSInProgress:      s.in_progress,
    cmSCompletedToday:  s.completed_today,
    cmSCancelledToday:  s.cancelled_today,
    cmSTotalCalls:      s.total_calls,
    cmSCallsScheduled:  s.calls_scheduled,
    cmSConnected:       s.connected,
    cmSMissedAbsent:    s.missed_absent,
    cmSUpdates:         s.updates,
    cmSWarnings:        s.warnings,
    cmSMistakes:        s.mistakes
  };
  Object.entries(map).forEach(([id, val]) => cmAnimCount(id, val || 0));
}

const CM_NUM_COLORS = {
  cmOHandledToday:'#00d4e8', cmSHandledToday:'#00d4e8',
  cmOAssignedTickets:'#1e90ff', cmSAssignedTickets:'#1e90ff',
  cmOInProgress:'#a78bfa', cmSInProgress:'#a78bfa',
  cmOCompletedToday:'#10b981', cmSCompletedToday:'#10b981',
  cmOCancelledToday:'#ff4d4f', cmSCancelledToday:'#ff4d4f',
  cmOTotalCalls:'#f8fafc', cmSTotalCalls:'#f8fafc',
  cmOCallsScheduled:'#00d4e8', cmSCallsScheduled:'#00d4e8',
  cmOConnected:'#10b981', cmSConnected:'#10b981',
  cmOMissedAbsent:'#fbbf24', cmSMissedAbsent:'#fbbf24',
  cmOUpdates:'#a78bfa', cmSUpdates:'#a78bfa',
  cmOWarnings:'#fbbf24', cmSWarnings:'#fbbf24',
  cmOMistakes:'#ff4d4f', cmSMistakes:'#ff4d4f'
};
function cmApplyNumberColor(id) {
  const el = document.getElementById(id);
  if (!el || !CM_NUM_COLORS[id]) return;
  el.style.setProperty('color', CM_NUM_COLORS[id], 'important');
  const tile = el.closest('.cm-stat-tile');
  if (tile) {
    const icon = tile.querySelector('.cm-stat-tile__icon, .cm-stat-tile__icon i');
    const iconWrap = tile.querySelector('.cm-stat-tile__icon');
    if (icon) icon.style.setProperty('color', CM_NUM_COLORS[id], 'important');
    if (iconWrap) iconWrap.style.setProperty('color', CM_NUM_COLORS[id], 'important');
  }
}
function cmApplyAllNumberColors() {
  Object.keys(CM_NUM_COLORS).forEach(cmApplyNumberColor);
}

function cmAnimCount(id, target) {
  const el = document.getElementById(id);
  if (!el) return;
  cmApplyNumberColor(id);
  const start = parseInt(el.textContent) || 0;
  const steps = 18; let i = 0;
  const step = () => { i++; el.textContent = Math.round(start + (target - start) * (i / steps)); if (i < steps) requestAnimationFrame(step); else { el.textContent = target; cmApplyNumberColor(id); } };
  requestAnimationFrame(step);
}

function cmRenderTeamPerf(ts) {
  const canvas = document.getElementById('cmTeamPerfChart');
  if (!canvas) return;
  const rows = Array.isArray(ts) && ts.length ? ts : [{
    team_name: 'No team data yet',
    handled_today: 0,
    assigned_tickets: 0,
    completed_today: 0,
    connected: 0
  }];
  const ctx = canvas.getContext('2d');
  if (_teamPerf) _teamPerf.destroy();
  _teamPerf = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: rows.map(t => String(t.team_name || 'Team').replace(/^(Team |TEAM )/i,'')),
      datasets: [
        { label:'Handled', data: rows.map(t=>parseInt(t.handled_today)||0), backgroundColor: CM.gh, borderRadius:4, barPercentage:0.28 },
        { label:'Assigned', data: rows.map(t=>parseInt(t.assigned_tickets)||0), backgroundColor: CM.sched, borderRadius:4, barPercentage:0.28 },
        { label:'Completed', data: rows.map(t=>parseInt(t.completed_today)||0), backgroundColor: 'rgba(52,211,153,.75)', borderRadius:4, barPercentage:0.28 },
        { label:'Connected', data: rows.map(t=>parseInt(t.connected)||0), backgroundColor: CM.attempt, borderRadius:4, barPercentage:0.28 },
      ]
    },
    options: cmChartOpts()
  });
}

function cmRenderTaskStatus(ts) {
  const canvas = document.getElementById('cmTaskStatusChart');
  if (!canvas) return;
  const rows = Array.isArray(ts) && ts.length ? ts : [{ status_name:'No status data yet', cnt:0, color_code:'#60a5fa' }];
  const ctx = canvas.getContext('2d');
  if (_taskStatus) _taskStatus.destroy();
  _taskStatus = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: rows.map(t => String(t.status_name || 'Unknown')),
      datasets: [{ data: rows.map(t => parseInt(t.cnt)||0), backgroundColor: rows.map(t => t.color_code||'#4fc3f7'), borderWidth:1, borderColor:'oklch(0.18 0.04 262)' }]
    },
    options: {
      responsive:true, maintainAspectRatio:false, cutout:'58%',
      plugins: {
        legend: { position:'right', labels:{ color:CM.tick, font:{size:CM.fs-1,family:'Inter'}, boxWidth:10, padding:6 } },
        tooltip: cmTooltipCfg()
      }
    }
  });
}

function cmRenderTopUsageCharts(res) {
  const cityRows = (res.top_cities && res.top_cities.length) ? res.top_cities.map(r => ({
    label: (r.region ? `${r.city} — ${r.region}` : r.city),
    cnt: r.cnt
  })) : (res.top_regions || []).map(r => ({ label: r.region, cnt: r.cnt }));
  _topCity = cmRenderSimpleTopBar('cmTopCityChart', _topCity, cityRows, 'label', 'cnt', 'Requests', CM.gh);
  _topBrands = cmRenderSimpleTopBar('cmTopBrandsChart', _topBrands, res.top_brands || [], 'name', 'cnt', 'Requests', CM.sched);
  _topAppliance = cmRenderSimpleTopBar('cmTopApplianceChart', _topAppliance, res.top_appliances || [], 'name', 'cnt', 'Requests', CM.attempt);
}

function cmRenderAdminExtraCharts(res) {
  const urgencyRows = (res.urgency_distribution && res.urgency_distribution.length) ? res.urgency_distribution : [{ label:'No data yet', cnt:0 }];
  const urgencyEl = document.getElementById('cmUrgencyChart');
  if (urgencyEl) {
    if (_urgency) _urgency.destroy();
    _urgency = new Chart(urgencyEl.getContext('2d'), {
      type: 'doughnut',
      data: {
        labels: urgencyRows.map(r => String(r.label || 'Normal')),
        datasets: [{ data: urgencyRows.map(r => parseInt(r.cnt)||0), backgroundColor: [CM.sched, CM.gh, CM.mistake, CM.attempt, 'rgba(251,191,36,.9)'], borderWidth:1, borderColor:'oklch(0.18 0.04 262)' }]
      },
      options: {
        responsive:true, maintainAspectRatio:false, cutout:'58%',
        plugins: { legend:{ position:'right', labels:{ color:CM.tick, font:{size:CM.fs-1,family:'Inter'}, boxWidth:10, padding:6 } }, tooltip:cmTooltipCfg() }
      }
    });
  }

  const peakRows = (res.peak_hours && res.peak_hours.length) ? res.peak_hours : [{ label:'No data yet', cnt:0 }];
  const peakEl = document.getElementById('cmPeakHoursChart');
  if (peakEl) {
    if (_peakHours) _peakHours.destroy();
    _peakHours = new Chart(peakEl.getContext('2d'), {
      type: 'bar',
      data: {
        labels: peakRows.map(r => String(r.label || r.hour || '—')),
        datasets: [{ label:'Requests', data: peakRows.map(r => parseInt(r.cnt)||0), backgroundColor: CM.attempt, borderRadius:5, barPercentage:.42 }]
      },
      options: cmChartOpts()
    });
  }
}

function cmRenderSimpleTopBar(canvasId, chartRef, rows, labelKey, valueKey, label, color) {
  const canvas = document.getElementById(canvasId);
  if (!canvas) return chartRef;
  const ctx = canvas.getContext('2d');
  if (chartRef) chartRef.destroy();

  const safeRows = (rows && rows.length) ? rows : [{ [labelKey]: 'No data yet', [valueKey]: 0 }];

  return new Chart(ctx, {
    type: 'bar',
    data: {
      labels: safeRows.map(r => String(r[labelKey] || 'Unknown')),
      datasets: [{
        label: label,
        data: safeRows.map(r => parseInt(r[valueKey]) || 0),
        backgroundColor: color,
        borderRadius: 5,
        barPercentage: 0.42
      }]
    },
    options: {
      ...cmChartOpts(),
      indexAxis: 'y',
      plugins: {
        legend: { display: false },
        tooltip: cmTooltipCfg()
      },
      scales: {
        x: { beginAtZero: true, grid: { color: CM.grid }, ticks: { color: CM.tick, font: { size: CM.fs - 1 }, precision: 0 } },
        y: { grid: { display: false }, ticks: { color: CM.tick, font: { size: CM.fs - 1 } } }
      }
    }
  });
}


function cmCloseDetailModal(e){
  if (e && e.target && e.target.id !== 'cmDetailModal') return;
  const m = document.getElementById('cmDetailModal');
  if (m) m.classList.remove('is-open');
}
function cmOpenDetailModal(title, sub, body){
  const m = document.getElementById('cmDetailModal');
  if (!m) return;
  document.getElementById('cmDetailTitle').textContent = title || 'Details';
  document.getElementById('cmDetailSub').textContent = sub || '';
  document.getElementById('cmDetailBody').innerHTML = body || '<div style="color:var(--cm-muted);">No details available.</div>';
  m.classList.add('is-open');
}
function cmFmtDate(v){
  if (!v) return '';
  const d = new Date(String(v).replace(' ', 'T'));
  if (isNaN(d.getTime())) return String(v);
  return d.toLocaleString();
}
function cmOpenDisciplineDetails(kind, item){
  item = item || {};
  const count = parseInt(kind === 'warning' ? item.warnings : item.mistakes) || 0;
  const label = kind === 'warning' ? 'Warning' : 'Mistake';
  const details = Array.isArray(item.details) ? item.details : [];
  const body = details.length ? details.map(d => `
    <div class="cm-detail-item">
      <div class="cm-detail-line">
        <div class="cm-detail-item-title">${cmEsc(d.title || label)}</div>
        <span class="cm-detail-pill">${cmEsc(d.severity || 'normal')}</span>
      </div>
      <div class="cm-detail-message">${cmEsc(d.message || 'No message provided.')}</div>
      <div class="cm-detail-meta">Sent by ${cmEsc(d.sender || 'Unknown')} • ${cmEsc(cmFmtDate(d.created_at))}</div>
    </div>`).join('') : '<div style="color:var(--cm-muted);">No individual details found for this record.</div>';
  cmOpenDetailModal(`${label} Details — ${item.name || 'User'}`, `${item.team || 'No team'} • Total ${label.toLowerCase()}s: ${count}`, body);
}
function cmOpenTeamDetails(t){
  t = t || {};
  const rows = [
    ['Agents', t.agents], ['Total Handled', t.handled_today], ['Assigned Tickets', t.assigned_tickets], ['In Progress', t.in_progress],
    ['Completed Tickets', t.completed_today], ['Cancelled Tickets', t.cancelled_today], ['Total Calls', t.total_calls], ['Calls Scheduled', t.calls_scheduled],
    ['Connected', t.connected], ['Missed / Absent', t.missed_absent], ['Updates', t.updates], ['Warnings', t.warnings], ['Mistakes', t.mistakes]
  ];
  const body = `<table class="cm-detail-table">${rows.map(r => `<tr><td>${cmEsc(r[0])}</td><td>${r[1] ?? 0}</td></tr>`).join('')}</table>`;
  cmOpenDetailModal(`${t.team_name || 'Team'} Details`, 'Team summary breakdown', body);
}

function cmRenderTeamCards(ts) {
  const area = document.getElementById('cmTeamCardsArea');
  if (!ts || !ts.length) { area.innerHTML = '<div style="color:var(--cm-muted);">No teams found.</div>'; return; }
  const colors = ['#22d3ee','#34d399','#a78bfa','#facc15'];
  area.style.gridTemplateColumns = ts.length === 1 ? '1fr' : '1fr 1fr';
  const row = (label, value, color = '', className = '') => `
    <div class="cm-tsr"><span class="cm-tsr__l">${label}</span><span class="cm-tsr__v ${className}" ${color ? `style="color:${color}!important;-webkit-text-fill-color:${color}!important;"` : ''}>${value ?? 0}</span></div>`;
  area.innerHTML = ts.map((t,i) => `
    <div class="cm-team-card is-clickable" onclick='cmOpenTeamDetails(${cmAttr(t)})' title="Click to show team details">
      <div class="cm-team-card__head">
        <div class="cm-team-card__name" style="color:${colors[i%colors.length]}">${cmEsc(t.team_name)}</div>
        <div class="cm-team-card__hint">Team Summary</div>
      </div>
      <div class="cm-team-grid">
        ${row('Agents', t.agents)}
        ${row('Total Handled', t.handled_today, '#22d3ee')}
        ${row('Assigned Tickets', t.assigned_tickets, '#60a5fa')}
        ${row('In Progress', t.in_progress, '#a78bfa')}
        ${row('Completed Tickets', t.completed_today, '#34d399')}
        ${row('Cancelled Tickets', t.cancelled_today, '#fb7185')}
        ${row('Total Calls', t.total_calls, '#38bdf8')}
        ${row('Calls Scheduled', t.calls_scheduled, '#22d3ee')}
        ${row('Connected', t.connected, '#34d399')}
        ${row('Missed / Absent', t.missed_absent, '#facc15')}
        ${row('Updates', t.updates, '#a78bfa')}
        ${row('Warnings', t.warnings, '#facc15')}
        ${row('Mistakes', t.mistakes, '#fb7185')}
      </div>
    </div>`).join('');
}

function cmRenderWarnings(warnings) {
  _cmWarningRows = Array.isArray(warnings) ? warnings : [];
  cmRenderDisciplineBoard('warning');
}

function cmRenderMistakes(mistakes) {
  _cmMistakeRows = Array.isArray(mistakes) ? mistakes : [];
  cmRenderDisciplineBoard('mistake');
}

function cmGetDiscFilters(kind) {
  const prefix = kind === 'warning' ? 'Warning' : 'Mistake';
  return {
    date: (document.getElementById(`cm${prefix}DateFilter`) || {}).value || 'all',
    search: ((document.getElementById(`cm${prefix}SearchFilter`) || {}).value || '').trim().toLowerCase()
  };
}

function cmRecordDatePass(item, dateFilter) {
  if (!dateFilter || dateFilter === 'all') return true;
  const details = Array.isArray(item.details) ? item.details : [];
  const dates = details.map(d => d.created_at).filter(Boolean);
  if (!dates.length) return true;
  const now = new Date();
  const startToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  return dates.some(v => {
    const d = new Date(String(v).replace(' ', 'T'));
    if (isNaN(d.getTime())) return false;
    if (dateFilter === 'today') return d >= startToday;
    const days = parseInt(dateFilter) || 0;
    if (!days) return true;
    const start = new Date(startToday);
    start.setDate(start.getDate() - (days - 1));
    return d >= start;
  });
}

function cmRecordSearchPass(item, q) {
  if (!q) return true;
  const details = Array.isArray(item.details) ? item.details : [];
  const hay = [item.team, item.name, item.updates, item.total_calls]
    .concat(details.flatMap(d => [d.title, d.message, d.sender, d.severity, d.created_at]))
    .join(' ').toLowerCase();
  return hay.includes(q);
}

function cmFilterDisciplineRows(rows, kind) {
  const f = cmGetDiscFilters(kind);
  return rows.filter(item => cmRecordDatePass(item, f.date) && cmRecordSearchPass(item, f.search));
}

function cmRenderDisciplineBoard(kind) {
  const isWarning = kind === 'warning';
  const rows = isWarning ? _cmWarningRows : _cmMistakeRows;
  const filtered = cmFilterDisciplineRows(rows, kind);
  const board = document.getElementById(isWarning ? 'cmWarningsBoard' : 'cmMistakesBoard');
  const badge = document.getElementById(isWarning ? 'cmWarningBadge' : 'cmMistakeBadge');
  if (!board || !badge) return;
  const key = isWarning ? 'warnings' : 'mistakes';
  badge.textContent = filtered.reduce((s,m)=>s+(parseInt(m[key])||0), 0);
  if (!filtered.length) {
    board.innerHTML = `<div class="cm-disc-empty">No ${isWarning ? 'warnings' : 'mistakes'} match this filter.</div>`;
    return;
  }
  board.innerHTML = filtered.map(m => `
    <div class="cm-mistake-row is-clickable" onclick='cmOpenDisciplineDetails("${kind}", ${cmAttr(m)})' title="Click to show ${kind} details">
      <div>
        <span class="cm-mistake-team">${cmEsc(m.team)}</span>
        <span class="cm-mistake-name">${cmEsc(m.name)}</span>
        <span class="cm-mistake-metric">Updates: ${m.updates||0} • Calls: ${m.total_calls||0}</span>
      </div>
      <span class="cm-mistake-badge ${(parseInt(m[key])||0)>=5?'danger':''}">
        <i class="fas ${isWarning ? 'fa-triangle-exclamation' : 'fa-circle-exclamation'} me-1"></i>${m[key]||0}
      </span>
    </div>`).join('');
}

function cmWireDisciplineFilters() {
  ['Warning','Mistake'].forEach(prefix => {
    ['DateFilter','SearchFilter'].forEach(suffix => {
      const el = document.getElementById(`cm${prefix}${suffix}`);
      if (el && !el.dataset.wired) {
        el.dataset.wired = '1';
        el.addEventListener('input', () => cmRenderDisciplineBoard(prefix === 'Warning' ? 'warning' : 'mistake'));
        el.addEventListener('change', () => cmRenderDisciplineBoard(prefix === 'Warning' ? 'warning' : 'mistake'));
      }
    });
  });
}


function cmAttr(obj) { return cmEsc(JSON.stringify(obj || {})); }

function cmEsc(str) {
  return String(str || '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

/* Chart shared options */
function cmChartOpts() {
  return {
    responsive:true, maintainAspectRatio:false,
    plugins: { legend:{ labels:{color:CM.tick, font:{size:CM.fs,family:'Inter'}, boxWidth:10, padding:10} }, tooltip:cmTooltipCfg() },
    scales: {
      x:{ grid:{color:CM.grid}, ticks:{color:CM.tick, font:{size:CM.fs-1}} },
      y:{ beginAtZero:true, grid:{color:CM.grid}, ticks:{color:CM.tick, font:{size:CM.fs-1}} }
    }
  };
}

function cmTooltipCfg() {
  return { backgroundColor:'oklch(0.18 0.04 262)', borderColor:'oklch(0.98 0.005 250 / 0.18)', borderWidth:1, titleColor:'#fff', bodyColor:'rgba(255,255,255,.75)', padding:10, cornerRadius:10 };
}

$(document).ready(function () {
  cmApplyAllNumberColors();
  cmWireDisciplineFilters();
cmDashLoad();
  setInterval(cmDashLoad, 60000);
});
</script>


</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
