<?php
// includes/navbar.php
$user = currentUser();
$rolColors = [1=>'#2ea8ff',2=>'#f7b93e',3=>'#3dffa0',4=>'#ff9d93',5=>'#c792ea'];
$rolIcons  = [1=>'🎓',2=>'🏢',3=>'📋',4=>'👨‍💼',5=>'🔍'];
$rolColor  = $rolColors[$user['id_rol']] ?? '#8b949e';
$rolIcon   = $rolIcons[$user['id_rol']]  ?? '👤';
?>
<nav class="navbar navbar-expand-lg" style="background:#161b22;border-bottom:1px solid #30363d;padding:0 16px;">

  <!-- ── Botón hamburguesa ── -->
  <button id="sidebar-toggle" title="Mostrar / ocultar menú" style="margin-right:12px;">
    <i class="fa fa-bars"></i>
  </button>

  <a class="navbar-brand fw-bold me-4" href="<?= BASE_URL ?>/modules/<?= strtolower($user['rol']) ?>/dashboard.php"
     style="font-family:'Sora',sans-serif;font-size:18px;color:#e6edf3;letter-spacing:-.5px;">
    SIG<span style="color:#2ea8ff;">VPT</span>
  </a>

  <div class="navbar-nav me-auto">
    <span class="nav-text" style="font-size:13px;color:#8b949e;"><?= htmlspecialchars($pageTitle ?? '') ?></span>
  </div>

  <div class="d-flex align-items-center gap-3">
    <!-- Rol badge -->
    <span style="background:<?= $rolColor ?>22;border:1px solid <?= $rolColor ?>44;color:<?= $rolColor ?>;
                 font-size:11px;padding:3px 10px;border-radius:20px;font-family:'JetBrains Mono',monospace;">
      <?= $rolIcon ?> <?= htmlspecialchars($user['rol']) ?>
    </span>

    <!-- Notificaciones -->
    <div class="dropdown" id="notif-dropdown">
      <button class="btn btn-sm position-relative" id="notif-btn"
              style="background:none;border:1px solid #30363d;color:#8b949e;border-radius:8px;padding:5px 10px;"
              data-bs-toggle="dropdown" aria-expanded="false">
        <i class="fa fa-bell fa-sm"></i>
        <span id="notif-badge"
              style="display:none;position:absolute;top:-6px;right:-6px;background:#ef4444;
                     color:#fff;font-size:9px;font-weight:800;border-radius:50%;
                     width:18px;height:18px;line-height:18px;text-align:center;
                     box-shadow:0 0 0 2px #161b22;
                     animation:notif-pulse 2s infinite;">0</span>
        <style>
          @keyframes notif-pulse {
            0%,100% { box-shadow:0 0 0 2px #161b22,0 0 0 4px rgba(239,68,68,0); }
            50%      { box-shadow:0 0 0 2px #161b22,0 0 0 6px rgba(239,68,68,.35); }
          }
        </style>
      </button>
      <div class="dropdown-menu dropdown-menu-end p-0"
           style="background:#1e2533;border:1px solid #30363d;border-radius:12px;
                  min-width:320px;max-width:360px;box-shadow:0 8px 30px rgba(0,0,0,.4);">
        <div style="padding:12px 16px;border-bottom:1px solid #30363d;
                    display:flex;justify-content:space-between;align-items:center;">
          <span style="font-size:13px;font-weight:700;color:#f0f6fc;">
            <i class="fa fa-bell me-2" style="color:#f7b93e;"></i>Notificaciones
          </span>
          <button onclick="marcarTodasLeidas()"
                  style="background:none;border:none;font-size:11px;color:#7cb9e8;cursor:pointer;padding:0;">
            Marcar todas leídas
          </button>
        </div>
        <div id="notif-list" style="max-height:380px;overflow-y:auto;">
          <div style="padding:24px;text-align:center;color:#8b949e;font-size:13px;">
            <i class="fa fa-spinner fa-spin me-2"></i>Cargando...
          </div>
        </div>
        <div style="padding:10px 16px;border-top:1px solid #30363d;text-align:center;">
          <span style="font-size:11px;color:#8b949e;">Últimas 20 notificaciones</span>
        </div>
      </div>
    </div>

    <!-- User menu -->
    <div class="dropdown">
      <button class="btn btn-sm dropdown-toggle"
              style="background:none;border:1px solid #30363d;color:#e6edf3;border-radius:8px;font-size:13px;"
              data-bs-toggle="dropdown">
        <?= htmlspecialchars($user['nombre']) ?>
      </button>
      <ul class="dropdown-menu dropdown-menu-end" style="background:#161b22;border-color:#30363d;">
        <li><a class="dropdown-item" style="color:#e6edf3;font-size:13px;" href="#">
          <i class="fa fa-user me-2 text-muted"></i>Mi Perfil</a></li>
        <li><hr class="dropdown-divider" style="border-color:#30363d;"></li>
        <li><a class="dropdown-item" style="color:#ff9d93;font-size:13px;" href="<?= BASE_URL ?>/auth/logout.php">
          <i class="fa fa-right-from-bracket me-2"></i>Cerrar Sesión</a></li>
      </ul>
    </div>
  </div>
</nav>

<!-- Overlay para cerrar sidebar en móvil -->
<div id="sidebar-overlay"></div>

<script>
/* ── Notificaciones ─────────────────────────────── */
(function(){
  var BASE='<?= BASE_URL ?>';
  function escHtml(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}

  function mostrarError(msg){
    var l=document.getElementById('notif-list');
    if(l) l.innerHTML='<div style="padding:20px;text-align:center;color:#f59e0b;font-size:12px;">'
      +'<i class="fa fa-triangle-exclamation me-2"></i>'+msg+'</div>';
  }

  function cargarNotifs(){
    var l=document.getElementById('notif-list');
    if(l) l.innerHTML='<div style="padding:24px;text-align:center;color:#8b949e;font-size:13px;">'
      +'<i class="fa fa-spinner fa-spin me-2"></i>Cargando...</div>';
    var ctrl=new AbortController();
    var tid=setTimeout(function(){ctrl.abort();},5000);
    fetch(BASE+'/api/notificaciones.php',{signal:ctrl.signal})
      .then(function(r){clearTimeout(tid);if(!r.ok)throw new Error('HTTP '+r.status);return r.json();})
      .then(function(d){
        if(!d.ok) throw new Error('API error');
        var badge=document.getElementById('notif-badge');
        var lista=document.getElementById('notif-list');
        if(d.total>0){badge.textContent=d.total>9?'9+':d.total;badge.style.display='block';}
        else{badge.style.display='none';}
        if(!d.rows||d.rows.length===0){
          lista.innerHTML='<div style="padding:24px;text-align:center;color:#8b949e;font-size:13px;">'
            +'<i class="fa fa-circle-check me-2" style="color:#3dffa0;"></i>Sin notificaciones nuevas</div>';
          return;
        }
        var html='';
        var userRol='<?= htmlspecialchars(strtolower($user['rol'] ?? 'coordinador')) ?>';
        d.rows.forEach(function(n){
          var leida  = n.leida == 1;
          var virtual= n.id_notif < 0;
          var bg  = virtual ? '#1a2e45' : (leida ? 'transparent' : '#2ea8ff0a');
          var bl  = virtual ? 'border-left:3px solid #f7b93e;'
                            : (leida ? '' : 'border-left:3px solid #2ea8ff;');
          // ── URL: usa el rol real del usuario, no hardcodeado ──
          var clickFn = virtual && n.url
            ? 'window.location.href=\'<?= BASE_URL ?>/modules/\'+userRol+\'/\'+'+JSON.stringify(n.url)
            : 'marcarLeida('+n.id_notif+')';
          var bgHover = virtual ? '#1f3a5a' : '#2a3a50';
          html += '<div onclick="'+clickFn+'" '
            +'style="padding:12px 16px;border-bottom:1px solid #2a3240;cursor:pointer;background:'+bg+';'+bl+'transition:background .15s;" '
            +'onmouseover="this.style.background=\''+bgHover+'\'" onmouseout="this.style.background=\''+bg+'\'">'
            +(virtual
              ? '<span style="display:inline-block;font-size:9px;font-weight:700;background:#f7b93e22;color:#f7b93e;border:1px solid #f7b93e44;border-radius:4px;padding:1px 6px;margin-bottom:4px;">PENDIENTE</span><br>'
              : '')
            +'<div style="font-size:12px;font-weight:'+(leida && !virtual ? 400 : 700)+';color:'+(leida && !virtual ? '#90b8d8' : '#f0f6fc')+';line-height:1.4;">'+escHtml(n.asunto)+'</div>'
            +'<div style="font-size:11px;color:#8b949e;margin-top:3px;line-height:1.4;">'+escHtml(n.mensaje)+'</div>'
            +'<div style="display:flex;align-items:center;justify-content:space-between;margin-top:5px;">'
              +'<span style="font-size:10px;color:#4a5568;"><i class="fa fa-clock me-1"></i>'+n.hace+'</span>'
              +(virtual && n.url ? '<span style="font-size:10px;color:#2ea8ff;font-weight:600;"><i class="fa fa-arrow-right me-1"></i>Ir al módulo</span>' : '')
            +'</div>'
            +'</div>';
        });
        lista.innerHTML=html;
      }).catch(function(err){
        clearTimeout(tid);
        mostrarError(err.name==='AbortError'?'Tiempo de espera agotado.':'Error: '+err.message);
      });
  }

  window.marcarLeida=function(id){
    fetch(BASE+'/api/marcar_notif_leida.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id_notif='+id})
      .then(function(){cargarNotifs();});
  };
  window.marcarTodasLeidas=function(){
    fetch(BASE+'/api/marcar_notif_leida.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id_notif=0'})
      .then(function(){cargarNotifs();});
  };

  // Badge inicial
  fetch(BASE+'/api/notificaciones.php')
    .then(function(r){return r.json();})
    .then(function(d){
      if(d.ok&&d.total>0){var b=document.getElementById('notif-badge');b.textContent=d.total>9?'9+':d.total;b.style.display='block';}
    }).catch(function(){});

  document.getElementById('notif-btn').addEventListener('click',function(){cargarNotifs();});

  setInterval(function(){
    fetch(BASE+'/api/notificaciones.php')
      .then(function(r){return r.json();})
      .then(function(d){
        if(!d.ok)return;
        var b=document.getElementById('notif-badge');
        if(d.total>0){b.textContent=d.total>9?'9+':d.total;b.style.display='block';}else{b.style.display='none';}
      }).catch(function(){});
  },60000);
})();

