<?php
function renderHeader($title, $activePage = '') {
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'StudyTrack';
    $siteUrl = defined('SITE_URL') ? SITE_URL : '';
    $userName = isset($_SESSION['user_name']) ? htmlspecialchars($_SESSION['user_name']) : 'User';
    $userInitial = strtoupper($userName[0]);

    // Load avatar from DB
    $userAvatar = null;
    if (isset($_SESSION['user_id'])) {
        global $pdo;
        try {
            $avQ = $pdo->prepare("SELECT avatar, google_avatar FROM users WHERE id=?");
            $avQ->execute([$_SESSION['user_id']]);
            $avRow = $avQ->fetch();

            if ($avRow) {
                // Priority 1: local uploaded avatar
                if (!empty($avRow['avatar'])) {
                    $absPath = __DIR__ . '/../' . $avRow['avatar'];
                    if (file_exists($absPath)) {
                        $userAvatar = $siteUrl . '/' . $avRow['avatar'] . '?v=' . filemtime($absPath);
                    }
                }
                // Priority 2: Google/Facebook avatar URL
                if (!$userAvatar && !empty($avRow['google_avatar'])) {
                    $userAvatar = $avRow['google_avatar'];
                }
            }
        } catch (Exception $e) { $userAvatar = null; }
    }

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars($title) ?> - <?= $siteName ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="icon" type="image/png" href="https://studytrack.edurx.icu/studytrack/images/studytrack.png">
<link rel="stylesheet" href="<?= $siteUrl ?>/assets/css/style.css">
<script>
// Apply theme before render to prevent flash
(function(){var t=localStorage.getItem('stTheme')||'dark';document.documentElement.setAttribute('data-theme',t);})();
</script>
<style>
/* ── Page Loader ──────────────────────────────────────────────── */
#st-loader {
  position: fixed;
  inset: 0;
  z-index: 999999;
  background: var(--bg-primary, #0a0a0f);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20px;
  transition: opacity 0.35s ease, visibility 0.35s ease;
}
#st-loader.hide {
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
}
.st-loader-logo {
  display: flex;
  align-items: center;
  gap: 12px;
  animation: loaderFadeUp 0.5s ease both;
}
.st-loader-logo img {
  width: 42px;
  height: 42px;
  border-radius: 12px;
}
.st-loader-name {
  font-size: 22px;
  font-weight: 800;
  font-family: 'Sora', 'Inter', sans-serif;
  background: linear-gradient(135deg, #6366f1, #a855f7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: -0.3px;
}
.st-loader-bar-wrap {
  width: 180px;
  height: 3px;
  background: rgba(99,102,241,.15);
  border-radius: 99px;
  overflow: hidden;
  animation: loaderFadeUp 0.5s 0.1s ease both;
}
.st-loader-bar {
  height: 100%;
  width: 0%;
  background: linear-gradient(90deg, #6366f1, #a855f7, #06b6d4);
  border-radius: 99px;
  animation: loaderBar 0.9s 0.15s cubic-bezier(.4,0,.2,1) forwards;
}
.st-loader-dots {
  display: flex;
  gap: 6px;
  animation: loaderFadeUp 0.5s 0.2s ease both;
}
.st-loader-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: rgba(99,102,241,.4);
  animation: loaderDot 1.2s infinite ease-in-out;
}
.st-loader-dot:nth-child(2) { animation-delay: .15s; }
.st-loader-dot:nth-child(3) { animation-delay: .3s; }

@keyframes loaderBar {
  0%   { width: 0%; }
  60%  { width: 75%; }
  100% { width: 100%; }
}
@keyframes loaderDot {
  0%, 60%, 100% { transform: translateY(0); opacity: .4; }
  30%            { transform: translateY(-6px); opacity: 1; }
}
@keyframes loaderFadeUp {
  from { opacity: 0; transform: translateY(10px); }
  to   { opacity: 1; transform: translateY(0); }
}

@keyframes notifSpin {
  from { transform: rotate(0deg); }
  to   { transform: rotate(360deg); }
}
/* ── Notification panel fade-in ── */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-8px) scale(0.97); }
  to   { opacity: 1; transform: translateY(0)    scale(1); }
}

/* ── Bell ring animation (triggered when new notification arrives) ── */
@keyframes bellRing {
  0%   { transform: rotate(0deg);   }
  10%  { transform: rotate(15deg);  }
  20%  { transform: rotate(-12deg); }
  30%  { transform: rotate(10deg);  }
  40%  { transform: rotate(-8deg);  }
  50%  { transform: rotate(5deg);   }
  60%  { transform: rotate(-3deg);  }
  70%  { transform: rotate(2deg);   }
  80%  { transform: rotate(-1deg);  }
  100% { transform: rotate(0deg);   }
}
@keyframes bellPulse {
  0%   { box-shadow: 0 0 0 0   rgba(99,102,241,0.6); }
  50%  { box-shadow: 0 0 0 8px rgba(99,102,241,0);   }
  100% { box-shadow: 0 0 0 0   rgba(99,102,241,0);   }
}
#notifBellBtn.bell-ringing svg {
  animation: bellRing 0.7s ease both;
  transform-origin: top center;
}
#notifBellBtn.bell-ringing {
  animation: bellPulse 0.7s ease both;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="<?= $siteUrl ?>/assets/js/app.js"></script>

<!-- ── Offline / Online Popup ─────────────────────────────────── -->
<style>
/* ── Popup wrapper ── */
#stcp {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%) translateY(140px) scale(0.88);
  z-index: 999999;
  width: 320px;
  border-radius: 20px;
  padding: 0;
  opacity: 0;
  pointer-events: none;
  transition: transform .55s cubic-bezier(.34,1.56,.64,1), opacity .4s ease;
  font-family: 'Plus Jakarta Sans','Outfit','Inter',sans-serif;
  overflow: hidden;
}
#stcp.stcp-show {
  transform: translateX(-50%) translateY(0) scale(1);
  opacity: 1;
  pointer-events: auto;
}

/* ── Offline skin ── */
#stcp.stcp-off {
  background: #0d0d18;
  border: 1px solid rgba(239,68,68,.4);
  box-shadow: 0 0 0 1px rgba(239,68,68,.08),
              0 24px 64px rgba(0,0,0,.7),
              0 0 40px rgba(239,68,68,.08);
}
/* ── Online skin ── */
#stcp.stcp-on {
  background: #0a0f14;
  border: 1px solid rgba(99,102,241,.45);
  box-shadow: 0 0 0 1px rgba(99,102,241,.08),
              0 24px 64px rgba(0,0,0,.7),
              0 0 50px rgba(99,102,241,.12);
}

/* ── Glow strip top ── */
#stcp-glow {
  position: absolute;
  top: 0; left: 0; right: 0;
  height: 1px;
  border-radius: 20px 20px 0 0;
}
.stcp-off #stcp-glow { background: linear-gradient(90deg, transparent, rgba(239,68,68,.9), rgba(251,113,133,.8), transparent); }
.stcp-on  #stcp-glow { background: linear-gradient(90deg, transparent, rgba(99,102,241,.9), rgba(168,85,247,.8), transparent); }

/* ── Inner ── */
#stcp-inner {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px 18px 18px;
  position: relative;
}

/* ── Icon ── */
#stcp-ic {
  width: 46px; height: 46px;
  border-radius: 14px;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
  font-size: 22px;
  position: relative;
  transition: background .3s, border-color .3s;
}
.stcp-off #stcp-ic {
  background: rgba(239,68,68,.12);
  border: 1px solid rgba(239,68,68,.3);
  box-shadow: 0 0 18px rgba(239,68,68,.15);
}
.stcp-on #stcp-ic {
  background: rgba(99,102,241,.12);
  border: 1px solid rgba(99,102,241,.35);
  box-shadow: 0 0 20px rgba(99,102,241,.18);
}

/* ── Icon ring pulse ── */
#stcp-ic::before {
  content: '';
  position: absolute;
  inset: -5px;
  border-radius: 18px;
  opacity: 0;
  animation: stcp-ring 2s ease-in-out infinite;
}
.stcp-off #stcp-ic::before { border: 1.5px solid rgba(239,68,68,.5); }
.stcp-on  #stcp-ic::before { border: 1.5px solid rgba(99,102,241,.6); }
@keyframes stcp-ring {
  0%   { transform: scale(1);    opacity: .7; }
  60%  { transform: scale(1.35); opacity: 0; }
  100% { transform: scale(1.35); opacity: 0; }
}

/* ── SVG wifi icon ── */
#stcp-wifi { display: block; }
.stcp-off #stcp-wifi { animation: stcp-flicker 1.6s ease-in-out infinite; }
@keyframes stcp-flicker {
  0%,100%{ opacity:1 } 45%{ opacity:.2 } 55%{ opacity:.2 } 60%{ opacity:1 }
}

/* ── Text ── */
#stcp-title {
  font-size: 14px; font-weight: 800;
  letter-spacing: -.3px;
  margin-bottom: 3px;
  transition: color .3s;
}
.stcp-off #stcp-title { color: #fca5a5; }
.stcp-on  #stcp-title {
  color: transparent;
  background: linear-gradient(90deg, #818cf8, #c084fc);
  -webkit-background-clip: text;
  background-clip: text;
}
#stcp-sub {
  font-size: 12px;
  color: rgba(255,255,255,.38);
  font-weight: 400;
  line-height: 1.4;
}

/* ── Dots ── */
.stcp-dots { display:inline-flex;gap:3px;align-items:center;vertical-align:middle;margin-left:3px; }
.stcp-dots i { display:block;width:4px;height:4px;border-radius:50%;background:rgba(255,255,255,.35);animation:stcp-db 1.3s ease-in-out infinite; }
.stcp-dots i:nth-child(2){animation-delay:.18s}
.stcp-dots i:nth-child(3){animation-delay:.36s}
@keyframes stcp-db { 0%,80%,100%{transform:scale(.7);opacity:.4} 40%{transform:scale(1.3);opacity:1} }

