
<div class="card" style="display:flex;justify-content:space-between;align-items:center;margin-top:12px">
  <div class="actions">
    <a class="btn" href="./?r=notifications&per=10&page=1"><i class="fas fa-rotate-right"></i> Recargar</a>
    <button class="btn" onclick="markAllRead()" type="button"><i class="fas fa-check-double"></i> Marcar todo leído</button>
    <button class="btn danger" onclick="deleteAllRead()" type="button"><i class="fas fa-trash"></i> Borrar todas las leídas</button>
  </div>
<div id="notifList"></div>
  <form method="get" action="./" style="display:flex;gap:8px;align-items:center">
    <input type="hidden" name="r" value="notifications">
    <label>Por página</label>
    <select class="select" name="per" onchange="this.form.submit()">
      <option value="10">10</option>
      <option value="20">20</option>
      <option value="30">30</option>
    </select>
  </form>
</div>
<script>
async function markAllRead(){
  await fetch('./?r=notifications/mark-all-read',{method:'POST'});
  location.reload();
}
async function markRead(id){
  await fetch('./?r=notifications/mark-read',{method:'POST', body:new URLSearchParams({id})});
  document.querySelector('[data-id="'+id+'"]')?.classList.remove('unread');
}
async function deleteNotif(id){
  const ok = confirm('¿Eliminar notificación?');
  if(!ok) return;
  await fetch('./?r=notifications/delete',{method:'POST', body:new URLSearchParams({id})});
  const el = document.querySelector('[data-id="'+id+'"]'); if(el) el.remove();
}
</script>

<?php
date_default_timezone_set('UTC');
if (!function_exists('avatar_img')) { @include_once '../../helpers.php'; } ?>