/* ── Sidebar toggle ─────────────────────────────── */
(function(){
  var STORAGE_KEY = 'sigvp_sidebar_open';
  var isMobile    = function(){ return window.innerWidth < 768; };

  // Leer preferencia guardada (solo desktop)
  // En móvil siempre arranca cerrado
  var savedOpen = localStorage.getItem(STORAGE_KEY);
  var startsOpen = isMobile() ? false : (savedOpen === null ? true : savedOpen === '1');

  var shell   = document.querySelector('.app-shell');
  var overlay = document.getElementById('sidebar-overlay');
  var btn     = document.getElementById('sidebar-toggle');

  function setOpen(open) {
    if (!shell) return;
    if (open) {
      shell.classList.remove('sidebar-collapsed');
    } else {
      shell.classList.add('sidebar-collapsed');
    }
    // Overlay solo en móvil
    if (overlay) overlay.classList.toggle('show', open && isMobile());
    // Guardar preferencia solo en desktop
    if (!isMobile()) localStorage.setItem(STORAGE_KEY, open ? '1' : '0');
  }

  // Estado inicial (debe aplicarse después de que el DOM esté listo)
  document.addEventListener('DOMContentLoaded', function(){
    shell   = document.querySelector('.app-shell');
    overlay = document.getElementById('sidebar-overlay');
    btn     = document.getElementById('sidebar-toggle');
    if (!shell) return;

    setOpen(startsOpen);

    // Botón toggle
    btn && btn.addEventListener('click', function(){
      var isOpen = !shell.classList.contains('sidebar-collapsed');
      setOpen(!isOpen);
    });

    // Cerrar al tocar el overlay (móvil)
    overlay && overlay.addEventListener('click', function(){
      setOpen(false);
    });

    // Al redimensionar: ajustar comportamiento móvil/desktop
    window.addEventListener('resize', function(){
      if (!isMobile()) {
        // Desktop: recuperar preferencia guardada
        overlay && overlay.classList.remove('show');
        var pref = localStorage.getItem(STORAGE_KEY);
        setOpen(pref === null ? true : pref === '1');
      } else {
        // Móvil: siempre cerrar al entrar a vista móvil
        setOpen(false);
      }
    });
  });
})();
</script>