/* ── Close btn ── */
#stcp-x {
  position: absolute;
  top: 10px; right: 12px;
  width: 22px; height: 22px;
  border-radius: 50%;
  background: rgba(255,255,255,.06);
  border: 1px solid rgba(255,255,255,.1);
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; font-size: 11px; color: rgba(255,255,255,.4);
  line-height: 1;
  transition: background .2s, color .2s;
}
#stcp-x:hover { background: rgba(255,255,255,.13); color: rgba(255,255,255,.8); }

/* ── Progress bar ── */
#stcp-track {
  height: 3px;
  background: rgba(255,255,255,.05);
  border-radius: 0 0 20px 20px;
  overflow: hidden;
}
#stcp-fill {
  height: 100%;
  border-radius: 99px;
  width: 0%;
  transition: width 3.2s linear;
}
.stcp-off #stcp-fill { background: linear-gradient(90deg,#ef4444,#f87171,#fda4af); width: 100%; transition: none; }
.stcp-on  #stcp-fill { background: linear-gradient(90deg,#6366f1,#a855f7,#818cf8); }

/* ── Particles ── */
#stcp-particles { position:absolute;inset:0;pointer-events:none;overflow:hidden;border-radius:20px; }
.stcp-p {
  position: absolute;
  border-radius: 50%;
  opacity: 0;
}
.stcp-on .stcp-p  { background: #818cf8; animation: stcp-float 2.4s ease-out forwards; }
.stcp-off .stcp-p { display: none; }
@keyframes stcp-float {
  0%   { opacity: .7; transform: translateY(0) scale(1); }
  100% { opacity: 0;  transform: translateY(-55px) scale(.3); }
}
</style>
</head>
<body>

<!-- ── Offline / Online Popup ── -->
<div id="stcp">
  <div id="stcp-glow"></div>
  <div id="stcp-particles"></div>
  <div id="stcp-inner">
    <div id="stcp-ic">
      <!-- SVG: wifi with slash for offline, wifi normal for online -->
      <svg id="stcp-wifi" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <!-- arcs -->
        <path id="sw-arc1" d="M5 12.55a11 11 0 0 1 14.08 0" stroke="#6366f1"/>
        <path id="sw-arc2" d="M1.42 9A16 16 0 0 1 22.58 9"  stroke="#a855f7"/>
        <path id="sw-arc3" d="M8.53 16.11a6 6 0 0 1 6.95 0" stroke="#818cf8"/>
        <circle id="sw-dot" cx="12" cy="20" r="1" fill="#c084fc"/>
        <!-- slash (offline only) -->
        <line id="sw-slash" x1="2" y1="2" x2="22" y2="22" stroke="#ef4444" stroke-width="2.2" style="display:none"/>
      </svg>
    </div>
    <div style="flex:1;min-width:0">
      <div id="stcp-title">You're Offline</div>
      <div id="stcp-sub">No internet connection<span class="stcp-dots"><i></i><i></i><i></i></span></div>
    </div>
    <div id="stcp-x" onclick="document.getElementById('stcp').classList.remove('stcp-show')">✕</div>
  </div>
  <div id="stcp-track"><div id="stcp-fill"></div></div>
</div>

<script>
(function(){
  var el    = document.getElementById('stcp');
  var fill  = document.getElementById('stcp-fill');
  var slash = document.getElementById('sw-slash');
  var arc1  = document.getElementById('sw-arc1');
  var arc2  = document.getElementById('sw-arc2');
  var arc3  = document.getElementById('sw-arc3');
  var sdot  = document.getElementById('sw-dot');
  var parts = document.getElementById('stcp-particles');
  var hideT = null;

  function spawnParticles(){
    parts.innerHTML='';
    for(var i=0;i<10;i++){
      (function(i){
        setTimeout(function(){
          var p=document.createElement('div');
          p.className='stcp-p';
          var sz=Math.random()*5+3;
          p.style.cssText='width:'+sz+'px;height:'+sz+'px;left:'+(Math.random()*90+5)+'%;bottom:'+(Math.random()*30+5)+'%;animation-delay:'+Math.random()*.4+'s;animation-duration:'+(1.8+Math.random())+'s';
          parts.appendChild(p);
        },i*80);
      })(i);
    }
  }

  function setOfflineColors(){
    slash.style.display='block';
    [arc1,arc2,arc3].forEach(function(a){ a.setAttribute('stroke','rgba(239,68,68,.35)'); });
    sdot.setAttribute('fill','rgba(239,68,68,.5)');
  }
  function setOnlineColors(){
    slash.style.display='none';
    arc1.setAttribute('stroke','#6366f1');
    arc2.setAttribute('stroke','#a855f7');
    arc3.setAttribute('stroke','#818cf8');
    sdot.setAttribute('fill','#c084fc');
  }

  function showOffline(){
    clearTimeout(hideT);
    el.classList.remove('stcp-on','stcp-show');
    void el.offsetWidth;
    setOfflineColors();
    el.classList.add('stcp-off','stcp-show');
    document.getElementById('stcp-title').textContent = "You're Offline";
    document.getElementById('stcp-sub').innerHTML = 'No internet connection<span class="stcp-dots"><i></i><i></i><i></i></span>';
    fill.style.transition='none'; fill.style.width='100%';
  }

  function showOnline(){
    clearTimeout(hideT);
    el.classList.remove('stcp-off');
    void el.offsetWidth;
    setOnlineColors();
    el.classList.add('stcp-on','stcp-show');
    document.getElementById('stcp-title').textContent = 'Back Online!';
    document.getElementById('stcp-sub').innerHTML = 'Connected successfully';
    fill.style.transition='none'; fill.style.width='0%';
    void fill.offsetWidth;
    fill.style.transition='width 3.2s linear'; fill.style.width='100%';
    spawnParticles();
    hideT=setTimeout(function(){ el.classList.remove('stcp-show'); },3500);
  }

  window.addEventListener('offline', showOffline);
  window.addEventListener('online',  showOnline);
  if(!navigator.onLine) setTimeout(showOffline, 700);
})();
</script>

<!-- ── Page Loader ──────────────────────────────────────────────── -->
<div id="st-loader">
  <div class="st-loader-logo">
    <img src="https://studytrack.edurx.icu/studytrack/images/studytrack.png" alt="StudyTrack">
    <span class="st-loader-name">StudyTrack</span>
  </div>
  <div class="st-loader-bar-wrap">
    <div class="st-loader-bar"></div>
  </div>
  <div class="st-loader-dots">
    <div class="st-loader-dot"></div>
    <div class="st-loader-dot"></div>
    <div class="st-loader-dot"></div>
  </div>
</div>

<script>
// Hide loader once page fully loaded
(function() {
  function hideLoader() {
    var l = document.getElementById('st-loader');
    if (l) {
      l.classList.add('hide');
      setTimeout(function(){ if(l.parentNode) l.parentNode.removeChild(l); }, 400);
    }
  }
  if (document.readyState === 'complete') {
    setTimeout(hideLoader, 300);
  } else {
    window.addEventListener('load', function() {
      setTimeout(hideLoader, 300);
    });
  }
  // Safety fallback — never stay longer than 3s
  setTimeout(hideLoader, 3000);
})();
</script>

<div class="app-layout">
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<aside class="sidebar" id="sidebar">
  <div class="sidebar-header">
    <a href="<?= $siteUrl ?>/dashboard" class="st-logo-link">
      <div class="st-logo-icon">
        <img src="https://studytrack.edurx.icu/studytrack/images/studytrack.png" alt="StudyTrack">
      </div>
      <div class="st-logo-text">
        <span class="st-logo-name"><?= $siteName ?></span>
        <span class="st-logo-tag">BY EDURX</span>
      </div>
    </a>
  </div>
  <style>
  .st-logo-link {
    display: flex;
    align-items: center;
    gap: 11px;
    text-decoration: none;
    padding: 2px 4px;
    border-radius: 12px;
    transition: opacity .2s;
  }
  .st-logo-link:hover { opacity: .8; }
  .st-logo-icon {
    width: 36px; height: 36px;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
  }
  .st-logo-icon img {
    width: 36px; height: 36px;
    object-fit: contain;
    border-radius: 10px;
  }
  .st-logo-text {
    display: flex; flex-direction: column; gap: 1px;
    min-width: 0;
  }
  .st-logo-name {
    font-size: 16px;
    font-weight: 800;
    font-family: 'Sora', 'Inter', sans-serif;
    background: linear-gradient(135deg, #c7d2fe, #a78bfa);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    letter-spacing: -0.2px;
    line-height: 1.2;
  }
  .st-logo-tag {
    font-size: 10px;
    font-weight: 500;
    color: var(--text-muted);
    letter-spacing: .3px;
    line-height: 1;
  }
  [data-theme="light"] .st-logo-name {
    background: linear-gradient(135deg, #4f46e5, #7c3aed);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
  [data-theme="light"] .st-logo-icon {
    background: linear-gradient(135deg, rgba(99,102,241,.1), rgba(168,85,247,.1));
    border-color: rgba(99,102,241,.2);
  }
  </style>
<style>
/* ── Themed Nav ───────────────────────────────────────────────── */
.nav-item { text-decoration:none; display:flex; align-items:center; gap:10px; padding:7px 10px; border-radius:10px; font-size:13px; font-weight:500; color:var(--text-secondary); transition:all .18s; margin-bottom:1px; position:relative; }
.nav-item:hover { color:var(--text-primary); background:rgba(255,255,255,.04); }
.nav-item.active { font-weight:600; color:#c4b5fd; background:rgba(99,102,241,.1); }
.nav-item.active::before { content:''; position:absolute; left:0; top:22%; bottom:22%; width:3px; background:linear-gradient(180deg,#6366f1,#a855f7); border-radius:0 3px 3px 0; }
.ni { width:28px; height:28px; border-radius:7px; display:flex; align-items:center; justify-content:center; flex-shrink:0; transition:all .18s; }
.ni svg { width:14px; height:14px; stroke-width:2; }
.ni-indigo  { background:rgba(99,102,241,.14);  color:#818cf8; }
.ni-cyan    { background:rgba(6,182,212,.14);   color:#22d3ee; }
.ni-emerald { background:rgba(16,185,129,.14);  color:#34d399; }
.ni-violet  { background:rgba(139,92,246,.14);  color:#a78bfa; }
.ni-amber   { background:rgba(245,158,11,.14);  color:#fbbf24; }
.ni-rose    { background:rgba(244,63,94,.14);   color:#fb7185; }
.ni-sky     { background:rgba(56,189,248,.14);  color:#7dd3fc; }
.ni-teal    { background:rgba(20,184,166,.14);  color:#2dd4bf; }
.ni-orange  { background:rgba(249,115,22,.14);  color:#fb923c; }
.ni-pink    { background:rgba(236,72,153,.14);  color:#f472b6; }
.ni-lime    { background:rgba(132,204,22,.14);  color:#a3e635; }
.ni-purple  { background:rgba(168,85,247,.14);  color:#c084fc; }
.ni-blue    { background:rgba(59,130,246,.14);  color:#60a5fa; }
.ni-fuchsia { background:rgba(217,70,239,.14);  color:#e879f9; }
.nav-item:hover .ni { filter:brightness(1.15); transform:scale(1.08); }
.nav-item.active .ni { filter:brightness(1.25); }
</style>

<nav class="sidebar-nav">

  <div class="nav-section">
    <div class="nav-section-title">Main</div>
    <a href="<?= $siteUrl ?>/dashboard" class="nav-item <?= $activePage==='dashboard'?'active':'' ?>">
      <span class="ni ni-indigo"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg></span>
      Dashboard
    </a>
        <a href="<?= $siteUrl ?>/subjects" class="nav-item <?= $activePage==='subjects'?'active':'' ?>">
      <span class="ni ni-violet"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg></span>
      Subjects
    </a>
    <a href="<?= $siteUrl ?>/study-log" class="nav-item <?= $activePage==='study-log'?'active':'' ?>">
      <span class="ni ni-cyan"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg></span>
      Study Log
    </a>
    <a href="<?= $siteUrl ?>/marks" class="nav-item <?= $activePage==='marks'?'active':'' ?>">
      <span class="ni ni-emerald"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg></span>
      Marks & Results
    </a>

        <a href="<?= $siteUrl ?>/class-hours" class="nav-item <?= $activePage==='class-hours'?'active':'' ?>">
      <span class="ni ni-orange"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg></span>
      Class Hours
    </a>
    
    <a href="<?= $siteUrl ?>/tasks" class="nav-item <?= $activePage==='tasks'?'active':'' ?>">
      <span class="ni ni-amber"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg></span>
      Tasks
    </a>
  </div>

  <div class="nav-section">
    <div class="nav-section-title">Analytics</div>
    <a href="<?= $siteUrl ?>/analysis" class="nav-item <?= $activePage==='analysis'?'active':'' ?>">
      <span class="ni ni-sky"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg></span>
      Analysis
    </a>
    <!--<a href="<?= $siteUrl ?>/ai-analysis" class="nav-item <?= $activePage==='ai-analysis'?'active':'' ?>">
      <span class="ni ni-purple"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 1 1 7.072 0l-.548.547A3.374 3.374 0 0 0 14 18.469V19a2 2 0 1 1-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg></span>
      AI Analysis
    </a>-->
    <a href="<?= $siteUrl ?>/progress" class="nav-item <?= $activePage==='progress'?'active':'' ?>">
      <span class="ni ni-teal"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg></span>
      Progress
    </a>
  </div>

  <div class="nav-section">
    <div class="nav-section-title">Features</div>
    <a href="<?= $siteUrl ?>/timetable" class="nav-item <?= $activePage==='timetable'?'active':'' ?>">
      <span class="ni ni-blue"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg></span>
      Timetable
    </a>

    <a href="<?= $siteUrl ?>/past-papers" class="nav-item <?= $activePage==='past-papers'?'active':'' ?>">
      <span class="ni ni-rose"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg></span>
      Past Papers
    </a>
    <a href="<?= $siteUrl ?>/resources" class="nav-item <?= $activePage==='resources'?'active':'' ?>">
      <span class="ni ni-lime"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg></span>
      Resources
    </a>
    <a href="<?= $siteUrl ?>/goals" class="nav-item <?= $activePage==='goals'?'active':'' ?>">
      <span class="ni ni-amber"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg></span>
      Goals
    </a>
    <a href="<?= $siteUrl ?>/notes" class="nav-item <?= $activePage==='notes'?'active':'' ?>">
      <span class="ni ni-pink"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></span>
      Notes & Flashcards
    </a>
    <a href="<?= $siteUrl ?>/reminders" class="nav-item <?= $activePage==='reminders'?'active':'' ?>">
      <span class="ni ni-violet"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg></span>
      Reminders
    </a>
    <a href="<?= $siteUrl ?>/heatmap" class="nav-item <?= $activePage==='heatmap'?'active':'' ?>">
      <span class="ni ni-indigo"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg></span>
      Study Heatmap
    </a>
    <a href="<?= $siteUrl ?>/report" class="nav-item <?= $activePage==='report'?'active':'' ?>">
      <span class="ni ni-sky"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg></span>
      Reports
    </a>
    <a href="<?= $siteUrl ?>/achievements" class="nav-item <?= $activePage==='achievements'?'active':'' ?>">
      <span class="ni ni-amber"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="8" r="6"/><path d="M15.477 12.89L17 22l-5-3-5 3 1.523-9.11"/></svg></span>
      Achievements
    </a>
    <a href="<?= $siteUrl ?>/leaderboard" class="nav-item <?= $activePage==='leaderboard'?'active':'' ?>">
      <span class="ni ni-fuchsia"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg></span>
      Leaderboard
    </a>
    <a href="<?= $siteUrl ?>/ai-tips" class="nav-item <?= $activePage==='ai-tips'?'active':'' ?>">
      <span class="ni ni-purple"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 1 1 7.072 0l-.548.547A3.374 3.374 0 0 0 14 18.469V19a2 2 0 1 1-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg></span>
      AI Study Tips
    </a>
  </div>

</nav>

  <!-- ⭐ Rate & Review + Contact — hide on scroll-down, show on scroll-up -->
  <div id="sidebarActionBtns" style="
    overflow:hidden;
    max-height:200px;
    opacity:1;
    transition:max-height 0.35s cubic-bezier(.4,0,.2,1), opacity 0.3s ease, margin 0.35s ease;
    margin-bottom:0;
  ">

    <!-- ⭐ Rate & Review — Gold theme -->
    <a href="<?= $siteUrl ?>/reviews" style="
      display:flex;align-items:center;gap:10px;
      margin:0 12px 6px;padding:11px 14px;
      border-radius:12px;text-decoration:none;
      background:linear-gradient(135deg,rgba(234,179,8,0.13),rgba(161,130,0,0.08));
      border:1px solid rgba(234,179,8,0.35);
      color:#d4a017;
      font-size:13px;font-weight:700;
      transition:all 0.2s;
      position:relative;overflow:hidden;
    "
    onmouseover="this.style.background='linear-gradient(135deg,rgba(234,179,8,0.24),rgba(161,130,0,0.16))';this.style.borderColor='rgba(234,179,8,0.6)';this.style.transform='translateY(-1px)';this.style.boxShadow='0 4px 18px rgba(234,179,8,0.22)'"
    onmouseout="this.style.background='linear-gradient(135deg,rgba(234,179,8,0.13),rgba(161,130,0,0.08))';this.style.borderColor='rgba(234,179,8,0.35)';this.style.transform='';this.style.boxShadow=''">
      <!-- Gold SVG star icon -->
      <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24"
           fill="#d4a017" stroke="#b8860b" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"
           style="filter:drop-shadow(0 0 5px rgba(212,160,23,0.5));flex-shrink:0">
        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
      </svg>
      <span style="flex:1">Rate &amp; Review</span>
      <span style="font-size:10px;background:rgba(212,160,23,0.18);border:1px solid rgba(212,160,23,0.4);border-radius:99px;padding:2px 8px;font-weight:800;letter-spacing:.3px;color:#d4a017">NEW</span>
    </a>

    <!-- Contact & Support -->
    <a href="<?= $siteUrl ?>/contact" style="
      display:flex;align-items:center;gap:10px;
      margin:0 12px 8px;padding:11px 14px;
      border-radius:12px;text-decoration:none;
      background:rgba(99,102,241,0.08);
      border:1px solid rgba(99,102,241,0.2);
      color:var(--text-secondary);
      font-size:13px;font-weight:600;
      transition:all 0.2s;
    "
    onmouseover="this.style.background='rgba(99,102,241,0.18)';this.style.color='var(--accent)';this.style.borderColor='rgba(99,102,241,0.4)'"
    onmouseout="this.style.background='rgba(99,102,241,0.08)';this.style.color='var(--text-secondary)';this.style.borderColor='rgba(99,102,241,0.2)'">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;opacity:0.8">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
      </svg>
      Contact &amp; Support
    </a>
  </div>

  <script>
  (function(){
    var sidebar = document.getElementById('sidebar');
    var btns    = document.getElementById('sidebarActionBtns');
    if (!sidebar || !btns) return;

    var lastY   = 0;
    var ticking = false;
    var hidden  = false;

    sidebar.addEventListener('scroll', function(){
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(function(){
        var cur = sidebar.scrollTop;
        if (cur > lastY && cur > 40) {
          // scrolling DOWN → hide buttons
          if (!hidden) {
            btns.style.maxHeight = '0';
            btns.style.opacity   = '0';
            btns.style.marginBottom = '-8px';
            hidden = true;
          }
        } else {
          // scrolling UP → show buttons
          if (hidden) {
            btns.style.maxHeight = '200px';
            btns.style.opacity   = '1';
            btns.style.marginBottom = '0';
            hidden = false;
          }
        }
        lastY   = cur;
        ticking = false;
      });
    }, { passive: true });
  })();
  </script>

  <div class="sidebar-user">
    <div class="user-card" style="display:flex;align-items:center;gap:10px;padding:12px 14px;">
      <a href="<?= $siteUrl ?>/profile" style="display:flex;align-items:center;gap:10px;text-decoration:none;flex:1;min-width:0;">
        <div class="user-avatar" style="overflow:hidden;padding:0;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
          <?php if ($userAvatar): ?>
          <img src="<?= $userAvatar ?>" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;" alt="avatar">
          <?php else: ?>
          <?= $userInitial ?>
          <?php endif; ?>
        </div>
        <div class="user-info" style="min-width:0;">
          <div class="name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= $userName ?></div>
          <div class="role">Student</div>
        </div>
      </a>
      <a href="<?= $siteUrl ?>/logout" title="Logout"
         style="
           width:34px;height:34px;border-radius:9px;flex-shrink:0;
           display:flex;align-items:center;justify-content:center;
           background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.2);
           color:#ef4444;text-decoration:none;transition:all 0.2s;
         "
         onmouseover="this.style.background='rgba(239,68,68,0.18)';this.style.borderColor='rgba(239,68,68,0.5)'"
         onmouseout="this.style.background='rgba(239,68,68,0.08)';this.style.borderColor='rgba(239,68,68,0.2)'">
        <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
          <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
          <polyline points="16 17 21 12 16 7"/>
          <line x1="21" y1="12" x2="9" y2="12"/>
        </svg>
      </a>
    </div>
  </div>
</aside>


</script>

<div class="main-content">
  <div class="topbar">
    <div class="topbar-left">
      <button class="sidebar-toggle" id="sidebarToggle">☰</button>
      <div>
        <div class="topbar-title"><?= htmlspecialchars($title) ?></div>
      </div>
    </div>
    <div class="topbar-right" style="display:flex;align-items:center;gap:8px;">

      <!-- ── Shared topbar icon style ── -->
      <!-- All icons: 36x36, border-radius:10px, border:1px solid var(--border), bg:var(--bg-secondary) -->

      <!-- Campus Explorer Button -->
      <a href="<?= $siteUrl ?>/campus" title="Campus Explorer"
         style="
           display:inline-flex;align-items:center;gap:6px;
           padding:0 14px;height:36px;border-radius:10px;
           background:<?= $activePage==='campus' ? 'rgba(99,102,241,.12)' : 'var(--bg-secondary)' ?>;
           border:1px solid <?= $activePage==='campus' ? 'var(--accent)' : 'var(--border)' ?>;
           color:<?= $activePage==='campus' ? 'var(--accent)' : 'var(--text-primary)' ?>;text-decoration:none;
           font-size:12px;font-weight:700;flex-shrink:0;
           transition:all 0.2s;white-space:nowrap;letter-spacing:0.2px;
         "
         onmouseover="this.style.background='var(--accent)';this.style.color='#fff';this.style.borderColor='var(--accent)'"
         onmouseout="this.style.background='<?= $activePage==='campus' ? 'rgba(99,102,241,.12)' : 'var(--bg-secondary)' ?>';this.style.color='<?= $activePage==='campus' ? 'var(--accent)' : 'var(--text-primary)' ?>';this.style.borderColor='<?= $activePage==='campus' ? 'var(--accent)' : 'var(--border)' ?>'">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>
        </svg>
        <span class="campus-btn-text">Explorer</span>
      </a>

      <!-- Dark / Light mode toggle 
      <button id="themeToggleBtn" onclick="toggleTheme()" title="Toggle dark/light mode" style="
        width:36px;height:36px;border-radius:10px;
        border:1px solid var(--border);
        background:var(--bg-secondary);
        color:var(--text-primary);cursor:pointer;
        display:inline-flex;align-items:center;justify-content:center;
        transition:all 0.2s;flex-shrink:0;padding:0;
      "
      onmouseover="this.style.borderColor='var(--accent)';this.style.color='var(--accent)'"
      onmouseout="this.style.borderColor='var(--border)';this.style.color='var(--text-primary)'">
        <!-- Moon icon (dark mode) 
        <svg id="icon-moon" xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
        </svg>
        <!-- Sun icon (light mode) 
        <svg id="icon-sun" xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none">
          <circle cx="12" cy="12" r="5"/>
          <line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/>
          <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
          <line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/>
          <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
        </svg>
      </button> -->

      <!-- ── Settings Icon ──────────────────────────────── -->
      <a href="<?= $siteUrl ?>/settings" title="Settings" style="
           width:36px;height:36px;border-radius:10px;
           border:1px solid <?= $activePage==='settings' ? 'var(--accent)' : 'var(--border)' ?>;
           background:<?= $activePage==='settings' ? 'rgba(99,102,241,.12)' : 'var(--bg-secondary)' ?>;
           color:<?= $activePage==='settings' ? 'var(--accent)' : 'var(--text-primary)' ?>;
           display:inline-flex;align-items:center;justify-content:center;
           flex-shrink:0;text-decoration:none;transition:all .2s;"
         onmouseover="this.style.borderColor='var(--accent)';this.style.color='var(--accent)';this.style.background='rgba(99,102,241,.1)'"
         onmouseout="this.style.borderColor='<?= $activePage==='settings' ? 'var(--accent)' : 'var(--border)' ?>';this.style.color='<?= $activePage==='settings' ? 'var(--accent)' : 'var(--text-primary)' ?>';this.style.background='<?= $activePage==='settings' ? 'rgba(99,102,241,.12)' : 'var(--bg-secondary)' ?>'">
        <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="12" cy="12" r="3"/>
          <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
        </svg>
      </a>

      <!-- ── Notification Bell ─────────────────────────── -->
      <div id="notifBellWrap" style="position:relative;flex-shrink:0;">
        <button id="notifBellBtn" onclick="toggleNotifPanel()" title="Notifications" style="
          width:36px;height:36px;border-radius:10px;
          border:1px solid <?= $activePage==='notifications' ? 'var(--accent)' : 'var(--border)' ?>;
          background:<?= $activePage==='notifications' ? 'rgba(99,102,241,.12)' : 'var(--bg-secondary)' ?>;
          color:<?= $activePage==='notifications' ? 'var(--accent)' : 'var(--text-primary)' ?>;
          cursor:pointer;display:inline-flex;
          align-items:center;justify-content:center;
          transition:all 0.2s;position:relative;padding:0;
        "
        onmouseover="this.style.borderColor='var(--accent)';this.style.color='var(--accent)';this.style.background='rgba(99,102,241,.1)'"
        onmouseout="this.style.borderColor='<?= $activePage==='notifications' ? 'var(--accent)' : 'var(--border)' ?>';this.style.color='<?= $activePage==='notifications' ? 'var(--accent)' : 'var(--text-primary)' ?>';this.style.background='<?= $activePage==='notifications' ? 'rgba(99,102,241,.12)' : 'var(--bg-secondary)' ?>'"
        ><svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg><span id="notifBadge" style="
          display:none;position:absolute;top:-4px;right:-4px;
          background:#ef4444;color:#fff;font-size:9px;font-weight:800;
          min-width:16px;height:16px;border-radius:8px;
          align-items:center;justify-content:center;
          padding:0 3px;line-height:1;border:2px solid var(--bg-card);
        "></span></button>

        <!-- Notification Dropdown Panel -->
        <div id="notifPanel" style="
          display:none;position:fixed;right:12px;top:62px;
          width:340px;max-width:calc(100vw - 24px);
          background:var(--bg-card);border:1px solid var(--border);
          border-radius:16px;box-shadow:0 8px 40px rgba(0,0,0,0.35);
          z-index:99999;overflow:hidden;
          animation:fadeIn 0.18s ease;
        ">
          <!-- Panel header -->
          <div style="display:flex;align-items:center;justify-content:space-between;
            padding:14px 16px;border-bottom:1px solid var(--border);">
            <div style="font-size:14px;font-weight:700;color:var(--text-primary)">
              🔔 Notifications
              <span id="notifPanelCount" style="
                background:rgba(99,102,241,0.15);color:var(--accent);
                font-size:11px;padding:2px 7px;border-radius:20px;margin-left:6px;
              "></span>
            </div>
            <button onclick="notifMarkAllRead()" style="
              background:none;border:none;color:var(--accent);
              font-size:12px;font-weight:600;cursor:pointer;padding:4px 8px;
              border-radius:6px;transition:background .15s;
            " onmouseover="this.style.background='rgba(99,102,241,0.1)'"
               onmouseout="this.style.background='none'">Mark all read</button>
          </div>

          <!-- Notification list -->
          <div id="notifList" style="
            max-height:360px;overflow-y:auto;
            scrollbar-width:thin;
            border-radius:0 0 16px 16px;
          ">
            <div id="notifLoading" style="
              text-align:center;padding:28px 16px;
              color:var(--text-muted);font-size:13px;
            ">
              <div style="display:inline-block;width:20px;height:20px;border:2px solid var(--border);border-top-color:var(--accent);border-radius:50%;animation:notifSpin 0.7s linear infinite;margin-bottom:8px"></div>
              <div>Loading...</div>
            </div>
            <div id="notifEmpty" style="
              text-align:center;padding:32px 16px;
              color:var(--text-muted);font-size:13px;display:none;
            ">
              <div style="font-size:32px;margin-bottom:8px">🔕</div>
              <div>No notifications yet</div>
            </div>
            <div id="notifError" style="
              text-align:center;padding:24px 16px;
              color:var(--text-muted);font-size:13px;display:none;
            ">
              <div style="font-size:28px;margin-bottom:8px">⚠️</div>
              <div>Could not load notifications</div>
              <button onclick="loadNotifications()" style="margin-top:8px;background:none;border:1px solid var(--border);color:var(--accent);font-size:12px;padding:4px 12px;border-radius:8px;cursor:pointer;">Retry</button>
            </div>
          </div>

          <!-- Panel footer -->
          <div style="padding:10px 16px;border-top:1px solid var(--border);text-align:center;">
            <a href="<?= $siteUrl ?>/notifications" style="
              font-size:12px;color:var(--accent);font-weight:600;text-decoration:none;
            ">View all notifications</a>
          </div>
        </div>
      </div>
      <!-- ── End Notification Bell ─────────────────────── -->

      <a href="<?= $siteUrl ?>/profile" class="user-avatar" style="width:36px;height:36px;cursor:pointer;text-decoration:none;overflow:hidden;padding:0;display:inline-flex;align-items:center;justify-content:center;">
        <?php if ($userAvatar): ?>
        <img src="<?= $userAvatar ?>" style="width:100%;height:100%;object-fit:cover;border-radius:10px;" alt="avatar">
        <?php else: ?>
        <span style="font-size:14px;font-weight:700;"><?= $userInitial ?></span>
        <?php endif; ?>
      </a>
    </div>
  </div>
  <div class="page-content">

<!-- ── Greeting Popup ─────────────────────────────────────────── -->
<style>
/* overlay */
#stgr-wrap {
  position: fixed;
  inset: 0;
  z-index: 99998;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  pointer-events: none;
  opacity: 0;
}
#stgr-wrap.stgr-in {
  pointer-events: auto;
  animation: stgr-fadein .4s ease forwards;
}
#stgr-wrap.stgr-out {
  animation: stgr-fadeout .45s ease forwards;
}
@keyframes stgr-fadein  { from{opacity:0} to{opacity:1} }
@keyframes stgr-fadeout { from{opacity:1} to{opacity:0} }

/* blur backdrop */
#stgr-backdrop {
  position: absolute;
  inset: 0;
  background: rgba(5,5,15,.65);
  backdrop-filter: blur(6px);
  -webkit-backdrop-filter: blur(6px);
}
[data-theme="light"] #stgr-backdrop {
  background: rgba(100,100,150,.25);
}

/* card */
#stgr-card {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 380px;
  border-radius: 28px;
  padding: 0;
  overflow: hidden;
  transform: scale(.82) translateY(24px);
  animation: none;
  box-shadow: 0 32px 80px rgba(0,0,0,.55), 0 0 0 1px rgba(255,255,255,.06);
}
#stgr-wrap.stgr-in #stgr-card {
  animation: stgr-pop .55s cubic-bezier(.34,1.56,.64,1) .1s both;
}
#stgr-wrap.stgr-out #stgr-card {
  animation: stgr-popout .38s cubic-bezier(.4,0,.2,1) forwards;
}
@keyframes stgr-pop    { from{transform:scale(.82) translateY(24px);opacity:0} to{transform:scale(1) translateY(0);opacity:1} }
@keyframes stgr-popout { from{transform:scale(1) translateY(0);opacity:1} to{transform:scale(.88) translateY(16px);opacity:0} }

/* gradient bg per time */
#stgr-bg {
  position: absolute;
  inset: 0;
  transition: background .4s;
}
.stgr-morning #stgr-bg { background: linear-gradient(145deg, #1a1040, #2d1b69 40%, #0f0a2a); }
.stgr-afternoon #stgr-bg { background: linear-gradient(145deg, #0a1628, #1e3a5f 40%, #0d2137); }
.stgr-evening #stgr-bg   { background: linear-gradient(145deg, #1a0f30, #3b1f6b 40%, #0f0a28); }
.stgr-night #stgr-bg     { background: linear-gradient(145deg, #050510, #0f0d28 40%, #08060f); }

[data-theme="light"] .stgr-morning  #stgr-bg { background: linear-gradient(145deg, #fef3c7, #fde68a 40%, #fbbf24); }
[data-theme="light"] .stgr-afternoon #stgr-bg{ background: linear-gradient(145deg, #dbeafe, #93c5fd 40%, #3b82f6); }
[data-theme="light"] .stgr-evening  #stgr-bg { background: linear-gradient(145deg, #ede9fe, #c4b5fd 40%, #8b5cf6); }
[data-theme="light"] .stgr-night    #stgr-bg { background: linear-gradient(145deg, #1e1b4b, #312e81 40%, #0f0e24); }

/* glow top line */
#stgr-card::before {
  content: '';
  position: absolute;
  top: 0; left: 15%; right: 15%;
  height: 1px;
  z-index: 3;
  border-radius: 99px;
}
.stgr-morning  #stgr-card::before { background: linear-gradient(90deg, transparent, #fcd34d, #fbbf24, transparent); }
.stgr-afternoon #stgr-card::before{ background: linear-gradient(90deg, transparent, #60a5fa, #818cf8, transparent); }
.stgr-evening  #stgr-card::before { background: linear-gradient(90deg, transparent, #a78bfa, #c084fc, transparent); }
.stgr-night    #stgr-card::before { background: linear-gradient(90deg, transparent, #6366f1, #8b5cf6, transparent); }

/* particles canvas */
#stgr-particles {
  position: absolute;
  inset: 0;
  pointer-events: none;
  overflow: hidden;
}
.stgr-star {
  position: absolute;
  border-radius: 50%;
  animation: stgr-twinkle var(--d,2s) ease-in-out infinite var(--dl,0s);
}
@keyframes stgr-twinkle {
  0%,100%{ opacity:.15; transform:scale(1); }
  50%    { opacity:.9;  transform:scale(1.4); }
}
.stgr-float {
  position: absolute;
  font-size: var(--fs,22px);
  animation: stgr-float var(--d,4s) ease-in-out infinite var(--dl,0s);
  opacity: .55;
}
@keyframes stgr-float {
  0%,100%{ transform:translateY(0) rotate(0deg); }
  50%    { transform:translateY(-12px) rotate(8deg); }
}

/* inner content */
#stgr-inner {
  position: relative;
  z-index: 2;
  padding: 36px 28px 28px;
  text-align: center;
}

/* big emoji */
#stgr-emoji {
  font-size: 64px;
  line-height: 1;
  margin-bottom: 16px;
  display: block;
  animation: stgr-bounce 2.2s ease-in-out infinite;
  filter: drop-shadow(0 8px 24px rgba(0,0,0,.3));
}
@keyframes stgr-bounce {
  0%,100%{ transform:translateY(0) scale(1); }
  40%    { transform:translateY(-10px) scale(1.06); }
  60%    { transform:translateY(-6px) scale(1.03); }
}

#stgr-time-label {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 2.5px;
  text-transform: uppercase;
  margin-bottom: 8px;
  opacity: .55;
}
.stgr-morning  #stgr-time-label { color: #fcd34d; }
.stgr-afternoon #stgr-time-label{ color: #93c5fd; }
.stgr-evening  #stgr-time-label { color: #c4b5fd; }
.stgr-night    #stgr-time-label { color: #818cf8; }

#stgr-greeting {
  font-family: 'Outfit', sans-serif;
  font-size: 30px;
  font-weight: 900;
  letter-spacing: -.5px;
  line-height: 1.15;
  margin-bottom: 6px;
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}
.stgr-morning  #stgr-greeting { background-image: linear-gradient(135deg, #fde68a, #fbbf24, #f97316); }
.stgr-afternoon #stgr-greeting{ background-image: linear-gradient(135deg, #93c5fd, #818cf8, #6366f1); }
.stgr-evening  #stgr-greeting { background-image: linear-gradient(135deg, #c4b5fd, #a78bfa, #8b5cf6); }
.stgr-night    #stgr-greeting { background-image: linear-gradient(135deg, #818cf8, #6366f1, #a855f7); }

#stgr-name {
  font-family: 'Outfit', sans-serif;
  font-size: 17px;
  font-weight: 700;
  color: rgba(255,255,255,.7);
  margin-bottom: 20px;
}
[data-theme="light"] .stgr-morning #stgr-name,
[data-theme="light"] .stgr-afternoon #stgr-name { color: rgba(15,23,42,.6); }

#stgr-msg {
  font-size: 13px;
  color: rgba(255,255,255,.4);
  font-weight: 400;
  line-height: 1.6;
  margin-bottom: 24px;
  padding: 0 8px;
}
[data-theme="light"] .stgr-morning  #stgr-msg,
[data-theme="light"] .stgr-afternoon #stgr-msg { color: rgba(15,23,42,.45); }

/* close btn */
#stgr-close {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 11px 28px;
  border-radius: 12px;
  border: none;
  cursor: pointer;
  font-family: 'Plus Jakarta Sans', sans-serif;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: .2px;
  transition: transform .18s, box-shadow .18s, opacity .18s;
  position: relative;
  overflow: hidden;
}
.stgr-morning  #stgr-close { background: linear-gradient(135deg,#f59e0b,#f97316); color:#fff; box-shadow:0 6px 20px rgba(249,115,22,.4); }
.stgr-afternoon #stgr-close{ background: linear-gradient(135deg,#6366f1,#3b82f6); color:#fff; box-shadow:0 6px 20px rgba(99,102,241,.4); }
.stgr-evening  #stgr-close { background: linear-gradient(135deg,#8b5cf6,#a855f7); color:#fff; box-shadow:0 6px 20px rgba(139,92,246,.4); }
.stgr-night    #stgr-close { background: linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; box-shadow:0 6px 20px rgba(99,102,241,.45); }
#stgr-close:hover { transform:translateY(-2px) scale(1.03); }
#stgr-close:active{ transform:scale(.97); }
#stgr-close::after {
  content:'';position:absolute;inset:0;
  background:linear-gradient(105deg,transparent,rgba(255,255,255,.18),transparent);
  animation: stgr-btn-shine 2.5s ease-in-out infinite;
}
@keyframes stgr-btn-shine {
  0%,100%{transform:translateX(-100%) skewX(-15deg)} 50%{transform:translateX(200%) skewX(-15deg)}
}

/* progress auto-close bar */
#stgr-progress {
  position: absolute;
  bottom: 0; left: 0; right: 0;
  height: 3px;
  overflow: hidden;
}
#stgr-prog-fill {
  height: 100%;
  width: 100%;
  transform-origin: left;
  transform: scaleX(1);
  transition: none;
}
.stgr-morning  #stgr-prog-fill { background:linear-gradient(90deg,#fbbf24,#f97316); }
.stgr-afternoon #stgr-prog-fill{ background:linear-gradient(90deg,#6366f1,#3b82f6); }
.stgr-evening  #stgr-prog-fill { background:linear-gradient(90deg,#8b5cf6,#c084fc); }
.stgr-night    #stgr-prog-fill { background:linear-gradient(90deg,#6366f1,#a855f7); }
</style>