<!-- Restored Styles: notifications -->
<style>

        :root {
            --bg: #0b0c10;
            --panel: #12141a;
            --card: #0e1016;
            --card-hover: #151820;
            --border: #21242c;
            --border-light: #2a2e3a;
            --text: #e9eaf1;
            --muted: #a7acb9;
            --accent: #7cd1ff;
            --accent2: #b99cff;
            --accent3: #ff9cf2;
            --btn: #ffffff;
            --btnText: #0b0c10;
            --error: #ff4d4d;
            --success: #4dff88;
            --warning: #ffc44d;
            --radius: 16px;
            --radius-sm: 10px;
            --shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
            --transition: all 0.3s ease;
            --accent-light: #6bc2ff;
            --accent2-light: #b59cff;
            --purple-light: #d6b3ff;
            --orange-light: #ffb366;
            --green-light: #66ff99;
            --blue-light: #66b3ff;
            --red: #ff4d4d;
            --gradient: linear-gradient(135deg, var(--accent), var(--accent2), var(--accent3));
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
        }

        body {
            background: linear-gradient(180deg, var(--bg) 0%, var(--panel) 100%);
            color: var(--text);
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
        }

        .card {
            background: var(--card);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 28px;
            transition: var(--transition);
            box-shadow: var(--shadow);
            position: relative;
            overflow: hidden;
        }

        .card:before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--gradient);
            opacity: 0;
            transition: var(--transition);
        }

        .card:hover {
            border-color: var(--border-light);
            transform: translateY(-8px);
            background: var(--card-hover);
        }

        .card:hover:before {
            opacity: 1;
        }

        h2, h3 {
            color: var(--text);
        }

        .muted {
            color: var(--muted);
            font-size: 0.9rem;
        }

        .btn {
            padding: 12px 22px;
            border-radius: var(--radius-sm);
            border: 1px solid var(--border);
            background: transparent;
            color: var(--text);
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: var(--transition);
            font-weight: 500;
            position: relative;
            overflow: hidden;
            text-decoration: none;
        }

        .btn:before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: var(--transition);
        }

        .btn:hover:before {
            left: 100%;
        }

        .btn:hover {
            background: rgba(255, 255, 255, 0.05);
            border-color: var(--border-light);
            transform: translateY(-2px);
        }

        .btn.primary {
            background: var(--gradient);
            color: var(--btnText);
            font-weight: 600;
            border: none;
            box-shadow: 0 5px 15px rgba(124, 209, 255, 0.3);
        }

        .btn.primary:hover {
            box-shadow: 0 8px 25px rgba(124, 209, 255, 0.4);
            transform: translateY(-3px);
        }

        .dot {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: var(--gradient);
            color: white;
            border-radius: 50%;
        }

        /* NOTIFICATION BADGE STYLES FOR DASHBOARD */
        .notification-wrapper {
            position: relative;
            display: inline-block;
        }
        
        .notification-badge {
            position: absolute;
            top: 2px;
            right: 2px;
            background: var(--red);
            color: white;
            border-radius: 50%;
            min-width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            font-weight: bold;
            padding: 0;
            border: 2px solid rgba(15, 17, 23, 0.95);
            z-index: 10;
            line-height: 1;
        }
        
        /* Ajuste específico para el botón de notificaciones */
        .notification-btn {
            position: relative;
            padding: 12px 16px 12px 16px !important;
        }

        .btn.sm {
            padding: 4px 10px;
            font-size: 0.8rem;
        }

        @media (max-width: 768px) {
            /* Mobile notification badge adjustment */
            .notification-badge {
                top: 1px;
                right: 1px;
                min-width: 16px;
                height: 16px;
                font-size: 9px;
            }
            
            .notification-btn {
                padding: 10px 14px 10px 14px !important;
            }
        }

        /* Estilos específicos para notificaciones */
        .notifications-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .notification-item {
            transition: var(--transition);
        }
        
        .notification-item:hover {
            transform: translateX(4px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
    
</style>
<div style="margin-top:40px">
    <!-- Header del dashboard IDÉNTICO -->
    <div class="card" style="margin-bottom:24px;background:linear-gradient(135deg, rgba(124,209,255,0.1), rgba(185,156,255,0.1));">
        <div style="display:flex;justify-content:space-between;align-items:center">
            <div>
                <h2 style="margin:0 0 8px 0;display:flex;align-items:center;gap:12px">
                    <span class="dot" style="width:32px;height:32px;"><i class="fas fa-bell"></i></span>
                    <span>Notificaciones</span>
                </h2>
                <p class="muted" style="margin:0">Gestiona tus notificaciones y solicitudes</p>
            </div>

            <!-- Indicador de notificaciones CORREGIDO -->
            <?php
            $unread_count = $_SESSION['unread_notifications'] ?? 0;
            if ($unread_count > 0): ?>
                <div class="notification-wrapper">
                    <a href="./?r=notifications" class="btn primary notification-btn">
                        <i class="fas fa-bell"></i> Notificaciones
                        <span class="notification-badge">
                            <?php echo $unread_count > 9 ? '9+' : $unread_count; ?>
                        </span>
                    </a>
                </div>
            <?php else: ?>
                <a href="./?r=notifications" class="btn">
                    <i class="fas fa-bell"></i> Notificaciones
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Contenido de notificaciones -->
    <?php if (!empty($notifications)): ?>
        <div class="notifications-list">
            <?php foreach($notifications as $n): ?>
                <div class="notification-item card" style="margin-bottom:16px;border-left:4px solid <?php 
                    echo match($n['type']) {
                        'friend_request' => 'var(--accent)',
                        'friend_accept' => 'var(--success)',
                        'like' => 'var(--purple-light)',
                        'comment' => 'var(--accent2)',
                        'tag' => 'var(--warning)',
                        default => 'var(--border)'
                    };
                ?>">
                    <div style="display:flex;align-items:flex-start;gap:12px">
                        <div style="width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent2));display:flex;align-items:center;justify-content:center;color:white">
                            <i class="fas fa-<?php 
                                echo match($n['type']) {
                                    'friend_request', 'friend_accept' => 'user-friends',
                                    'like' => 'heart',
                                    'comment' => 'comment',
                                    'tag' => 'tag',
                                    default => 'bell'
                                };
                            ?>"></i>
                        </div>
                        
                        <div style="flex:1">
                            <div style="font-weight:500;margin-bottom:4px">
                                <?php echo h($n['notification_message'] ?? $n['message']); ?>
                            </div>
                            
                            <div class="muted" style="font-size:0.85rem;display:flex;align-items:center;gap:8px">
                                <i class="far fa-clock"></i> 
                                <?php echo h(date('d/m/Y H:i', strtotime($n['created_at']))); ?>
                                
                                <?php if ($n['type'] === 'friend_request' && isset($n['related_user_id'])): ?>
                                    <div style="display:flex;gap:8px;margin-left:auto">
                                        <a href="?r=friends/accept&id=<?php echo h($n['related_user_id']); ?>" class="btn primary sm">
                                            <i class="fas fa-check"></i> Aceptar
                                        </a>
                                        <a href="?r=friends/reject&id=<?php echo h($n['related_user_id']); ?>" class="btn sm">
                                            <i class="fas fa-times"></i> Rechazar
                                        </a>
                                    </div>
                                <?php elseif (isset($n['related_post_id'])): ?>
                                    <a href="?r=posts/view&id=<?php echo h($n['related_post_id']); ?>" class="btn sm" style="margin-left:auto">
                                        <i class="fas fa-eye"></i> Ver publicación
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="card" style="text-align:center;padding:60px 20px;background:linear-gradient(135deg, rgba(124,209,255,0.05), rgba(185,156,255,0.05))">
            <div style="width:80px;height:80px;border-radius:20px;background:linear-gradient(135deg,var(--accent),var(--accent2));display:flex;align-items:center;justify-content:center;margin:0 auto 20px;color:white;font-size:2rem">
                <i class="fas fa-bell-slash"></i>
            </div>
            <h3 style="margin:0 0 12px 0;color:var(--accent)">No hay notificaciones</h3>
            <p class="muted" style="margin:0">Cuando tengas notificaciones, aparecerán aquí</p>
        </div>
    <?php endif; ?>
</div>

<script>
    // Efecto hover en las tarjetas de notificación
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.notification-item').forEach(item => {
            item.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-5px)';
                this.style.boxShadow = '0 12px 30px rgba(0, 0, 0, 0.3)';
            });
            
            item.addEventListener('mouseleave', function() {
                this.style.transform = '';
                this.style.boxShadow = '';
            });
        });

        // Efecto hover en botones del menú
        document.querySelectorAll('.btn').forEach(btn => {
            btn.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px)';
            });
            
            btn.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
            });
        });
    });
