<header class="main-header">
  <!-- Logo -->
  <a href="#" class="logo">
    <span class="logo-mini"><b><img src="<?= base_url('assets/images/company_logo.jpg') ?>"></b></span>
    <span class="logo-lg"><b>MotorBike</b></span>
  </a>

  <!-- Header Navbar -->
  <nav class="navbar navbar-static-top" style="position: relative; height: 50px; background: #3c8dbc;">
    <!-- Sidebar toggle button -->
    <a href="#" class="sidebar-toggle" onclick="toggleSidebar()">
      <span class="sr-only">Toggle navigation</span>
    </a>

    <!-- Navbar Right Menu -->
    <ul class="navbar-nav" style="position: absolute; right: 15px; top: 50%; transform: translateY(-50%); margin: 0; padding: 0; list-style: none; display: flex; align-items: center; gap: 20px;">
      
      <!-- Notifications -->
      <li class="nav-item dropdown" style="position: relative;">
        <i class="fa fa-bell" id="notificationIcon" style="font-size: 20px; cursor: pointer; color:white;" data-toggle="dropdown"></i>
        <span id="notificationCount" class="navbar-badge"></span>
        <div class="dropdown-menu dropdown-menu-right notif-dropdown">
          <div class="notif-panel-header">
            <span class="notif-panel-title" id="notificationHeader">
              <i class="fa fa-bell"></i> Notifications
            </span>
            <button id="markAllAsReadBtn" style="display:none;">
              <i class="fa fa-check-double"></i> Tout lire
            </button>
          </div>
          <div id="notificationList"></div>
        </div>
      </li>

      <!-- User Info (sans dropdown) -->
      <li class="nav-item" style="position: relative;">
        <div style="color: white; display: flex; align-items: center; gap: 10px; padding: 5px 10px; background: rgba(255,255,255,0.1); border-radius: 20px;">
          <i class="fa fa-user-circle" style="font-size: 24px;"></i>
          <div style="display: flex; flex-direction: column; line-height: 1.2;">
            <span style="font-size: 13px; font-weight: 600;">
              <?php 
                $username = session()->get('username');
                echo $username ? esc($username) : 'Utilisateur'; 
              ?>
            </span>
            <span style="font-size: 11px; opacity: 0.8;">
              <?php 
                $role = session()->get('role');
                echo $role ? esc($role) : 'Aucun groupe'; 
              ?>
            </span>
          </div>
        </div>
      </li>
    </ul>
  </nav>
</header>

<!-- Styles -->
<style>
  .navbar-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    padding: 3px 6px;
    border-radius: 10px;
    background: #e74c3c;
    color: white;
    font-size: 10px;
    font-weight: 700;
    line-height: 1;
    min-width: 18px;
    text-align: center;
  }

  /* Dropdown container */
  .notif-dropdown {
    width: 420px;
    padding: 0;
    max-height: 520px;
    display: flex;
    flex-direction: column;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 8px 30px rgba(0,0,0,0.15);
    border: 1px solid rgba(0,0,0,0.08);
  }

  /* Header du panel */
  .notif-panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 16px;
    background: linear-gradient(135deg, #2c3e50, #3498db);
    color: white;
    flex-shrink: 0;
  }

  .notif-panel-title {
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 0.5px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  #markAllAsReadBtn {
    background: rgba(255,255,255,0.2);
    border: 1px solid rgba(255,255,255,0.4);
    color: white;
    font-size: 11px;
    padding: 4px 10px;
    border-radius: 20px;
    cursor: pointer;
    white-space: nowrap;
    transition: all 0.2s;
  }

  #markAllAsReadBtn:hover {
    background: rgba(255,255,255,0.35);
  }

  /* Liste scrollable */
  #notificationList {
    overflow-y: auto;
    flex: 1;
    padding: 8px;
    background: #f8f9fa;
  }

  #notificationList:empty::after {
    content: 'Aucune notification';
    display: block;
    text-align: center;
    padding: 30px;
    color: #aaa;
    font-size: 13px;
  }

  /* Carte de notification */
  .notif-card {
    display: flex;
    align-items: stretch;
    margin-bottom: 6px;
    border-radius: 8px;
    border: 1px solid #e8e8e8;
    background: #fff;
    text-decoration: none !important;
    color: inherit !important;
    overflow: hidden;
    position: relative;
    transition: box-shadow 0.2s, transform 0.1s;
    cursor: pointer;
  }

  .notif-card:hover {
    box-shadow: 0 3px 12px rgba(0,0,0,0.1);
    transform: translateY(-1px);
    text-decoration: none !important;
    color: inherit !important;
  }

  .notif-card.notif-unread {
    background: #f0f7ff;
    border-color: #b8d9f8;
  }

  /* Barre colorée à gauche */
  .notif-accent {
    width: 5px;
    flex-shrink: 0;
  }

  /* Corps de la notif */
  .notif-body {
    flex: 1;
    padding: 10px 12px;
    min-width: 0;
  }

  /* En-tête : type + heure */
  .notif-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    gap: 8px;
  }

  .notif-type-badge {
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 2px 8px;
    border-radius: 20px;
    color: #fff;
    white-space: nowrap;
    flex-shrink: 0;
  }

  .notif-time {
    font-size: 11px;
    color: #999;
    white-space: nowrap;
    flex-shrink: 0;
  }

  /* Contenu du message */
  .notif-message {
    font-size: 12.5px;
    color: #444;
    line-height: 1.55;
    word-break: break-word;
  }

  .notif-card.notif-unread .notif-message {
    color: #1a1a2e;
    font-weight: 500;
  }

  /* Point bleu "non lu" */
  .notif-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #3498db;
    flex-shrink: 0;
    align-self: flex-start;
    margin: 12px 10px 0 0;
  }