<!-- Greeting Popup HTML -->
<div id="stgr-wrap">
  <div id="stgr-backdrop" onclick="stgrClose()"></div>
  <div id="stgr-card">
    <div id="stgr-bg"></div>
    <div id="stgr-particles"></div>
    <div id="stgr-inner">
      <span id="stgr-emoji">🌅</span>
      <div id="stgr-time-label">GOOD MORNING</div>
      <div id="stgr-greeting">Rise &amp; Shine!</div>
      <div id="stgr-name">Welcome back, <?= htmlspecialchars($_SESSION['user_name'] ?? 'Student') ?> 👋</div>
      <div id="stgr-msg">The early bird catches the worm. Let's make today count!</div>
      <button id="stgr-close" onclick="stgrClose()">
        <span>Let's Go! 🚀</span>
      </button>
    </div>
    <div id="stgr-progress"><div id="stgr-prog-fill"></div></div>
  </div>
</div>

<script>
(function(){
  var AUTO_CLOSE = 6000; // 6 seconds

  var data = {
    morning: {
      cls:'stgr-morning', emoji:'🌄', label:'GOOD MORNING',
      greetings:['Rise & Shine!','Good Morning!','Start Strong!'],
      msgs:['The early bird catches the worm. Let\'s make today count! ✨','A new day, a new chance to be brilliant. You\'ve got this! 💪','Morning energy is everything. Let\'s crush those study goals! 🎯'],
      btn:'Let\'s Go! 🚀', particles:['⭐','✨','🌟']
    },
    afternoon: {
      cls:'stgr-afternoon', emoji:'☀️', label:'GOOD AFTERNOON',
      greetings:['Keep It Up!','Afternoon Grind!','Stay Focused!'],
      msgs:['The afternoon is full of potential. Keep that momentum going! 📚','Half the day done, and you\'re still going strong! 💡','Stay hydrated and keep your eyes on the goal. You\'re doing great! ⚡'],
      btn:'Keep Going! 💡', particles:['☀️','💫','🌤️']
    },
    evening: {
      cls:'stgr-evening', emoji:'🌆', label:'GOOD EVENING',
      greetings:['Evening Hustle!','Wind Down Smart','Almost There!'],
      msgs:['Evenings are for reflection and final pushes. Make it count! 🌟','The day is winding down — finish strong and be proud! 🎉','A quiet evening is perfect for deep focus. Let\'s dive in! 📖'],
      btn:'Let\'s Study! 📖', particles:['🌆','⭐','🌙']
    },
    night: {
      cls:'stgr-night', emoji:'🌙', label:'GOOD NIGHT',
      greetings:['Night Owl Mode!','Burning Midnight Oil','Late Night Grind!'],
      msgs:['The night is quiet and your mind is sharp. Own this session! 🦉','Some of the best studying happens when the world is asleep. 💫','Late night dedication separates the good from the great. Let\'s go! 🌟'],
      btn:'Night Mode On! 🌙', particles:['🌙','⭐','💫']
    }
  };

  function getPeriod(h){
    if(h>=5  && h<12) return 'morning';
    if(h>=12 && h<17) return 'afternoon';
    if(h>=17 && h<21) return 'evening';
    return 'night';
  }

  var KEY = 'stgr_last_' + (new Date().toDateString());

  // Only show once per day
  if(localStorage.getItem(KEY)) return;

  var h = new Date().getHours();
  var period = getPeriod(h);
  var d = data[period];
  var idx = Math.floor(Math.random() * d.greetings.length);

  var wrap = document.getElementById('stgr-wrap');
  var card = document.getElementById('stgr-card');

  // Apply period class
  card.classList.add(d.cls);

  // Set content
  document.getElementById('stgr-emoji').textContent   = d.emoji;
  document.getElementById('stgr-time-label').textContent = d.label;
  document.getElementById('stgr-greeting').textContent  = d.greetings[idx];
  document.getElementById('stgr-msg').textContent       = d.msgs[idx];
  document.getElementById('stgr-close').innerHTML       = '<span>'+d.btn+'</span>';

  // Spawn particles
  var parts = document.getElementById('stgr-particles');
  var emojis = d.particles;
  // stars
  for(var i=0;i<18;i++){
    var s=document.createElement('div'); s.className='stgr-star';
    var sz = Math.random()*3+1.5;
    s.style.cssText='width:'+sz+'px;height:'+sz+'px;'
      +'left:'+(Math.random()*100)+'%;top:'+(Math.random()*100)+'%;'
      +'background:rgba(255,255,255,'+(Math.random()*.5+.2)+');'
      +'--d:'+(1.5+Math.random()*2.5)+'s;--dl:'+(Math.random()*2)+'s;';
    parts.appendChild(s);
  }
  // floating emoji
  for(var j=0;j<4;j++){
    var f=document.createElement('div'); f.className='stgr-float';
    f.textContent=emojis[j%emojis.length];
    f.style.cssText='left:'+(10+j*22)+'%;bottom:'+(8+Math.random()*20)+'%;'
      +'--fs:'+(18+Math.random()*10)+'px;'
      +'--d:'+(3+Math.random()*2)+'s;--dl:'+(j*.4)+'s;';
    parts.appendChild(f);
  }

  // Show after page load
  function show(){
    wrap.classList.add('stgr-in');
    // auto-close progress
    var fill = document.getElementById('stgr-prog-fill');
    fill.style.transition = 'transform '+AUTO_CLOSE+'ms linear';
    setTimeout(function(){ fill.style.transform='scaleX(0)'; }, 50);
    setTimeout(stgrClose, AUTO_CLOSE);
  }

  if(document.readyState==='complete'){ setTimeout(show,600); }
  else { window.addEventListener('load', function(){ setTimeout(show,600); }); }

  window.stgrClose = function(){
    if(!wrap.classList.contains('stgr-in')) return;
    wrap.classList.remove('stgr-in');
    wrap.classList.add('stgr-out');
    localStorage.setItem(KEY,'1');
    setTimeout(function(){ wrap.style.display='none'; }, 480);
  };
})();
</script>