</script>

<script>
async function deleteAllRead(){
  const ok = confirm('¿Borrar todas las notificaciones leídas?');
  if(!ok) return;
  await fetch('./?r=notifications/delete-read', {method:'POST'});
  location.reload();
}
</script>

<script>
/* live-notifs */
(function(){
  const listEl = document.getElementById('notifList');
  let page = 1, per = 10, busy = false;

  function h(s){ return (s==null?'':String(s)); }
  function time(ts){ return h(ts); }

  function notifIcon(type){
    switch(type){
      case 'friend_request': return '<i class="fas fa-user-plus"></i>';
      case 'friend_accept': return '<i class="fas fa-user-check"></i>';
      case 'comment': return '<i class="fas fa-comment"></i>';
      case 'like': return '<i class="fas fa-heart"></i>';
      case 'tag': return '<i class="fas fa-tag"></i>';
      default: return '<i class="fas fa-bell"></i>';
    }
  }

  function card(n){
    const managed = n.is_read ? '' : 'unread';
    let actions = '';
    if(n.type === 'friend_request' && !n.is_read){
      actions = `
        <div class="actions" style="display:flex;gap:8px;margin-top:8px">
          <form method="post" action="./?r=friends/accept" onsubmit="return handleAccept(event,'${h(n.related_user_id)}')">
<?= csrf_field() ?>

            <input type="hidden" name="friend_id" value="${h(n.related_user_id)}">
            <button class="btn primary" type="submit"><i class="fas fa-check"></i> Aceptar</button>
          </form>
          <form method="post" action="./?r=friends/reject" onsubmit="return handleReject(event,'${h(n.related_user_id)}')">
<?= csrf_field() ?>

            <input type="hidden" name="friend_id" value="${h(n.related_user_id)}">
            <button class="btn danger" type="submit"><i class="fas fa-times"></i> Rechazar</button>
          </form>
        </div>`;
    } else if(n.is_read){
      actions = '<span class="badge success">Gestionada</span>';
    }

    return `
      <div class="card notification ${managed}" data-id="${h(n.id)}">
        <div style="display:flex;gap:12px;align-items:flex-start;justify-content:space-between">
          <div style="display:flex;gap:12px;align-items:flex-start">
            <div class="icon">${notifIcon(n.type)}</div>
            <div>
              <div class="title">${h(n.message || '')}</div>
              <div class="meta"><i class="far fa-clock"></i> ${time(n.created_at)}</div>
            </div>
          </div>
          <div class="actions" style="display:flex;gap:8px;flex-wrap:wrap">
            <button class="btn" onclick="markRead('${h(n.id)}')" type="button"><i class="fas fa-check"></i> Leída</button>
            <button class="btn danger" onclick="deleteNotif('${h(n.id)}')" type="button"><i class="fas fa-trash"></i> Borrar</button>
          </div>
        </div>
        ${actions}
      </div>`;
  }

  async function fetchList(){
    if(busy) return; busy = true;
    try{
      const res = await fetch(`./?r=notifications/list&per=${per}&page=${page}`, {headers:{'Cache-Control':'no-cache'}});
      const data = await res.json();
      render(data.items || []);
      renderPager(data.page, data.pages);
    }catch(e){/* silent */}
    busy = false;
  }

  function render(items){
    if(!Array.isArray(items)) return;
    listEl.innerHTML = items.map(card).join('') || '<div class="card"><em>No hay notificaciones.</em></div>';
  }

  function renderPager(p, pages){
    const containerId = 'notifPager';
    let el = document.getElementById(containerId);
    if(!el){
      el = document.createElement('div');
      el.id = containerId;
      el.style = 'display:flex;gap:8px;justify-content:center;margin:12px 0';
      listEl.after(el);
    }
    const prevDis = (p<=1)?'disabled':'';
    const nextDis = (p>=pages)?'disabled':'';
    el.innerHTML = \`
      <button class="btn" \${prevDis} onclick="window.__notifSetPage(\${p-1})"><i class="fas fa-chevron-left"></i> Anterior</button>
      <span style="align-self:center">Página \${p} / \${pages}</span>
      <button class="btn" \${nextDis} onclick="window.__notifSetPage(\${p+1})">Siguiente <i class="fas fa-chevron-right"></i></button>
    \`;
    window.__notifSetPage = (np)=>{ if(np<1) return; page=np; fetchList(); };
  }

  // Hook accept/reject
  window.handleAccept = async function(ev, friendId){
    ev.preventDefault();
    try{
      await fetch('./?r=friends/accept', {method:'POST', body:new URLSearchParams({friend_id: friendId})});
      await fetchList();
    }catch(e){}
    return false;
  }
  window.handleReject = async function(ev, friendId){
    ev.preventDefault();
    try{
      await fetch('./?r=friends/reject', {method:'POST', body:new URLSearchParams({friend_id: friendId})});
      await fetchList();
    }catch(e){}
    return false;
  }

  // Reuse existing functions from page for markRead/deleteNotif; after action refresh list
  const _markRead = window.markRead;
  window.markRead = async function(id){ try{ await _markRead(id); }catch(e){} finally{ fetchList(); } }
  const _deleteNotif = window.deleteNotif;
  window.deleteNotif = async function(id){ try{ await _deleteNotif(id); }catch(e){} finally{ fetchList(); } }

  // Initial load + periodic refresh every 15s (same ritmo que badge)
  fetchList();
  setInterval(fetchList, 15000);
})();
</script>
