<script>
  document.addEventListener("DOMContentLoaded", () => {
    // Get server user image or localStorage image
    <%
      let serverUserImg = (typeof user !== 'undefined' && user) ? (user.image?.img_path || user.img_path || '') : '';
      let serverUserName = (typeof user !== 'undefined' && user) ? (user.u_name || ((user.u_fname || '') + ' ' + (user.u_lname || '')).trim() || user.company_name || user.u_email || 'Admin') : 'Admin';
      let serverUserRole = (typeof user !== 'undefined' && user) ? (user.group_id === 5 ? 'Fleet Operator' : (user.group_id === 6 ? 'Corporate Admin' : (user.group_id === 9 || user.is_ltfrb || user.u_email === 'ltfrb@gmail.com' || user.group_id === 3 ? 'Sub Admin' : 'Admin'))) : 'Admin';
    %>
    const serverImg = <%- JSON.stringify(serverUserImg) %>;
    let img = serverImg || localStorage.getItem("img") || "";

    // Get and parse user info
    const userStr = localStorage.getItem("user");
    let name = <%- JSON.stringify(serverUserName) %>;
    let subtext = <%- JSON.stringify(serverUserRole) %>;

    try {
      if (userStr) {
        const parsed = JSON.parse(userStr);
        if (!name || name === "undefined") {
          name = parsed?.u_name || parsed?.name || `${parsed?.u_fname || ''} ${parsed?.u_lname || ''}`.trim() || parsed?.company_name || parsed?.u_email || "Admin";
        }
        if (parsed?.group_id === 5) {
          subtext = "Fleet Operator";
        } else if (parsed?.group_id === 6) {
          subtext = "Corporate Admin";
        } else if (parsed?.group_id === 9 || parsed?.email === "ltfrb@gmail.com" || parsed?.group_id === 3) {
          subtext = "Sub Admin";
        }
      }
    } catch (e) {
      console.error("Invalid user data in localStorage", e);
    }

    if (!name || name === "undefined") name = "Admin";
    if (!subtext || subtext === "undefined") subtext = "Admin";

    // Set name and role subtext if elements exist
    const nameElement = document.getElementById("name");
    if (nameElement) {
      nameElement.innerText = name;
    }
    const subtextElement = document.getElementById("userRoleSubtext");
    if (subtextElement) {
      subtextElement.innerText = subtext;
    }

    // Clean leading/trailing quotes from img value
    img = img?.replace(/^['"]|['"]$/g, '');

    // Set image src if valid
    const profileImage = document.getElementById("profileImage");
    if (img && profileImage) {
      profileImage.src = img.startsWith("http") ? img : `<%=CATEGORY_BASE_URL %>${img.startsWith('/') ? img.substring(1) : img}`;
    }

    // Check for expired driver documents notification
    fetch('/admin/expired-driver-documents')
      .then(res => {
        if (!res.ok) throw new Error('Network response was not ok');
        return res.json();
      })
      .then(data => {
        const container = document.getElementById('expiredDocsDropdownContainer');
        const badge = document.getElementById('expiredDocsBadge');
        const list = document.getElementById('expiredDocsList');
        if (container && badge && list) {
          if (data && data.success && data.count > 0) {
            container.style.display = 'block';
            badge.innerText = data.count;
            let html = '';
            data.expiredDocuments.forEach(item => {
              const driverName = item.driver ? (item.driver.d_name || (item.driver.d_fname + ' ' + item.driver.d_lname)) : 'Driver #' + item.driver_id;
              let expireDate = 'Expired';
              if (item.expire_date) {
                const parts = String(item.expire_date).split('T')[0].split(' ')[0].split('-');
                expireDate = (parts.length === 3) ? `${parts[2]}/${parts[1]}/${parts[0]}` : String(item.expire_date);
              }
              html += `<div class="p-2 mb-2 bg-light rounded border border-danger-subtle">
                         <strong>${driverName}</strong><br/>
                         <span class="text-danger fw-semibold">${item.asset_type || 'Document'}</span> filters expired on <strong>${expireDate}</strong>
                       </div>`;
            });
            list.innerHTML = html;
          } else {
            container.style.display = 'none';
          }
        }
      })
      .catch(e => {
        console.error('Expired docs notification error:', e);
      });
  });
</script>
<style>
  .dropdown-menu.show{
    padding: 20px !important;
  }
</style>


<div class="navbar-header shadow-sm">
  <div class="row align-items-center justify-content-between">
    <div class="col-auto">
      <div class="d-flex flex-wrap align-items-center gap-4">
        <button type="button" class="sidebar-toggle">
          <iconify-icon icon="heroicons:bars-3-solid" class="icon text-2xl non-active"></iconify-icon>
          <iconify-icon icon="iconoir:arrow-right" class="icon text-2xl active"></iconify-icon>
        </button>
        <button type="button" class="sidebar-mobile-toggle">
          <iconify-icon icon="heroicons:bars-3-solid" class="icon"></iconify-icon>
        </button>
      </div>
    </div>
    <div class="col-auto" style="z-index: 9999 !important; display: flex; justify-content: center; align-items: center;">
 <%- include('../partials/utils/multicity') %>

      <div class="d-flex flex-wrap align-items-center gap-3">
        <!-- Expired Documents Notification Bell -->
        <div class="dropdown" id="expiredDocsDropdownContainer" style="display: none;">
          <button class="btn btn-outline-danger position-relative d-flex align-items-center justify-content-center p-2 rounded-circle" type="button" data-bs-toggle="dropdown" data-bs-boundary="window" title="Expired Driver Documents">
            <iconify-icon icon="solar:bell-bing-bold" class="text-xl text-danger"></iconify-icon>
            <span id="expiredDocsBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">0</span>
          </button>
          <div class="dropdown-menu dropdown-menu-end p-3 shadow-lg" style="width: 320px; max-height: 250px; overflow-y: auto; overflow-x: hidden; z-index: 100005 !important; position: absolute !important; right: 0 !important; left: auto !important;">
            <h6 class="text-danger fw-bold mb-2">⚠️ Expired Driver Documents</h6>
            <hr class="my-2"/>
            <div id="expiredDocsList" class="small text-secondary">Loading...</div>
          </div>
        </div>

        <!-- Light / Dark Mode Theme Toggle (Remixicon loads in head — always visible) -->
        <button
          id="themeToggleBtn"
          type="button"
          class="btn btn-outline-primary d-inline-flex align-items-center justify-content-center rounded-circle"
          style="width: 42px; height: 42px; min-width: 42px; padding: 0;"
          title="Toggle Light/Dark Theme"
          aria-label="Toggle Light/Dark Theme"
          onclick="toggleAdminTheme()"
        >
          <i id="themeToggleIcon" class="ri-sun-fill" style="font-size: 1.35rem; line-height: 1;"></i>
        </button>

        <div class="dropdown">
          <button class="d-flex justify-content-center align-items-center rounded-circle" type="button" data-bs-toggle="dropdown">
            <img id="profileImage" src="/default.jpg" alt="image" class="w-40-px h-40-px object-fit-cover rounded-circle no-popup" >
          </button>
          <div class="dropdown-menu to-top dropdown-menu-sm">
            <div class="py-12 px-16 radius-8 bg-primary-50 mb-16 d-flex align-items-center justify-content-between gap-2">
              <div>
                <h6 class="text-lg text-primary-light fw-semibold mb-2" id="name"><%= serverUserName %></h6>
                <span class="text-secondary-light fw-medium text-sm" id="userRoleSubtext"><%= serverUserRole %></span>
              </div>
              <button type="button" class="hover-text-danger">
                <iconify-icon icon="radix-icons:cross-1" class="icon text-xl"></iconify-icon>
              </button>
            </div>
            <ul class="to-top-list">
              <li>
                <a class="dropdown-item text-black px-0 py-8 hover-bg-transparent hover-text-primary d-flex align-items-center gap-3" href="/admin/edit-admin">
                  <iconify-icon icon="solar:user-linear" class="icon text-xl"></iconify-icon> Edit Profile
                </a>
              </li>
              <li>
                <a class="dropdown-item text-black px-0 py-8 hover-bg-transparent hover-text-primary d-flex align-items-center gap-3" href="/admin/change-password">
                  <iconify-icon icon="tabler:message-check" class="icon text-xl"></iconify-icon> Change Password
                </a>
              </li>
              <li>
                <a onclick="handleLogout()" class="dropdown-item text-black px-0 py-8 hover-bg-transparent hover-text-danger d-flex align-items-center gap-3" href="javascript:void(0)">
                  <iconify-icon icon="lucide:power" class="icon text-xl"></iconify-icon> Logout
                </a>
              </li>
            </ul>
          </div>
        </div><!-- Profile dropdown end -->
      </div>
    </div>
  </div>
</div>

<div id="loader" class="text-center my-4">
  <img src="/loader.gif" alt="Loading..." width="60">
</div>
 

<script>
  function handleLogout() {
    fetch('/admin/logout', {
        method: 'GET',
        credentials: 'include'
      })
      .then(response => {
        const remEmail = localStorage.getItem("rememberedEmail");
        const remPass = localStorage.getItem("rememberedPassword");
        const remLtfrbEmail = localStorage.getItem("rememberedLtfrbEmail");
        const remLtfrbPass = localStorage.getItem("rememberedLtfrbPassword");
        const savedTheme = localStorage.getItem("theme");
        localStorage.clear();
        if (remEmail) localStorage.setItem("rememberedEmail", remEmail);
        if (remPass) localStorage.setItem("rememberedPassword", remPass);
        if (remLtfrbEmail) localStorage.setItem("rememberedLtfrbEmail", remLtfrbEmail);
        if (remLtfrbPass) localStorage.setItem("rememberedLtfrbPassword", remLtfrbPass);
        if (savedTheme === "dark" || savedTheme === "light") {
          localStorage.setItem("theme", savedTheme);
        }
        window.location.href = '/admin/login';
      })
      .catch(error => {
        console.error('Error:', error);
        window.location.href = '/admin/login';
      });
  }

  $(document).ready(function() {
    $("#loader").hide();
  });

  function updateAdminThemeIcon(theme) {
    const icon = document.getElementById("themeToggleIcon");
    const btn = document.getElementById("themeToggleBtn");
    if (!icon) return;
    if (theme === "dark") {
      icon.className = "ri-moon-fill";
      icon.style.fontSize = "1.35rem";
      icon.style.lineHeight = "1";
      if (btn) {
        btn.classList.remove("btn-outline-primary");
        btn.classList.add("btn-outline-warning");
      }
    } else {
      icon.className = "ri-sun-fill";
      icon.style.fontSize = "1.35rem";
      icon.style.lineHeight = "1";
      if (btn) {
        btn.classList.remove("btn-outline-warning");
        btn.classList.add("btn-outline-primary");
      }
    }
  }

  function toggleAdminTheme() {
    const currentTheme = document.documentElement.getAttribute("data-theme") || "light";
    const newTheme = currentTheme === "dark" ? "light" : "dark";
    document.documentElement.setAttribute("data-theme", newTheme);
    try {
      localStorage.setItem("theme", newTheme);
    } catch (e) {}
    updateAdminThemeIcon(newTheme);
  }

  document.addEventListener("DOMContentLoaded", function () {
    const activeTheme = document.documentElement.getAttribute("data-theme") || "light";
    updateAdminThemeIcon(activeTheme);
  });
</script>