<!-- ── Notification JS (inline so siteUrl is available) ─────────── -->
<script>
var _notifSiteUrl = '<?= $siteUrl ?>';
var _notifPanelOpen = false;
var _notifPollTimer = null;
var _notifPrevUnread = -1; // -1 means first load

// Type icons & colors
var _notifIcons  = {info:'ℹ️', success:'✅', warning:'⚠️', danger:'🚨', achievement:'🏆', streak:'🔥', reminder:'⏰', task:'✅'};
var _notifColors = {info:'var(--accent)', success:'var(--success)', warning:'var(--warning)', danger:'var(--danger)', achievement:'#f59e0b', streak:'#f97316', reminder:'var(--accent-3)', task:'var(--success)'};

function toggleNotifPanel() {
  _notifPanelOpen = !_notifPanelOpen;
  var panel = document.getElementById('notifPanel');
  if (_notifPanelOpen) {
    var topbar = document.querySelector('.topbar');
    var topbarBottom = topbar ? topbar.getBoundingClientRect().bottom : 62;
    panel.style.top = (topbarBottom + 6) + 'px';
    // Reset and re-trigger the fadeIn animation each time panel opens
    panel.style.animation = 'none';
    panel.offsetHeight; // force reflow so animation restarts
    panel.style.animation = 'fadeIn 0.2s ease both';
    panel.style.display = 'block';
    loadNotifications();
    // Close on outside click
    setTimeout(function() {
      document.addEventListener('click', _notifOutsideClick);
    }, 10);
  } else {
    panel.style.display = 'none';
    document.removeEventListener('click', _notifOutsideClick);
  }
}