</style>

<script>
function fetchNotifications() {
  $.ajax({
    url: '/notifications',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
      let notificationCount = 0;
      let notificationHTML = '';

      data.forEach(notif => {
        if (notif.is_read == 0) notificationCount++;

        const href = '/' + notif.link.replace(/^\/+/, '');
        const isUnread = notif.is_read == 0;

        // Détecter le type à partir du début du message
        let accentColor = '#7f8c8d';
        let badgeColor  = '#7f8c8d';
        let typeLabel   = 'Info';
        let typeIcon    = 'fa-bell';

        const msg = notif.message || '';
        if (msg.includes('💰') || msg.toLowerCase().includes('remise')) {
          accentColor = '#f39c12'; badgeColor = '#e67e22'; typeLabel = 'Remise'; typeIcon = 'fa-tag';
        } else if (msg.includes('📦') || msg.toLowerCase().includes('commande')) {
          accentColor = '#3498db'; badgeColor = '#2980b9'; typeLabel = 'Commande'; typeIcon = 'fa-shopping-cart';
        } else if (msg.includes('✅') || msg.toLowerCase().includes('acceptée') || msg.toLowerCase().includes('validée')) {
          accentColor = '#27ae60'; badgeColor = '#219a52'; typeLabel = 'Accepté'; typeIcon = 'fa-check-circle';
        } else if (msg.includes('❌') || msg.toLowerCase().includes('refusée')) {
          accentColor = '#e74c3c'; badgeColor = '#c0392b'; typeLabel = 'Refusé'; typeIcon = 'fa-times-circle';
        } else if (msg.toLowerCase().includes('livraison') || msg.toLowerCase().includes('remis')) {
          accentColor = '#9b59b6'; badgeColor = '#8e44ad'; typeLabel = 'Livraison'; typeIcon = 'fa-truck';
        }

        // Formater la date lisiblement
        let dateDisplay = notif.created_at || '';
        try {
          const d = new Date(notif.created_at);
          if (!isNaN(d)) {
            const now = new Date();
            const diffMs = now - d;
            const diffMn = Math.floor(diffMs / 60000);
            const diffH  = Math.floor(diffMn / 60);
            if (diffMn < 1)        dateDisplay = 'À l\'instant';
            else if (diffMn < 60)  dateDisplay = diffMn + ' min';
            else if (diffH < 24)   dateDisplay = diffH + 'h';
            else                   dateDisplay = d.toLocaleDateString('fr-FR', {day:'2-digit', month:'2-digit'});
          }
        } catch(e) {}

        notificationHTML += `
          <a href="${href}" class="notif-card ${isUnread ? 'notif-unread' : ''}" data-id="${notif.id}">
            <div class="notif-accent" style="background:${accentColor};"></div>
            <div class="notif-body">
              <div class="notif-header">
                <span class="notif-type-badge" style="background:${badgeColor};">
                  <i class="fa ${typeIcon}"></i> ${typeLabel}
                </span>
                <span class="notif-time"><i class="fa fa-clock-o"></i> ${dateDisplay}</span>
              </div>
              <div class="notif-message">${msg}</div>
            </div>
            ${isUnread ? '<div class="notif-dot"></div>' : ''}
          </a>
        `;
      });

      if (notificationHTML === '') {
        notificationHTML = '';
      }

      $('#notificationList').html(notificationHTML);

      const unreadLabel = notificationCount > 0
        ? `<i class="fa fa-bell"></i> ${notificationCount} non lue${notificationCount > 1 ? 's' : ''}`
        : `<i class="fa fa-bell"></i> Notifications`;
      $('#notificationHeader').html(unreadLabel);

      if (notificationCount > 0) {
        $('#notificationCount').text(notificationCount).show();
        $('#markAllAsReadBtn').show();
      } else {
        $('#notificationCount').hide();
        $('#markAllAsReadBtn').hide();
      }

      document.querySelectorAll('.notif-card').forEach(item => {
        item.addEventListener('click', () => {
          const notifId = item.dataset.id;
          fetch("<?= base_url('notifications/markAsRead') ?>/" + notifId, {
            method: "POST",
            headers: { "Content-Type": "application/json" }
          })
          .then(r => r.json())
          .catch(e => console.error(e));
        });
      });
    },
    error: function(err) {
      console.error('Error fetching notifications:', err);
    }
  });
}

function markAllAsRead() {
  fetch("<?= base_url('notifications/markAllAsRead') ?>", {
    method: "POST",
    headers: { "Content-Type": "application/json" }
  })
  .then(response => response.json())
  .then(data => {
    console.log("All notifications marked as read:", data);
    fetchNotifications();
  })
  .catch(error => console.error("Error:", error));
}

$(document).on('click', '#markAllAsReadBtn', function(e) {
  e.preventDefault();
  e.stopPropagation();
  markAllAsRead();
});

setInterval(fetchNotifications, 10000);
fetchNotifications();
</script>