   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->
     <script src="/js/validator/validation.js"></script>
     <style>
       .notification-container {
         max-width: 1200px;
         margin: 0 auto;
         padding: 20px;
       }

       #audienceSelect {
         border: 1px solid grey;
         border-radius: 8px;
         padding: 10px;
       }

       .card {
         background: white;
         border-radius: 12px;
         box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
         padding: 24px;
         margin-bottom: 24px;
       }

       .section-title {
         font-size: 18px;
         font-weight: 600;
         color: #374151;
         margin-bottom: 16px;
       }

       .radio-group {
         display: flex;
         gap: 24px;
         margin-bottom: 20px;
       }

       .radio-option {
         display: flex;
         align-items: center;
         gap: 8px;
         cursor: pointer;
       }

       .radio-option input {
         width: 18px;
         height: 18px;
         cursor: pointer;
       }

       .dropdown-container {
         position: relative;
         margin-bottom: 20px;
       }

       .dropdown-button {
         display: flex;
         align-items: center;
         justify-content: space-between;
         padding: 10px 16px;
         background: #f3f4f6;
         border: 1px solid #d1d5db;
         border-radius: 8px;
         width: 100%;
         cursor: pointer;
         transition: all 0.2s;
       }

       .dropdown-button:hover {
         background: #e5e7eb;
       }

       .dropdown-menu {
         position: absolute;
         top: 100%;
         left: 0;
         width: 100%;
         max-height: 300px;
         overflow-y: auto;
         background: white;
         border: 1px solid #d1d5db;
         border-radius: 8px;
         box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
         z-index: 10;
         display: none;
         margin-top: 4px;
       }

       .dropdown-menu.show {
         display: block;
       }

       .search-box {
         padding: 5px;
         position: sticky;
         top: -16px;
         z-index: 999;
         background-color: #fff;
         border-bottom: 1px solid #e5e7eb;
       }

       .search-box input {
         width: 100%;
         padding: 8px 12px;
         border: 1px solid #d1d5db;
         border-radius: 6px;
       }

       .dropdown-list {
         padding: 0;
         margin: 0;
         list-style: none;
       }

       .dropdown-item {
         padding: 12px 16px;
         display: flex;
         align-items: center;
         gap: 12px;
         cursor: pointer;
         transition: background 0.2s;
       }

       .dropdown-item:hover {
         background: #f3f4f6;
       }

       .dropdown-item input {
         width: 18px;
         height: 18px;
         cursor: pointer;
       }

    
       .select-all {
         padding: 12px 16px;
         display: flex;
         position: sticky;
         bottom: -20px;
         align-items: center;
         background-color: #fff;
         gap: 8px;
         color: #3b82f6;
         font-weight: 500;
         cursor: pointer;
         border-top: 1px solid #e5e7eb;
       }

       .form-group {
         margin-bottom: 20px;
       }

       .form-label {
         display: block;
         margin-bottom: 8px;
         font-weight: 500;
         color: #374151;
       }

       .form-input {
         width: 100%;
         padding: 10px 12px;
         border: 1px solid #d1d5db;
         border-radius: 8px;
         transition: border 0.2s;
       }

       .form-input:focus {
         outline: none;
         border-color: #3b82f6;
         box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
       }

       .form-textarea {
         width: 100%;
         padding: 12px;
         border: 1px solid #d1d5db;
         border-radius: 8px;
         min-height: 120px;
         resize: vertical;
       }

       .form-textarea:focus {
         outline: none;
         border-color: #3b82f6;
         box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
       }

       .submit-btn {
         background: #3b82f6;
         color: white;
         padding: 12px 24px;
         border: none;
         border-radius: 8px;
         font-weight: 500;
         cursor: pointer;
         transition: background 0.2s;
       }

       .submit-btn:hover {
         background: #2563eb;
       }

       .submit-btn:disabled {
         background: #9ca3af;
         cursor: not-allowed;
       }

       .hidden {
         display: none;
       }

       .audience-actions {
         display: grid;
         gap: 12px;
         margin-bottom: 16px;
       }

       .create-audience-btn {
         background: #10b981;
         color: white;
         padding: 10px 16px;
         border-radius: 8px;
         font-weight: 500;
         text-decoration: none;
         display: inline-flex;
         align-items: center;
         gap: 8px;
       }

       .create-audience-btn:hover {
         background: #059669;
       }

       .audience-select {
         width: 100%;
         padding: 10px 12px;
         border: 1px solid #d1d5db;
         border-radius: 8px;
       }

       .info-text {
         font-size: 14px;
         color: #6b7280;
         margin-top: 4px;
       }

       .badge {
         display: inline-block;
         padding: 4px 8px;
         background: #e5e7eb;
         border-radius: 999px;
         font-size: 12px;
         margin-left: 8px;
       }

       .loading-spinner {
         display: inline-block;
         width: 16px;
         height: 16px;
         border: 2px solid rgba(255, 255, 255, 0.3);
         border-radius: 50%;
         border-top-color: white;
         animation: spin 1s ease-in-out infinite;
       }

       .dropdown-menu * {
         pointer-events: auto;
       }

       @keyframes spin {
         to {
           transform: rotate(360deg);
         }
       }
     </style>

     <div class="container pt-20">
       <%- include('../../partials/utils/title.ejs', {title: "Notification Manager"}) %>

       <% 
      const breadcrumbs = [
        { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
        { label: "Notification Manager" }
      ];
    %>
       <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

       <div class="card">
         <h2 class="text-xl font-semibold text-gray-800 mb-6">Send Notification</h2>

         <!-- Audience Info Section -->
         <div class="mb-8">
           <hr />
           <div class="radio-group pt-8">
             <% if (user.group_id !== 6) { %>
             <label class="radio-option">
               <input type="radio" name="audience" value="driver" class="form-check-input" checked>
               <span>Driver</span>
             </label>
             <% } %>
             <% if (user.group_id !== 5) { %>
             <label class="radio-option">
               <input type="radio" name="audience" class="form-check-input" value="user" <%= user.group_id === 6 ? 'checked' : '' %>>
               <span>User</span>
             </label>
             <% } %>
           </div>

           <div class="radio-group">
             <label class="radio-option">
               <input type="radio" name="selection" class="form-check-input" value="manual" checked>
               <span>Manual Selection</span>
             </label>
             <label class="radio-option">
               <input type="radio" name="selection" class="form-check-input" value="audience">
               <span>Audience</span>
             </label>
           </div>

           <div class="radio-group">
             <label class="radio-option">
               <input type="radio" name="type" class="form-check-input" value="single" checked>
               <span>Single</span>
             </label>
             <label class="radio-option">
               <input type="radio" name="type" class="form-check-input" value="broadcast">
               <span>Broadcast <span class="info-text">(Notification only, not saved)</span></span>
             </label>
           </div>
         </div>

         <!-- Manual Selection UI -->
         <div id="manual-selection">
           <!-- Driver Select -->
           <div id="driver-select">
             <div class="dropdown-container">
               <label class="form-label">Select Driver(s)</label>
               <button id="dropdownDriverButton" class="dropdown-button">
                 <span id="driverButtonText">Select driver</span>
                 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                   <path d="M6 9l6 6 6-6" />
                 </svg>
               </button>

               <div id="dropdownDriver" class="dropdown-menu">
                 <div class="search-box">
                   <input type="text" id="driver-search" placeholder="Search driver...">
                 </div>
                 <ul class="dropdown-list" id="driver-list">
                   <!-- Driver items will be loaded here via JavaScript -->
                   <li class="dropdown-item">
                     <div class="spinner-border text-primary" role="status">
                       <span class="visually-hidden">Loading...</span>
                     </div>
                   </li>
                 </ul>
                 <div class="select-all" id="select-all-drivers">
                   <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                     <path d="M6.5 9a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9ZM8 10H5a5.006 5.006 0 0 0-5 5v2a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-2a5.006 5.006 0 0 0-5-5Zm11-3h-6a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2Z" />
                   </svg>
                   Select all
                 </div>
               </div>
             </div>
           </div>

           <!-- User Select -->
           <div id="user-select" class="hidden">
             <div class="dropdown-container">
               <label class="form-label">Select User(s)</label>
               <button id="dropdownUserButton" class="dropdown-button">
                 <span id="userButtonText">Select user</span>
                 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                   <path d="M6 9l6 6 6-6" />
                 </svg>
               </button>

               <div id="dropdownUser" class="dropdown-menu">
                 <div class="search-box">
                   <input type="text" id="user-search" placeholder="Search user...">
                 </div>
                 <ul class="dropdown-list" id="user-list">
                   <!-- User items will be loaded here via JavaScript -->
                   <li class="dropdown-item">
                     <div class="spinner-border text-primary" role="status">
                       <span class="visually-hidden">Loading...</span>
                     </div>
                   </li>
                 </ul>
                 <div class="select-all" id="select-all-users">
                   <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                     <path d="M6.5 9a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9ZM8 10H5a5.006 5.006 0 0 0-5 5v2a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-2a5.006 5.006 0 0 0-5-5Zm11-3h-6a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2Z" />
                   </svg>
                   Select all
                 </div>
               </div>
             </div>
           </div>
         </div>

         <!-- Audience Selection UI -->
         <div id="audience-selection" class="hidden">
           <div class="form-group">
             <label class="form-label">Select Audience</label>
             <div class="audience-actions">
               <a id="createDriverAudienceBtn" href="/admin/driver-audience" class="create-audience-btn">
                 <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                   <path d="M12 4v16m8-8H4" />
                 </svg>
                 Create Driver Audience
               </a>
               <a id="createUserAudienceBtn" href="/admin/rider-audience" class="create-audience-btn hidden">
                 <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                   <path d="M12 4v16m8-8H4" />
                 </svg>
                 Create User Audience
               </a>
             </div>
             <select id="audienceSelect" class="audience-select">
               <option value="">Select an audience...</option>
               <!-- Audience options will be loaded here via JavaScript -->
             </select>
           </div>
         </div>

         <!-- Notification Form -->
         <form id="notification-form">
           <div class="form-group">
             <label class="form-label">Title</label>
             <input type="text" id="notification-title" name="notificationTitle" class="form-input" required>
           </div>

           <div class="form-group">
             <label class="form-label">URL</label>
             <input type="url" name="notificationUrl" class="form-input" placeholder="http://www.example.com">
             <p class="info-text">URL requires HTTP/HTTPS protocol</p>
           </div>

           <div class="form-group">
             <label class="form-label">Message</label>
             <textarea name="notificationMessage" id="notification-message" class="form-textarea" required></textarea>
           </div>

           <div class="flex justify-end mt-6">
             <button type="button" id="sendNotificationBtn" class="submit-btn">
               Send Notification
             </button>
           </div>
         </form>
       </div>
     </div>
   </main>




   <script>
     // Get URL param for audience ID
     const pathParts = window.location.pathname.split('/');
     const preselectedAudienceId = pathParts[pathParts.length - 1]; // Gets "23" from "/admin/sendNotification/23"

     document.addEventListener('DOMContentLoaded', function() {


       // Define form configuration
       const formConfig = {
         formId: "notification-form",
         fields: [{
             name: "notificationTitle",
             type: "text",
             required: true,
             messages: {
               required: "Title is required"
             }
           },
           {
             name: "notificationUrl",
             type: "text",
             required: false,
             messages: {
               required: "URL is required"
             }
           },
           {
             name: "notificationMessage",
             type: "text",
             required: true,
             messages: {
               invalid: "Message is required"
             }
           }
         ]
       };
       // Global state
       const state = {
         drivers: [],
         users: [],
         driverAudiences: [],
         userAudiences: [],
         selectedDrivers: [],
         selectedUsers: []
       };

       // DOM elements
       const elements = {
         driverSelect: document.getElementById('driver-select'),
         userSelect: document.getElementById('user-select'),
         manualSelection: document.getElementById('manual-selection'),
         audienceSelection: document.getElementById('audience-selection'),
         createDriverAudienceBtn: document.getElementById('createDriverAudienceBtn'),
         createUserAudienceBtn: document.getElementById('createUserAudienceBtn'),
         audienceSelect: document.getElementById('audienceSelect'),
         driverDropdown: document.getElementById('dropdownDriver'),
         userDropdown: document.getElementById('dropdownUser'),
         driverList: document.getElementById('driver-list'),
         userList: document.getElementById('user-list'),
         driverSearch: document.getElementById('driver-search'),
         userSearch: document.getElementById('user-search'),
         driverButton: document.getElementById('dropdownDriverButton'),
         userButton: document.getElementById('dropdownUserButton'),
         driverButtonText: document.getElementById('driverButtonText'),
         userButtonText: document.getElementById('userButtonText'),
         selectAllDrivers: document.getElementById('select-all-drivers'),
         selectAllUsers: document.getElementById('select-all-users'),
         sendNotificationBtn: document.getElementById('sendNotificationBtn'),
         notificationForm: document.getElementById('notification-form')
       };

       // Initialize the page
       init();

async function init() {
  // Load initial data
  await fetchDrivers();
  await fetchUsers();
  await fetchDriverAudiences();
  await fetchUserAudiences();

  // Check if we have a valid preselected audience ID
  if (preselectedAudienceId && preselectedAudienceId !== "sendNotification") {
    // Try to find the audience in driver or user lists
    const matchedDriverAudience = state.driverAudiences.find(
      a => String(a.audience_id) === preselectedAudienceId
    );
    const matchedUserAudience = state.userAudiences.find(
      a => String(a.audience_id) === preselectedAudienceId
    );

    if (matchedDriverAudience) {
      // Set driver audience type and selection type
      document.querySelector('input[name="audience"][value="driver"]').checked = true;
      document.querySelector('input[name="selection"][value="audience"]').checked = true;

      // Update UI
      toggleAudienceType('driver');
      toggleSelectionType('audience');

      // Wait for audiences to load, then select the audience
      setTimeout(() => {
        elements.audienceSelect.value = preselectedAudienceId;
      }, 100);
    } else if (matchedUserAudience) {
      // Set user audience type and selection type
      document.querySelector('input[name="audience"][value="user"]').checked = true;
      document.querySelector('input[name="selection"][value="audience"]').checked = true;

      // Update UI
      toggleAudienceType('user');
      toggleSelectionType('audience');

      // Wait for audiences to load, then select the audience
      setTimeout(() => {
        elements.audienceSelect.value = preselectedAudienceId;
      }, 100);
    } else {
      // If no matching audience found, default to driver and manual
      document.querySelector('input[name="audience"][value="driver"]').checked = true;
      document.querySelector('input[name="selection"][value="manual"]').checked = true;
      toggleAudienceType('driver');
      toggleSelectionType('manual');
    }
  } else {
    // Default based on user group_id
    const userGroupId = <%= user.group_id %>;
    
    if (userGroupId === 6) {
      // Corporate admin - default to user
      const userRadio = document.querySelector('input[name="audience"][value="user"]');
      if (userRadio) {
        userRadio.checked = true;
        toggleAudienceType('user');
      }
    } else {
      // Company admin or super admin - default to driver
      const driverRadio = document.querySelector('input[name="audience"][value="driver"]');
      if (driverRadio) {
        driverRadio.checked = true;
        toggleAudienceType('driver');
      }
    }
    
    document.querySelector('input[name="selection"][value="manual"]').checked = true;
    toggleSelectionType('manual');
  }

  // Set up event listeners
  setupEventListeners();
}

       function setupEventListeners() {
         // Audience type toggle
         document.querySelectorAll('input[name="audience"]').forEach(radio => {
           radio.addEventListener('change', function() {
             toggleAudienceType(this.value);
           });
         });

         // Selection type toggle
         document.querySelectorAll('input[name="selection"]').forEach(radio => {
           radio.addEventListener('change', function() {
             toggleSelectionType(this.value);
           });
         });

         // Fixed dropdown toggle handlers
         elements.driverButton.addEventListener('click', function(e) {
           e.stopPropagation();
           // Close the other dropdown
           elements.userDropdown.classList.remove('show');
           // Toggle this dropdown
           elements.driverDropdown.classList.toggle('show');
         });

         elements.userButton.addEventListener('click', function(e) {
           e.stopPropagation();
           // Close the other dropdown
           elements.driverDropdown.classList.remove('show');
           // Toggle this dropdown
           elements.userDropdown.classList.toggle('show');
         });

         // Fixed click outside handler
         document.addEventListener('click', function(e) {
           // Only close if clicking outside of both dropdown buttons and dropdown menus
           if (!elements.driverButton.contains(e.target) &&
             !elements.userButton.contains(e.target) &&
             !elements.driverDropdown.contains(e.target) &&
             !elements.userDropdown.contains(e.target)) {
             elements.driverDropdown.classList.remove('show');
             elements.userDropdown.classList.remove('show');
           }
         });

         // Prevent clicks inside dropdown content from closing
         elements.driverDropdown.addEventListener('click', function(e) {
           e.stopPropagation();
         });

         elements.userDropdown.addEventListener('click', function(e) {
           e.stopPropagation();
         });

         // Search functionality
         elements.driverSearch.addEventListener('input', function() {
           filterList(this.value, 'driver');
         });

         elements.userSearch.addEventListener('input', function() {
           filterList(this.value, 'user');
         });

         // Select all functionality
         elements.selectAllDrivers.addEventListener('click', function() {
           selectAll('driver');
         });

         elements.selectAllUsers.addEventListener('click', function() {
           selectAll('user');
         });

         // Form validation
         // Handle send notification button click
         elements.sendNotificationBtn.addEventListener('click', function(e) {
           e.preventDefault();
           sendNotification();
         });

         // Also keep the form submit handler as a fallback
         elements.notificationForm.addEventListener('submit', function(e) {
           e.preventDefault();
           sendNotification();
         });
       }


       function toggleAudienceType(type) {
         if (type === 'driver') {
           elements.driverSelect.classList.remove('hidden');
           elements.userSelect.classList.add('hidden');

           // Only show driver audience button
           elements.createDriverAudienceBtn.style.display = 'inline-flex';
           elements.createUserAudienceBtn.style.display = 'none';

           // Update audience dropdown with driver audiences
           updateAudienceSelect(type);
         } else {
           elements.driverSelect.classList.add('hidden');
           elements.userSelect.classList.remove('hidden');

           // Only show user audience button
           elements.createDriverAudienceBtn.style.display = 'none';
           elements.createUserAudienceBtn.style.display = 'inline-flex';

           // Update audience dropdown with user audiences
           updateAudienceSelect(type);
         }
       }

       function toggleSelectionType(type) {
         if (type === 'manual') {
           elements.manualSelection.classList.remove('hidden');
           elements.audienceSelection.classList.add('hidden');
           // Ensure correct dropdown is visible for manual selection
           const audienceType = document.querySelector('input[name="audience"]:checked')?.value || 'driver';
           toggleAudienceType(audienceType);
         } else {
           elements.manualSelection.classList.add('hidden');
           elements.audienceSelection.classList.remove('hidden');

           // Update the audience dropdown based on current audience type
           const audienceType = document.querySelector('input[name="audience"]:checked')?.value || 'driver';
           updateAudienceSelect(audienceType);
         }
       }

       // Initialize with driver audience button visible and user audience button hidden
       elements.createDriverAudienceBtn.style.display = 'inline-flex';
       elements.createUserAudienceBtn.style.display = 'none';

       async function fetchDrivers() {
         try {
           const response = await fetch('/admin/active/driver/options?d_active=1&is_delete=0');
           if (!response.ok) throw new Error('Failed to fetch drivers');

           drivers = await response.json();

           state.drivers = drivers.data;
           renderDriverList();
         } catch (error) {
           console.error('Error fetching drivers:', error);
           showError('Failed to load drivers. Please try again.');
         }
       }

       async function fetchUsers() {
         try {
           const response = await fetch('/admin/all/passengers/options?active=1&is_delete=0');
           if (!response.ok) throw new Error('Failed to fetch users');

           users = await response.json();

           state.users = users.data;
           renderUserList();
         } catch (error) {
           console.error('Error fetching users:', error);
           showError('Failed to load users. Please try again.');
         }
       }

       async function fetchDriverAudiences() {
         try {
           const response = await fetch('/admin/getaudiences');
           if (!response.ok) throw new Error('Failed to fetch driver audiences');

           const data = await response.json();
           state.driverAudiences = data.driversAudience.filter(audience => !audience.is_delete);
         } catch (error) {
           console.error('Error fetching driver audiences:', error);
         }
       }

       async function fetchUserAudiences() {
         try {
           const response = await fetch('/admin/getaudiences');
           if (!response.ok) throw new Error('Failed to fetch user audiences');

           const data = await response.json();
           state.userAudiences = data.userAudience.filter(audience => !audience.is_delete);
         } catch (error) {
           console.error('Error fetching user audiences:', error);
         }
       }

       function renderDriverList() {
         elements.driverList.innerHTML = '';

         if (state.drivers.length === 0) {
           elements.driverList.innerHTML = '<li class="dropdown-item">No drivers found</li>';
           return;
         }

         state.drivers.forEach(driver => {
           const li = document.createElement('li');
           li.className = 'dropdown-item';
           li.innerHTML = `
          <input type="checkbox" id="driver-${driver.driver_id}" class="form-check-input" value="${driver.driver_id}" 
            ${state.selectedDrivers.includes(driver.driver_id) ? 'checked' : ''}>
          <label for="driver-${driver.driver_id}">
            ${driver.d_name} (${driver.d_phone})
          </label>
        `;

           li.querySelector('input').addEventListener('change', function() {
             if (this.checked) {
               if (!state.selectedDrivers.includes(this.value)) {
                 state.selectedDrivers.push(this.value);
               }
             } else {
               state.selectedDrivers = state.selectedDrivers.filter(id => id !== this.value);
             }
             updateSelectedCount('driver');
           });

           elements.driverList.appendChild(li);
         });

         updateSelectedCount('driver');
       }

       function renderUserList() {
         elements.userList.innerHTML = '';

         if (state.users.length === 0) {
           elements.userList.innerHTML = '<li class="dropdown-item">No users found</li>';
           return;
         }

         state.users.forEach(user => {
           const li = document.createElement('li');
           li.className = 'dropdown-item';
           li.innerHTML = `
          <input type="checkbox" id="user-${user.user_id}" class="form-check-input" value="${user.user_id}" 
            ${state.selectedUsers.includes(user.user_id) ? 'checked' : ''}>
          <label for="user-${user.user_id}">
            ${user.u_name} (${user.u_phone})
          </label>
        `;

           li.querySelector('input').addEventListener('change', function() {
             if (this.checked) {
               if (!state.selectedUsers.includes(this.value)) {
                 state.selectedUsers.push(this.value);
               }
             } else {
               state.selectedUsers = state.selectedUsers.filter(id => id !== this.value);
             }
             updateSelectedCount('user');
           });

           elements.userList.appendChild(li);
         });

         updateSelectedCount('user');
       }

       function selectAll(type) {
         const listItems = type === 'driver' ? state.drivers : state.users;
         const selectedItems = type === 'driver' ? state.selectedDrivers : state.selectedUsers;

         // Check if all items are already selected
         const allSelected = listItems.every(item =>
           selectedItems.includes(type === 'driver' ? item.driver_id : item.user_id)
         );

         if (allSelected) {
           // Deselect all
           if (type === 'driver') {
             state.selectedDrivers = [];
           } else {
             state.selectedUsers = [];
           }
         } else {
           // Select all
           if (type === 'driver') {
             state.selectedDrivers = listItems.map(driver => driver.driver_id);
           } else {
             state.selectedUsers = listItems.map(user => user.user_id);
           }
         }

         // Re-render the appropriate list
         if (type === 'driver') {
           renderDriverList();
         } else {
           renderUserList();
         }
       }
       if (preselectedAudienceId) {
         // Set selection to "audience"
         const audienceRadio = document.querySelector('input[name="selection"][value="audience"]');
         if (audienceRadio) audienceRadio.checked = true;
         toggleSelectionType('audience');
       }


       function updateAudienceSelect(audienceType) {
         elements.audienceSelect.innerHTML = '<option value="">Select an audience...</option>';

         const audiences = audienceType === 'driver' ? state.driverAudiences : state.userAudiences;

         audiences.forEach(audience => {
           const option = document.createElement('option');
           option.value = audience.audience_id;
           option.textContent = audience.title;
           elements.audienceSelect.appendChild(option);
         });

         // After populating, check if we need to preselect
         if (preselectedAudienceId) {
           const matchedAudience = audiences.find(a => String(a.audience_id) === preselectedAudienceId);
           if (matchedAudience) {
             elements.audienceSelect.value = preselectedAudienceId;
           }
         }
       }

       function filterList(searchTerm, type) {
         const list = type === 'driver' ? elements.driverList : elements.userList;
         const items = list.querySelectorAll('.dropdown-item');

         searchTerm = searchTerm.toLowerCase();

         items.forEach(item => {
           const text = item.textContent.toLowerCase();
           item.style.display = text.includes(searchTerm) ? 'flex' : 'none';
         });
       }

       function updateSelectedCount(type) {
         const count = type === 'driver' ? state.selectedDrivers.length : state.selectedUsers.length;
         const buttonText = type === 'driver' ? elements.driverButtonText : elements.userButtonText;

         buttonText.textContent = count > 0 ? `${count} selected` : `Select ${type}`;
       }
       const formValidator = setupFormValidation(
         formConfig.formId,
         formConfig.fields
       );


       async function sendNotification() {

         // Validate form
         if (!formValidator.validateForm()) {
           console.log('Form validation failed');
           return false;
         }
         // Validate form
         const title = document.getElementById('notification-title').value.trim();
         const message = document.getElementById('notification-message').value.trim();

         if (!title || !message) {
           showError('Title and message are required');
           return;
         }

         // Prepare notification data
         const audienceType = document.querySelector('input[name="audience"]:checked').value;
         const selectionType = document.querySelector('input[name="selection"]:checked').value;
         const notificationType = document.querySelector('input[name="type"]:checked').value;
         const url = document.querySelector('input[name="notificationUrl"]').value.trim();

         const notificationData = {
           userType: audienceType === 'driver' ? 'Drivers' : 'Users',
           Notification: {
             title,
             message,
             url: url || undefined,
             notifType: notificationType
           },
           selectionType,
           message,
           url: url || undefined,
           notifType: notificationType
         };

         // Add recipients based on selection type
         if (selectionType === 'manual') {
           if (audienceType === 'driver') {
             if (state.selectedDrivers.length === 0) {
               showError('Please select at least one driver');
               return;
             }
             notificationData.default_drivers = state.selectedDrivers;
           } else {
             if (state.selectedUsers.length === 0) {
               showError('Please select at least one user');
               return;
             }
             notificationData.default_users = state.selectedUsers;
           }
         } else {
           const audienceId = elements.audienceSelect.value;
           if (!audienceId) {
             showError('Please select an audience');
             return;
           }
           notificationData.users = audienceId;
         }

         ;

         try {
           const response = await fetch('/admin/notifications/send', {
             method: 'POST',
             headers: {
               'Content-Type': 'application/json'
             },
             body: JSON.stringify(notificationData)
           });

           const data = await response.json();

           if (response.ok) {
             showSuccess(data.message || 'Notification sent successfully');

             // Reset form if not broadcast
             if (notificationType !== 'broadcast') {
               elements.notificationForm.reset();
               state.selectedDrivers = [];
               state.selectedUsers = [];
               renderDriverList();
               renderUserList();
             }
           } else {
             showError(data.message || data.error || 'Failed to send notification');
           }
         } catch (error) {
           console.error('Error sending notification:', error);
           showError('An error occurred while sending the notification');
         } finally {

         }
       }

       function showError(message) {
         Swal.fire({
           icon: 'error',
           title: 'Error',
           text: message,
           confirmButtonText: 'OK'
         });
       }

       function showSuccess(message) {
         Swal.fire({
           icon: 'success',
           title: 'Success',
           text: message,
           confirmButtonText: 'OK'
         });
       }
     });
   </script>

   <%- footer %>