function _notifOutsideClick(e) {
  var wrap = document.getElementById('notifBellWrap');
  if (wrap && !wrap.contains(e.target)) {
    _notifPanelOpen = false;
    document.getElementById('notifPanel').style.display = 'none';
    document.removeEventListener('click', _notifOutsideClick);
  }
}

async function loadNotifications() {
  var loadingEl = document.getElementById('notifLoading');
  var errorEl   = document.getElementById('notifError');
  var emptyEl   = document.getElementById('notifEmpty');
  if (loadingEl) loadingEl.style.display = 'block';
  if (errorEl)   errorEl.style.display   = 'none';
  if (emptyEl)   emptyEl.style.display   = 'none';
  try {
    var res = await fetch(_notifSiteUrl + '/api/notifications.php', {headers:{'X-Requested-With':'XMLHttpRequest'}});
    if (!res.ok) throw new Error('HTTP ' + res.status);
    var list = await res.json();
    if (loadingEl) loadingEl.style.display = 'none';
    var unreadCount = list.filter(function(n){ return !n.is_read; }).length;
    var bellBtn = document.getElementById('notifBellBtn');
    if (bellBtn && _notifPrevUnread !== -1 && unreadCount > _notifPrevUnread) {
      bellBtn.classList.remove('bell-ringing');
      bellBtn.offsetHeight;
      bellBtn.classList.add('bell-ringing');
      setTimeout(function() { bellBtn.classList.remove('bell-ringing'); }, 800);
    }
    if (_notifPrevUnread === -1 && unreadCount > 0 && bellBtn) {
      bellBtn.classList.remove('bell-ringing');
      bellBtn.offsetHeight;
      bellBtn.classList.add('bell-ringing');
      setTimeout(function() { bellBtn.classList.remove('bell-ringing'); }, 800);
    }
    _notifPrevUnread = unreadCount;
    renderNotifications(list);
    updateBadge(unreadCount);
  } catch(e) {
    console.error('Notif load error:', e);
    if (loadingEl) loadingEl.style.display = 'none';
    if (errorEl)   errorEl.style.display   = 'block';
  }
}

