
    // ===== 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 Renewal Data =====
    const renewals = [
      {
        id: 'REN-2024-001',
        customerId: 'CUS-001',
        name: 'Ahmed Raza',
        company: 'Tech Solutions Ltd',
        plan: 'Premium Website',
        renewalDate: '2024-04-15',
        amount: 'PKR 15,000',
        paymentMethod: 'Bank Transfer',
        status: 'completed',
        email: 'ahmed@techsolutions.com'
      },
      {
        id: 'REN-2024-002',
        customerId: 'CUS-002',
        name: 'Sana Khan',
        company: 'Digital Marketing Pro',
        plan: 'Business Software',
        renewalDate: '2024-04-20',
        amount: 'PKR 45,000',
        paymentMethod: 'Credit Card',
        status: 'pending',
        email: 'sana@dmp.com'
      },
      {
        id: 'REN-2024-003',
        customerId: 'CUS-003',
        name: 'Bilal Ahmed',
        company: 'Startup Innovations',
        plan: 'Basic Website',
        renewalDate: '2024-03-01',
        amount: 'PKR 120,000',
        paymentMethod: 'Bank Transfer',
        status: 'expired',
        email: 'bilal@startup.com'
      },
      {
        id: 'REN-2024-004',
        customerId: 'CUS-004',
        name: 'Hira Malik',
        company: 'E-commerce Store',
        plan: 'E-commerce Package',
        renewalDate: '2024-05-05',
        amount: 'PKR 25,000',
        paymentMethod: 'Credit Card',
        status: 'upcoming',
        email: 'hira@estore.com'
      },
      {
        id: 'REN-2024-005',
        customerId: 'CUS-005',
        name: 'Usman Ali',
        company: 'Consulting Firm',
        plan: 'Enterprise Software',
        renewalDate: '2024-03-10',
        amount: 'PKR 60,000',
        paymentMethod: 'Bank Transfer',
        status: 'cancelled',
        email: 'usman@consulting.com'
      },
      {
        id: 'REN-2024-006',
        customerId: 'CUS-006',
        name: 'Fatima Noor',
        company: 'Creative Agency',
        plan: 'Professional Hosting',
        renewalDate: '2024-04-25',
        amount: 'PKR 18,000',
        paymentMethod: 'Credit Card',
        status: 'completed',
        email: 'fatima@creative.com'
      },
      {
        id: 'REN-2024-007',
        customerId: 'CUS-007',
        name: 'Kamran Butt',
        company: 'Manufacturing Corp',
        plan: 'Custom Software',
        renewalDate: '2024-06-20',
        amount: 'PKR 200,000',
        paymentMethod: 'Bank Transfer',
        status: 'upcoming',
        email: 'kamran@manufacturing.com'
      },
      {
        id: 'REN-2024-008',
        customerId: 'CUS-008',
        name: 'Ayesha Siddiqui',
        company: 'Healthcare Solutions',
        plan: 'Medical Website',
        renewalDate: '2024-04-01',
        amount: 'PKR 22,000',
        paymentMethod: 'Credit Card',
        status: 'completed',
        email: 'ayesha@healthcare.com'
      },
      {
        id: 'REN-2024-009',
        customerId: 'CUS-009',
        name: 'Zain Abid',
        company: 'Real Estate Partners',
        plan: 'Domain & Hosting',
        renewalDate: '2024-05-15',
        amount: 'PKR 30,000',
        paymentMethod: 'Bank Transfer',
        status: 'pending',
        email: 'zain@realestate.com'
      },
      {
        id: 'REN-2024-010',
        customerId: 'CUS-010',
        name: 'Nadia Shah',
        company: 'Education First',
        plan: 'Education Package',
        renewalDate: '2024-04-18',
        amount: 'PKR 28,000',
        paymentMethod: 'Credit Card',
        status: 'completed',
        email: 'nadia@education.com'
      }
    ];

    // ===== Populate Renewals Table =====
    function populateRenewalsTable(filteredRenewals = renewals) {
      const tableBody = document.getElementById('renewalsTable');
      tableBody.innerHTML = '';
      
      filteredRenewals.forEach(renewal => {
        const row = document.createElement('tr');
        
        // Get initials for avatar
        const initials = renewal.name.split(' ').map(n => n[0]).join('').toUpperCase();
        
        // Format renewal date
        const renewalDate = new Date(renewal.renewalDate).toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'short',
          day: 'numeric'
        });
        
        row.innerHTML = `
          <td>
            <div style="font-weight: 600; color: var(--primary);">${renewal.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;">${renewal.name}</div>
                <div style="font-size: 12px; color: var(--muted);">${renewal.email}</div>
              </div>
            </div>
          </td>
          <td>${renewal.plan}</td>
          <td>${renewalDate}</td>
          <td>
            <div style="font-weight: 600;">${renewal.amount}</div>
          </td>
          <td>
            <div style="display: flex; align-items: center; gap: 6px;">
              <i class="fa-solid fa-credit-card" style="color: var(--muted); font-size: 12px;"></i>
              <span>${renewal.paymentMethod}</span>
            </div>
          </td>
          <td>
            <span class="status ${renewal.status}">${renewal.status.charAt(0).toUpperCase() + renewal.status.slice(1)}</span>
          </td>
          <td>
            <div class="action-buttons">
              <button class="action-btn view" title="View Details" data-id="${renewal.id}">
                <i class="fa-solid fa-eye"></i>
              </button>
              <button class="action-btn edit" title="Edit Renewal" data-id="${renewal.id}">
                <i class="fa-solid fa-pen"></i>
              </button>
              ${renewal.status === 'pending' ? `
                <button class="action-btn renew" title="Process Renewal" data-id="${renewal.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('#renewalsTable 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 planFilter = document.getElementById('planFilter').value;
      
      let filteredRenewals = renewals;
      
      // Apply status filter
      if (statusFilter) {
        filteredRenewals = filteredRenewals.filter(renewal => renewal.status === statusFilter);
      }
      
      // Apply plan filter
      if (planFilter) {
        filteredRenewals = filteredRenewals.filter(renewal => 
          renewal.plan.toLowerCase().includes(planFilter.toLowerCase())
        );
      }
      
      // Apply date filter (simplified for demo)
      if (dateFilter) {
        const today = new Date();
        filteredRenewals = filteredRenewals.filter(renewal => {
          const renewalDate = new Date(renewal.renewalDate);
          // This is a simplified date filtering for demo purposes
          return true; // In real app, implement proper date filtering
        });
      }
      
      populateRenewalsTable(filteredRenewals);
      document.querySelector('.pagination-info').textContent = `Showing 1-${filteredRenewals.length} of ${filteredRenewals.length} renewals`;
    });

    // ===== Clear Filters =====
    document.getElementById('clearFilters').addEventListener('click', function() {
      document.getElementById('statusFilter').value = '';
      document.getElementById('dateFilter').value = '';
      document.getElementById('planFilter').value = '';
      document.getElementById('tableSearch').value = '';
      populateRenewalsTable();
      document.querySelector('.pagination-info').textContent = 'Showing 1-10 of 428 renewals';
    });

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

    // ===== Action Button Handlers =====
    document.addEventListener('click', function(e) {
      if (e.target.closest('.action-btn.view')) {
        const renewalId = e.target.closest('.action-btn').getAttribute('data-id');
        alert(`View renewal details for ID: ${renewalId}`);
      }
      
      if (e.target.closest('.action-btn.edit')) {
        const renewalId = e.target.closest('.action-btn').getAttribute('data-id');
        alert(`Edit renewal for ID: ${renewalId}`);
      }
      
      if (e.target.closest('.action-btn.renew')) {
        const renewalId = e.target.closest('.action-btn').getAttribute('data-id');
        if (confirm('Are you sure you want to process this renewal?')) {
          alert(`Renewal processed for ID: ${renewalId}`);
          // In a real application, you would update the renewal 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 = 'renewallist.html';
      document.querySelectorAll('.nav a').forEach(link => {
        if (link.getAttribute('href') === currentPage) {
          link.classList.add('active');
        }
      });
      
      // Populate the renewals table
      populateRenewalsTable();
    });
