
    // ===== 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 Report Data =====
    const reportData = [
      {
        id: 'CUS-001',
        name: 'Ahmed Raza',
        company: 'Tech Solutions Ltd',
        plan: 'Enterprise',
        joinDate: '2023-05-15',
        renewalDate: '2024-05-15',
        status: 'active',
        revenue: 'PKR 45,000',
        email: 'ahmed@techsolutions.com'
      },
      {
        id: 'CUS-002',
        name: 'Sana Khan',
        company: 'Digital Marketing Pro',
        plan: 'Business',
        joinDate: '2023-08-22',
        renewalDate: '2024-08-22',
        status: 'active',
        revenue: 'PKR 25,000',
        email: 'sana@dmp.com'
      },
      {
        id: 'CUS-003',
        name: 'Bilal Ahmed',
        company: 'Startup Innovations',
        plan: 'Startup',
        joinDate: '2024-01-10',
        renewalDate: '2024-07-10',
        status: 'active',
        revenue: 'PKR 15,000',
        email: 'bilal@startup.com'
      },
      {
        id: 'CUS-004',
        name: 'Hira Malik',
        company: 'E-commerce Store',
        plan: 'Business',
        joinDate: '2023-11-05',
        renewalDate: '2024-11-05',
        status: 'active',
        revenue: 'PKR 22,500',
        email: 'hira@estore.com'
      },
      {
        id: 'CUS-005',
        name: 'Usman Ali',
        company: 'Consulting Firm',
        plan: 'Enterprise',
        joinDate: '2022-09-18',
        renewalDate: '2024-09-18',
        status: 'active',
        revenue: 'PKR 52,000',
        email: 'usman@consulting.com'
      },
      {
        id: 'CUS-006',
        name: 'Fatima Noor',
        company: 'Creative Agency',
        plan: 'Business',
        joinDate: '2023-12-12',
        renewalDate: '2024-12-12',
        status: 'active',
        revenue: 'PKR 28,000',
        email: 'fatima@creative.com'
      },
      {
        id: 'CUS-007',
        name: 'Kamran Butt',
        company: 'Manufacturing Corp',
        plan: 'Enterprise',
        joinDate: '2023-03-30',
        renewalDate: '2024-03-30',
        status: 'active',
        revenue: 'PKR 65,000',
        email: 'kamran@manufacturing.com'
      },
      {
        id: 'CUS-008',
        name: 'Ayesha Siddiqui',
        company: 'Healthcare Solutions',
        plan: 'Business',
        joinDate: '2024-02-14',
        renewalDate: '2024-08-14',
        status: 'active',
        revenue: 'PKR 24,500',
        email: 'ayesha@healthcare.com'
      },
      {
        id: 'CUS-009',
        name: 'Zain Abid',
        company: 'Real Estate Partners',
        plan: 'Enterprise',
        joinDate: '2022-11-20',
        renewalDate: '2024-11-20',
        status: 'active',
        revenue: 'PKR 48,000',
        email: 'zain@realestate.com'
      },
      {
        id: 'CUS-010',
        name: 'Nadia Shah',
        company: 'Education First',
        plan: 'Individual',
        joinDate: '2024-03-05',
        renewalDate: '2024-09-05',
        status: 'active',
        revenue: 'PKR 8,500',
        email: 'nadia@education.com'
      }
    ];

    // ===== Populate Report Table =====
    function populateReportTable(filteredData = reportData) {
      const tableBody = document.getElementById('reportTable');
      tableBody.innerHTML = '';
      
      filteredData.forEach(item => {
        const row = document.createElement('tr');
        
        // Get initials for avatar
        const initials = item.name.split(' ').map(n => n[0]).join('').toUpperCase();
        
        // Format dates
        const joinDate = new Date(item.joinDate).toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'short',
          day: 'numeric'
        });
        
        const renewalDate = new Date(item.renewalDate).toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'short',
          day: 'numeric'
        });
        
        row.innerHTML = `
          <td>
            <div style="font-weight: 600; color: var(--primary);">${item.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;">${item.name}</div>
                <div style="font-size: 12px; color: var(--muted);">${item.company}</div>
              </div>
            </div>
          </td>
          <td>${item.plan}</td>
          <td>${joinDate}</td>
          <td>${renewalDate}</td>
          <td>
            <span class="status active">Active</span>
          </td>
          <td>
            <div style="font-weight: 600;">${item.revenue}</div>
            <div style="font-size: 12px; color: var(--muted);">Monthly</div>
          </td>
          <td>
            <div class="action-buttons">
              <button class="action-btn view" title="View Details" data-id="${item.id}">
                <i class="fa-solid fa-eye"></i>
              </button>
              <button class="action-btn remind" title="Send Report" data-id="${item.id}">
                <i class="fa-solid fa-paper-plane"></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('#reportTable tr');
      
      rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchTerm) ? '' : 'none';
      });
    });

    // ===== Filter Functionality =====
    document.getElementById('generateReport').addEventListener('click', function() {
      const dateRange = document.getElementById('dateRange').value;
      const reportType = document.getElementById('reportType').value;
      const customerSegment = document.getElementById('customerSegment').value;
      
      let filteredData = reportData;
      
      // Apply customer segment filter
      if (customerSegment !== 'all') {
        filteredData = filteredData.filter(item => {
          if (customerSegment === 'enterprise') return item.plan === 'Enterprise';
          if (customerSegment === 'small-business') return item.plan === 'Business';
          if (customerSegment === 'startup') return item.plan === 'Startup';
          if (customerSegment === 'individual') return item.plan === 'Individual';
          return true;
        });
      }
      
      populateReportTable(filteredData);
      document.querySelector('.pagination-info').textContent = `Showing 1-${filteredData.length} of ${filteredData.length} customers`;
    });

    // ===== Clear Filters =====
    document.getElementById('clearFilters').addEventListener('click', function() {
      document.getElementById('dateRange').value = '90days';
      document.getElementById('reportType').value = 'overview';
      document.getElementById('customerSegment').value = 'all';
      document.getElementById('tableSearch').value = '';
      populateReportTable();
      document.querySelector('.pagination-info').textContent = 'Showing 1-10 of 1,248 customers';
    });

    // ===== Export Functionality =====
    document.getElementById('exportReport').addEventListener('click', function() {
      alert('Exporting general 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 itemId = e.target.closest('.action-btn').getAttribute('data-id');
        alert(`View customer details for ID: ${itemId}`);
      }
      
      if (e.target.closest('.action-btn.remind')) {
        const itemId = e.target.closest('.action-btn').getAttribute('data-id');
        alert(`Report sent to customer with ID: ${itemId}`);
      }
    });

    // ===== 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 = 'reports.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 report table
      populateReportTable();
    });