function renderNotifications(list) {
  var el      = document.getElementById('notifList');
  var empty   = document.getElementById('notifEmpty');
  var errorEl = document.getElementById('notifError');
  var countEl = document.getElementById('notifPanelCount');
  var unread  = list.filter(function(n){ return !n.is_read; }).length;
  if (countEl) countEl.textContent = unread > 0 ? unread + ' unread' : 'All read';
  if (errorEl) errorEl.style.display = 'none';

  if (!list || list.length === 0) {
    if (empty) empty.style.display = 'block';
    Array.from(el.children).forEach(function(c){
      if (c.id !== 'notifEmpty' && c.id !== 'notifLoading' && c.id !== 'notifError') c.remove();
    });
    return;
  }
  if (empty) empty.style.display = 'none';

  // Build HTML
  var html = '';
  list.forEach(function(n) {
    var icon  = _notifIcons[n.type]  || '🔔';
    var color = _notifColors[n.type] || 'var(--accent)';
    html += '<div class="_notif-item" data-id="' + n.id + '" style="' +
      'display:flex;align-items:flex-start;gap:11px;padding:12px 16px;' +
      'border-bottom:1px solid var(--border);cursor:pointer;transition:background .15s;' +
      (n.is_read ? 'opacity:0.6;' : 'background:rgba(99,102,241,0.04);') +
      '" onmouseover="this.style.background=\'var(--bg-secondary)\'" onmouseout="this.style.background=\'' + (n.is_read?'transparent':'rgba(99,102,241,0.04)') + '\'" onclick="notifMarkRead(' + n.id + ',this)">' +
      '<div style="width:34px;height:34px;border-radius:10px;background:rgba(99,102,241,0.1);' +
      'display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0;' +
      'border:1.5px solid ' + color + '33;">' + icon + '</div>' +
      '<div style="flex:1;min-width:0;">' +
        '<div style="font-size:13px;font-weight:' + (n.is_read?'500':'700') + ';color:var(--text-primary);margin-bottom:2px;' +
          'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' +
          (n.is_read ? '' : '<span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--accent);margin-right:5px;vertical-align:middle;flex-shrink:0"></span>') +
          escHtml(n.title) + '</div>' +
        '<div style="font-size:12px;color:var(--text-secondary);margin-bottom:4px;' +
          'display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">' +
          escHtml(n.message) + '</div>' +
        '<div style="font-size:11px;color:var(--text-muted);">' + escHtml(n.time_ago) + '</div>' +
      '</div>' +
    '</div>';
  });
  // Replace items but keep special state divs
  Array.from(el.children).forEach(function(c){
    if (c.id !== 'notifEmpty' && c.id !== 'notifLoading' && c.id !== 'notifError') c.remove();
  });
  el.insertAdjacentHTML('afterbegin', html);
}

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

