
    // ===== Dynamic Header: Clock =====
    const clock = document.querySelector('#clock span');
    function pad(n) { return (n < 10 ? '0' : '') + n }
    function tick() {
      const d = new Date();
      const h = pad(d.getHours());
      const m = pad(d.getMinutes());
      clock.textContent = `${h}:${m}`;
    }
    setInterval(tick, 1000); tick();

    // ===== Sidebar: dropdowns =====
    const dropdownTriggers = [...document.querySelectorAll('[data-toggle="submenu"]')];
    dropdownTriggers.forEach(btn => {
      const item = btn.closest('.nav-item');
      const pane = item.querySelector('.submenu');
      btn.addEventListener('click', () => {
        const expanded = btn.getAttribute('aria-expanded') === 'true';
        btn.setAttribute('aria-expanded', String(!expanded));
        btn.classList.toggle('active', !expanded);
        pane.style.height = !expanded ? (pane.scrollHeight + 'px') : '0px';
        btn.querySelector('.chev').style.transform = !expanded ? 'rotate(180deg)' : 'rotate(0)';
      });
    });
    function closeSiblings(currentBtn) {
      dropdownTriggers.forEach(btn => {
        if (btn !== currentBtn) {
          const pane = btn.closest('.nav-item').querySelector('.submenu');
          btn.setAttribute('aria-expanded', 'false');
          btn.classList.remove('active');
          pane.style.height = '0px';
          btn.querySelector('.chev').style.transform = 'rotate(0)';
        }
      })
    }
    dropdownTriggers.forEach(btn => btn.addEventListener('click', () => closeSiblings(btn)));

    // ===== Sidebar: collapse & mobile toggle =====
    const app = document.getElementById('app');
    const sidebar = document.getElementById('sidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const collapseToggle = document.getElementById('collapseToggle');
    const closeSidebarMobile = document.getElementById('closeSidebarMobile');
    
    sidebarToggle.addEventListener('click', () => {
      if (window.matchMedia('(max-width: 860px)').matches) {
        sidebar.classList.toggle('open');
      } else {
        app.classList.toggle('collapsed');
      }
    });
    
    collapseToggle.addEventListener('click', () => {
      app.classList.toggle('collapsed');
    });
    
    closeSidebarMobile.addEventListener('click', () => {
      sidebar.classList.remove('open');
    });
    
    document.querySelector('.main').addEventListener('click', () => {
      if (window.matchMedia('(max-width: 860px)').matches) {
        sidebar.classList.remove('open');
      }
    });

    // ===== Keyboard shortcut for search focus =====
    const searchInput = document.querySelector('.header .search input');
    window.addEventListener('keydown', (e) => {
      if (e.key === '/' && document.activeElement !== searchInput) {
        e.preventDefault(); searchInput.focus();
      }
    });

    // ===== Set current year in footer =====
    document.getElementById('year').textContent = new Date().getFullYear();

    // ===== Sample Recovery Data =====
    const recoveryData = [
      {
        id: 'REC-2024-001',
        customerId: 'CUS-001',
        name: 'Ahmed Raza',
        company: 'Tech Solutions Ltd',
        agent: 'Agent 1',
        attemptDate: '2024-04-15',
        method: 'Phone Call',
        amount: 'PKR 15,000',
        status: 'recovered',
        email: 'ahmed@techsolutions.com'
      },
      {
        id: 'REC-2024-002',
        customerId: 'CUS-002',
        name: 'Sana Khan',
        company: 'Digital Marketing Pro',
        agent: 'Agent 2',
        attemptDate: '2024-04-20',
        method: 'Email Campaign',
        amount: 'PKR 45,000',
        status: 'in-progress',
        email: 'sana@dmp.com'
      },
      {
        id: 'REC-2024-003',
        customerId: 'CUS-003',
        name: 'Bilal Ahmed',
        company: 'Startup Innovations',
        agent: 'Agent 1',
        attemptDate: '2024-03-01',
        method: 'Special Offer',
        amount: 'PKR 120,000',
        status: 'failed',
        email: 'bilal@startup.com'
      },
      {
        id: 'REC-2024-004',
        customerId: 'CUS-004',
        name: 'Hira Malik',
        company: 'E-commerce Store',
        agent: 'Agent 3',
        attemptDate: '2024-05-05',
        method: 'Phone Call',
        amount: 'PKR 25,000',
        status: 'recovered',
        email: 'hira@estore.com'
      },
      {
        id: 'REC-2024-005',
        customerId: 'CUS-005',
        name: 'Usman Ali',
        company: 'Consulting Firm',
        agent: 'Agent 2',
        attemptDate: '2024-03-10',
        method: 'Email Campaign',
        amount: 'PKR 60,000',
        status: 'pending',
        email: 'usman@consulting.com'
      },
      {
        id: 'REC-2024-006',
        customerId: 'CUS-006',
        name: 'Fatima Noor',
        company: 'Creative Agency',
        agent: 'Agent 1',
        attemptDate: '2024-04-25',
        method: 'Special Offer',
        amount: 'PKR 18,000',
        status: 'recovered',
        email: 'fatima@creative.com'
      },
      {
        id: 'REC-2024-007',
        customerId: 'CUS-007',
        name: 'Kamran Butt',
        company: 'Manufacturing Corp',
        agent: 'Agent 3',
        attemptDate: '2024-06-20',
        method: 'Phone Call',
        amount: 'PKR 200,000',
        status: 'in-progress',
        email: 'kamran@manufacturing.com'
      },
      {
        id: 'REC-2024-008',
        customerId: 'CUS-008',
        name: 'Ayesha Siddiqui',
        company: 'Healthcare Solutions',
        agent: 'Agent 2',
        attemptDate: '2024-04-01',
        method: 'Email Campaign',
        amount: 'PKR 22,000',
        status: 'recovered',
        email: 'ayesha@healthcare.com'
      },
      {
        id: 'REC-2024-009',
        customerId: 'CUS-009',
        name: 'Zain Abid',
        company: 'Real Estate Partners',
        agent: 'Agent 1',
        attemptDate: '2024-05-15',
        method: 'Special Offer',
        amount: 'PKR 30,000',
        status: 'failed',
        email: 'zain@realestate.com'
      },
      {
        id: 'REC-2024-010',
        customerId: 'CUS-010',
        name: 'Nadia Shah',
        company: 'Education First',
        agent: 'Agent 3',
        attemptDate: '2024-04-18',
        method: 'Phone Call',
        amount: 'PKR 28,000',
        status: 'recovered',
        email: 'nadia@education.com'
      }
    ];

    // ===== Populate Recovery Table =====
    function populateRecoveryTable(filteredData = recoveryData) {
      const tableBody = document.getElementById('recoveryTable');
      tableBody.innerHTML = '';
      
      filteredData.forEach(recovery => {
        const row = document.createElement('tr');
        
        // Get initials for avatar
        const initials = recovery.name.split(' ').map(n => n[0]).join('').toUpperCase();
        
        // Format attempt date
        const attemptDate = new Date(recovery.attemptDate).toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'short',
          day: 'numeric'
        });
        
        row.innerHTML = `
          <td>
            <div style="font-weight: 600; color: var(--primary);">${recovery.id}</div>
          </td>
          <td>
            <div style="display: flex; align-items: center; gap: 12px;">
              <div class="customer-avatar">${initials}</div>
              <div>
                <div style="font-weight: 600;">${recovery.name}</div>
                <div style="font-size: 12px; color: var(--muted);">${recovery.email}</div>
              </div>
            </div>
          </td>
          <td>${recovery.agent}</td>
          <td>${attemptDate}</td>
          <td>${recovery.method}</td>
          <td>
            <div style="font-weight: 600;">${recovery.amount}</div>
          </td>
          <td>
            <span class="status ${recovery.status}">${recovery.status.charAt(0).toUpperCase() + recovery.status.slice(1).replace('-', ' ')}</span>
          </td>
          <td>
            <div class="action-buttons">
              <button class="action-btn view" title="View Details" data-id="${recovery.id}">
                <i class="fa-solid fa-eye"></i>
              </button>
              <button class="action-btn contact" title="Contact Customer" data-id="${recovery.id}">
                <i class="fa-solid fa-phone"></i>
              </button>
              ${recovery.status === 'failed' || recovery.status === 'pending' ? `
                <button class="action-btn retry" title="Retry Recovery" data-id="${recovery.id}">
                  <i class="fa-solid fa-rotate-right"></i>
                </button>
              ` : ''}
            </div>
          </td>
        `;
        
        tableBody.appendChild(row);
      });
    }

    // ===== Table Search Functionality =====
    document.getElementById('tableSearch').addEventListener('input', function(e) {
      const searchTerm = e.target.value.toLowerCase();
      const rows = document.querySelectorAll('#recoveryTable tr');
      
      rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchTerm) ? '' : 'none';
      });
    });

    // ===== Filter Functionality =====
    document.getElementById('applyFilters').addEventListener('click', function() {
      const statusFilter = document.getElementById('statusFilter').value;
      const dateFilter = document.getElementById('dateFilter').value;
      const agentFilter = document.getElementById('agentFilter').value;
      
      let filteredData = recoveryData;
      
      // Apply status filter
      if (statusFilter) {
        filteredData = filteredData.filter(recovery => recovery.status === statusFilter);
      }
      
      // Apply agent filter
      if (agentFilter) {
        filteredData = filteredData.filter(recovery => 
          recovery.agent.toLowerCase().includes(agentFilter.toLowerCase())
        );
      }
      
      // Apply date filter (simplified for demo)
      if (dateFilter) {
        // This is a simplified date filtering for demo purposes
        // In real app, implement proper date filtering based on the selected range
        filteredData = filteredData; // Keep all data for demo
      }
      
      populateRecoveryTable(filteredData);
      document.querySelector('.pagination-info').textContent = `Showing 1-${filteredData.length} of ${filteredData.length} recovery attempts`;
    });

    // ===== Clear Filters =====
    document.getElementById('clearFilters').addEventListener('click', function() {
      document.getElementById('statusFilter').value = '';
      document.getElementById('dateFilter').value = '';
      document.getElementById('agentFilter').value = '';
      document.getElementById('tableSearch').value = '';
      populateRecoveryTable();
      document.querySelector('.pagination-info').textContent = 'Showing 1-10 of 156 recovery attempts';
    });

    // ===== Export Functionality =====
    document.getElementById('exportReport').addEventListener('click', function() {
      alert('Exporting recovery report...');
      // In a real application, this would generate and download a CSV/PDF report
    });

    // ===== Print Functionality =====
    document.getElementById('printReport').addEventListener('click', function() {
      alert('Opening print dialog...');
      // In a real application, this would open the browser's print dialog
    });

    // ===== Action Button Handlers =====
    document.addEventListener('click', function(e) {
      if (e.target.closest('.action-btn.view')) {
        const recoveryId = e.target.closest('.action-btn').getAttribute('data-id');
        alert(`View recovery details for ID: ${recoveryId}`);
      }
      
      if (e.target.closest('.action-btn.contact')) {
        const recoveryId = e.target.closest('.action-btn').getAttribute('data-id');
        alert(`Contact customer for recovery ID: ${recoveryId}`);
      }
      
      if (e.target.closest('.action-btn.retry')) {
        const recoveryId = e.target.closest('.action-btn').getAttribute('data-id');
        if (confirm('Are you sure you want to retry this recovery attempt?')) {
          alert(`Recovery retry initiated for ID: ${recoveryId}`);
          // In a real application, you would update the recovery status
        }
      }
    });

    // ===== Pagination Controls =====
    document.querySelectorAll('.page-btn').forEach(btn => {
      btn.addEventListener('click', function() {
        if (!this.querySelector('i')) { // Don't change active state for arrow buttons
          document.querySelectorAll('.page-btn').forEach(b => b.classList.remove('active'));
          this.classList.add('active');
        }
      });
    });

    // ===== Initialize the page =====
    document.addEventListener('DOMContentLoaded', function() {
      // Set current page as active in sidebar
      const currentPage = 'recoveryreport.html';
      document.querySelectorAll('.nav a').forEach(link => {
        if (link.getAttribute('href') === currentPage) {
          link.classList.add('active');
          // If it's in a submenu, open the parent dropdown
          const parentItem = link.closest('.nav-item');
          if (parentItem) {
            const dropdownBtn = parentItem.querySelector('[data-toggle="submenu"]');
            if (dropdownBtn) {
              dropdownBtn.click(); // Open the dropdown
            }
          }
        }
      });
      
      // Populate the recovery table
      populateRecoveryTable();
    });
 