function updateBadge(count) {
  var badge = document.getElementById('notifBadge');
  var sidebarBadge = document.getElementById('sidebarNotifBadge');
  if (badge) {
    if (count > 0) {
      badge.style.display = 'flex';
      badge.textContent = count > 99 ? '99+' : count;
    } else {
      badge.style.display = 'none';
    }
  }
  if (sidebarBadge) {
    if (count > 0) {
      sidebarBadge.style.display = 'inline-block';
      sidebarBadge.textContent = count > 99 ? '99+' : count;
    } else {
      sidebarBadge.style.display = 'none';
    }
  }
}

async function notifMarkRead(id, el) {
  try {
    var fd = new FormData(); fd.append('action','read'); fd.append('id',id);
    await fetch(_notifSiteUrl + '/api/notifications.php', {method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    if (el) {
      el.style.opacity = '0.6';
      el.style.background = 'transparent';
      el.onmouseout = function(){ this.style.background='transparent'; };
      var dot = el.querySelector('span[style*="border-radius:50%"]');
      if (dot) dot.remove();
      var title = el.querySelector('div > div:first-child');
      if (title) title.style.fontWeight = '500';
    }
    // Refresh badge
    var badge = document.getElementById('notifBadge');
    if (badge && badge.style.display !== 'none') {
      var cur = parseInt(badge.textContent) || 0;
      updateBadge(Math.max(0, cur - 1));
    }
    var countEl = document.getElementById('notifPanelCount');
    if (countEl) {
      var c = parseInt(countEl.textContent) || 0;
      var newC = Math.max(0, c - 1);
      countEl.textContent = newC > 0 ? newC + ' unread' : 'All read';
    }
  } catch(e) {}
}

async function notifMarkAllRead() {
  try {
    var fd = new FormData(); fd.append('action','read_all');
    await fetch(_notifSiteUrl + '/api/notifications.php', {method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    updateBadge(0);
    var countEl = document.getElementById('notifPanelCount');
    if (countEl) countEl.textContent = 'All read';
    // Fade all items
    document.querySelectorAll('._notif-item').forEach(function(item) {
      item.style.opacity = '0.6';
      item.style.background = 'transparent';
      var dot = item.querySelector('span[style*="border-radius:50%"]');
      if (dot) dot.remove();
    });
  } catch(e) {}
}

// Poll for new notifications every 60s
function _startNotifPoll() {
  loadNotifications(); // initial load for badge (triggers bell ring if unread)
  _notifPollTimer = setInterval(function() {
    if (!_notifPanelOpen) loadNotifications();
  }, 60000);
}

document.addEventListener('DOMContentLoaded', _startNotifPoll);
</script>

<?php if (!empty($_SESSION['user_disabled'])): ?>
<!-- ===== ACCOUNT DISABLED OVERLAY ===== -->
<div id="disabledOverlay" style="
  position:fixed;inset:0;z-index:99999;
  background:rgba(0,0,0,0.85);
  backdrop-filter:blur(8px);
  display:flex;align-items:center;justify-content:center;
  padding:20px;
">
  <div style="
    background:var(--bg-card);
    border:1px solid rgba(239,68,68,0.4);
    border-radius:24px;
    padding:40px 36px;
    max-width:460px;
    width:100%;
    text-align:center;
    box-shadow:0 20px 60px rgba(239,68,68,0.15);
    position:relative;
  ">
    <div style="
      width:72px;height:72px;border-radius:50%;
      background:rgba(239,68,68,0.12);
      border:2px solid rgba(239,68,68,0.3);
      display:flex;align-items:center;justify-content:center;
      font-size:32px;margin:0 auto 20px;
    ">🚫</div>
    <div style="font-size:22px;font-weight:800;color:var(--text-primary);margin-bottom:10px">
      Account Suspended
    </div>
    <div style="font-size:14px;color:var(--text-secondary);line-height:1.7;margin-bottom:28px">
      Your account has been temporarily disabled by an administrator.<br>
      If you think this is a mistake, please <a href="<?= $siteUrl ?>/contact" style="font-weight: bold; color: lightblue; text-decoration: none;">Contact support</a>
    </div>
    <div style="
      background:rgba(239,68,68,0.08);
      border:1px solid rgba(239,68,68,0.2);
      border-radius:12px;
      padding:12px 16px;
      font-size:12px;
      color:#fca5a5;
      margin-bottom:24px;
    ">
      ⚠️ You cannot access any features while your account is suspended.
    </div>
    <a href="<?= defined('SITE_URL') ? SITE_URL : '' ?>/logout"
       class="btn btn-danger btn-full"
       style="font-size:15px;padding:13px;">
      Logout
    </a>
  </div>
</div>
<script>
// Block all clicks behind overlay
document.addEventListener('DOMContentLoaded', function() {
  var overlay = document.getElementById('disabledOverlay');
  if (overlay) {
    overlay.addEventListener('click', function(e) { e.stopPropagation(); });
    // Block keyboard navigation away
    document.addEventListener('keydown', function(e) {
      if (e.key !== 'Tab') e.preventDefault();
    });
  }
});
</script>
<?php endif; ?>

<?php
// ── Review Popup ────────────────────────────────────────────
// Show if: admin has it enabled + user is logged in + user hasn't reviewed yet
if (isset($_SESSION['user_id'])) {
    try {
        global $pdo;
        $popupOn = false;
        $stmtSet = $pdo->query("SELECT `value` FROM site_settings WHERE `key`='review_popup_enabled'");
        if ($stmtSet) {
            $settingVal = $stmtSet->fetchColumn();
            $popupOn = ($settingVal === '1');
        }
        $userHasReview = false;
        if ($popupOn) {
            $rChk = $pdo->prepare("SELECT id FROM reviews WHERE user_id=?");
            $rChk->execute([$_SESSION['user_id']]);
            $userHasReview = (bool)$rChk->fetchColumn();
        }
        if ($popupOn && !$userHasReview):
?>
<!-- ===== REVIEW POPUP ===== -->
<div id="reviewPopupOverlay" style="
  position:fixed;inset:0;z-index:88888;
  background:rgba(0,0,0,0.65);
  backdrop-filter:blur(6px);
  display:flex;align-items:center;justify-content:center;
  padding:20px;
  opacity:0;pointer-events:none;
  transition:opacity .35s ease;
">
  <div id="reviewPopupCard" style="
    background:var(--bg-card,#1a1a2e);
    border:1px solid rgba(99,102,241,0.35);
    border-radius:24px;
    padding:36px 32px 32px;
    max-width:460px;width:100%;
    position:relative;
    box-shadow:0 24px 80px rgba(99,102,241,0.2);
    transform:translateY(24px) scale(0.97);
    transition:transform .35s cubic-bezier(.34,1.56,.64,1);
    text-align:center;
  ">
    <!-- Close -->
    <button onclick="closeReviewPopup()" style="
      position:absolute;top:14px;right:16px;
      background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.1);
      color:var(--text-muted,#94a3b8);width:32px;height:32px;border-radius:50%;
      cursor:pointer;font-size:18px;line-height:1;display:flex;align-items:center;justify-content:center;
      transition:background .2s;
    " onmouseover="this.style.background='rgba(255,255,255,0.12)'" onmouseout="this.style.background='rgba(255,255,255,0.07)'">×</button>

    <!-- Icon -->
    <div style="
      width:68px;height:68px;border-radius:20px;margin:0 auto 16px;
      background:linear-gradient(135deg,rgba(99,102,241,0.2),rgba(168,85,247,0.2));
      border:1px solid rgba(99,102,241,0.3);
      display:flex;align-items:center;justify-content:center;font-size:30px;
    ">⭐</div>

    <div style="font-size:20px;font-weight:800;color:var(--text-primary,#e2e8f0);margin-bottom:8px">
      Enjoying StudyTrack?
    </div>
    <div style="font-size:14px;color:var(--text-muted,#94a3b8);line-height:1.6;margin-bottom:24px">
      Your feedback helps us improve! Take 30 seconds to rate your experience and leave a quick review.
    </div>

    <!-- Star Rating -->
    <div id="rvpStars" style="display:flex;justify-content:center;gap:8px;margin-bottom:20px">
      <?php for ($i=1;$i<=5;$i++): ?>
      <button onclick="rvpSetRating(<?= $i ?>)" data-star="<?= $i ?>" style="
        font-size:34px;background:none;border:none;cursor:pointer;
        color:var(--border,rgba(255,255,255,0.1));
        transition:transform .15s,color .15s;line-height:1;padding:2px;
      " onmouseover="rvpHover(<?= $i ?>)" onmouseout="rvpHoverOut()">★</button>
      <?php endfor; ?>
    </div>

    <div id="rvpForm" style="display:none">
      <input type="text" id="rvpTitle" placeholder="Review title (e.g. Great app!)" maxlength="150" style="
        width:100%;padding:11px 14px;border-radius:10px;margin-bottom:10px;
        background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.12);
        color:var(--text-primary,#e2e8f0);font-size:14px;outline:none;
        font-family:inherit;box-sizing:border-box;
        transition:border-color .2s;
      " onfocus="this.style.borderColor='rgba(99,102,241,0.6)'" onblur="this.style.borderColor='rgba(255,255,255,0.12)'">
      <textarea id="rvpBody" placeholder="Tell us what you think…" rows="3" maxlength="1000" style="
        width:100%;padding:11px 14px;border-radius:10px;margin-bottom:14px;
        background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.12);
        color:var(--text-primary,#e2e8f0);font-size:14px;outline:none;resize:vertical;
        font-family:inherit;box-sizing:border-box;min-height:80px;
        transition:border-color .2s;
      " onfocus="this.style.borderColor='rgba(99,102,241,0.6)'" onblur="this.style.borderColor='rgba(255,255,255,0.12)'"></textarea>
      <div id="rvpError" style="display:none;color:#ef4444;font-size:12px;margin-bottom:10px;text-align:left"></div>
      <div style="display:flex;gap:10px">
        <button onclick="closeReviewPopup()" style="
          flex:1;padding:12px;border-radius:12px;
          background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);
          color:var(--text-muted,#94a3b8);font-size:14px;font-weight:600;cursor:pointer;
          font-family:inherit;transition:background .2s;
        " onmouseover="this.style.background='rgba(255,255,255,0.1)'" onmouseout="this.style.background='rgba(255,255,255,0.06)'">Maybe Later</button>
        <button onclick="rvpSubmit()" id="rvpSubmitBtn" style="
          flex:2;padding:12px;border-radius:12px;
          background:linear-gradient(135deg,#6366f1,#a855f7);border:none;
          color:#fff;font-size:14px;font-weight:700;cursor:pointer;
          font-family:inherit;transition:opacity .2s;
          box-shadow:0 4px 20px rgba(99,102,241,0.35);
        ">Submit Review ✨</button>
      </div>
    </div>

    <div id="rvpSkipBtn" style="margin-top:14px">
      <button onclick="closeReviewPopup()" style="
        background:none;border:none;color:var(--text-muted,#94a3b8);
        font-size:13px;cursor:pointer;font-family:inherit;
        text-decoration:underline;text-decoration-style:dotted;
      ">Maybe later</button>
    </div>

    <!-- Success state (hidden) -->
    <div id="rvpSuccess" style="display:none;padding:10px 0 4px">
      <div style="font-size:48px;margin-bottom:12px">🎉</div>
      <div style="font-size:18px;font-weight:800;color:var(--text-primary,#e2e8f0);margin-bottom:8px">Thank you!</div>
      <div style="font-size:14px;color:var(--text-muted,#94a3b8)">Your review has been submitted and is pending approval.</div>
    </div>
  </div>
</div>

<script>
(function(){
  var _rvpRating = 0;

  // Show after 1.5s delay
  setTimeout(function(){
    var overlay = document.getElementById('reviewPopupOverlay');
    var card    = document.getElementById('reviewPopupCard');
    overlay.style.pointerEvents = 'auto';
    overlay.style.opacity = '1';
    card.style.transform = 'translateY(0) scale(1)';
  }, 1500);

  window.closeReviewPopup = function() {
    var overlay = document.getElementById('reviewPopupOverlay');
    var card    = document.getElementById('reviewPopupCard');
    overlay.style.opacity = '0';
    card.style.transform  = 'translateY(16px) scale(0.97)';
    setTimeout(function(){ overlay.style.pointerEvents = 'none'; }, 350);
  };

  // Close on overlay click
  document.getElementById('reviewPopupOverlay').addEventListener('click', function(e){
    if (e.target === this) closeReviewPopup();
  });

  window.rvpHover = function(n) {
    document.querySelectorAll('#rvpStars button').forEach(function(b){
      b.style.color = parseInt(b.dataset.star) <= n ? '#f59e0b' : 'rgba(255,255,255,0.15)';
      b.style.transform = parseInt(b.dataset.star) <= n ? 'scale(1.12)' : 'scale(1)';
    });
  };

  window.rvpHoverOut = function() {
    document.querySelectorAll('#rvpStars button').forEach(function(b){
      var s = parseInt(b.dataset.star);
      b.style.color     = s <= _rvpRating ? '#f59e0b' : 'rgba(255,255,255,0.15)';
      b.style.transform = s <= _rvpRating ? 'scale(1.08)' : 'scale(1)';
    });
  };

  window.rvpSetRating = function(n) {
    _rvpRating = n;
    rvpHoverOut();
    document.getElementById('rvpForm').style.display = 'block';
    document.getElementById('rvpSkipBtn').style.display = 'none';
  };

  window.rvpSubmit = function() {
    var title = document.getElementById('rvpTitle').value.trim();
    var body  = document.getElementById('rvpBody').value.trim();
    var errEl = document.getElementById('rvpError');
    errEl.style.display = 'none';

    if (_rvpRating < 1) { errEl.textContent='Please select a star rating.'; errEl.style.display='block'; return; }
    if (title.length < 3) { errEl.textContent='Please enter a short title (at least 3 characters).'; errEl.style.display='block'; return; }
    if (body.length < 10) { errEl.textContent='Please write a bit more (at least 10 characters).'; errEl.style.display='block'; return; }

    var btn = document.getElementById('rvpSubmitBtn');
    btn.textContent = 'Submitting…';
    btn.style.opacity = '0.7';
    btn.disabled = true;

    var siteUrl = '<?= $siteUrl ?>';
    fetch(siteUrl + '/reviews.php', {
      method: 'POST',
      body: new URLSearchParams({ rating: _rvpRating, title: title, body: body }),
      headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded' }
    }).then(function(r){ return r.json(); }).then(function(d){
      if (d.success) {
        document.getElementById('rvpStars').style.display   = 'none';
        document.getElementById('rvpForm').style.display    = 'none';
        document.getElementById('rvpSkipBtn').style.display = 'none';
        document.querySelector('#reviewPopupCard > div:nth-child(2)').style.display = 'none'; // icon
        document.querySelector('#reviewPopupCard > div:nth-child(3)').style.display = 'none'; // heading
        document.querySelector('#reviewPopupCard > div:nth-child(4)').style.display = 'none'; // subtext
        document.getElementById('rvpSuccess').style.display = 'block';
        setTimeout(closeReviewPopup, 3000);
      } else {
        errEl.textContent = d.msg || 'Something went wrong.';
        errEl.style.display = 'block';
        btn.textContent = 'Submit Review ✨';
        btn.style.opacity = '1';
        btn.disabled = false;
      }
    }).catch(function(){
      errEl.textContent = 'Network error. Please try again.';
      errEl.style.display = 'block';
      btn.textContent = 'Submit Review ✨';
      btn.style.opacity = '1';
      btn.disabled = false;
    });
  };
})();
</script>
<?php
        endif;
    } catch (Exception $e) { /* silently skip if site_settings table doesn't exist yet */ }
}
?>

<?php } ?>