const UI = {
    init() {
        this.initTables();
        this.initSearch();
        this.initSortable();
    },
    
    initTables() {
        document.querySelectorAll('.data-table').forEach(table => {
            const wrapper = document.createElement('div');
            wrapper.className = 'table-responsive';
            table.parentNode.insertBefore(wrapper, table);
            wrapper.appendChild(table);
        });
    },
    
    initSearch() {
        document.querySelectorAll('[data-search]').forEach(input => {
            const tableId = input.getAttribute('data-search');
            const table = document.getElementById(tableId);
            
            if (table) {
                input.addEventListener('input', debounce(function() {
                    const searchTerm = this.value.toLowerCase();
                    const rows = table.querySelectorAll('tbody tr');
                    
                    rows.forEach(row => {
                        const text = row.textContent.toLowerCase();
                        row.style.display = text.includes(searchTerm) ? '' : 'none';
                    });
                }, 300));
            }
        });
    },
    
    initSortable() {
        document.querySelectorAll('.data-table th[data-sort]').forEach(th => {
            th.style.cursor = 'pointer';
            th.addEventListener('click', function() {
                const table = this.closest('table');
                const tbody = table.querySelector('tbody');
                const rows = Array.from(tbody.querySelectorAll('tr'));
                const column = this.cellIndex;
                const isAsc = this.classList.contains('sort-asc');
                
                table.querySelectorAll('th').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
                this.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
                
                rows.sort((a, b) => {
                    const aVal = a.cells[column].textContent.trim();
                    const bVal = b.cells[column].textContent.trim();
                    
                    const aNum = parseFloat(aVal);
                    const bNum = parseFloat(bVal);
                    
                    if (!isNaN(aNum) && !isNaN(bNum)) {
                        return isAsc ? bNum - aNum : aNum - bNum;
                    }
                    
                    return isAsc ? bVal.localeCompare(aVal) : aVal.localeCompare(bVal);
                });
                
                rows.forEach(row => tbody.appendChild(row));
            });
        });
    },
    
    renderTable(containerId, data, columns, actions = null) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        if (data.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
                    </svg>
                    <h3>No data found</h3>
                    <p>There are no records to display.</p>
                </div>
            `;
            return;
        }
        
        let html = `
            <table class="data-table" id="${containerId}-table">
                <thead>
                    <tr>
                        ${columns.map(col => `<th data-sort="${col.key}">${col.label}</th>`).join('')}
                        ${actions ? '<th>Actions</th>' : ''}
                    </tr>
                </thead>
                <tbody>
        `;
        
        data.forEach(row => {
            html += '<tr>';
            columns.forEach(col => {
                let value = row[col.key];
                if (col.format) {
                    value = col.format(value, row);
                }
                html += `<td>${value || '-'}</td>`;
            });
            if (actions) {
                html += `<td class="action-buttons">${actions(row)}</td>`;
            }
            html += '</tr>';
        });
        
        html += '</tbody></table>';
        container.innerHTML = html;
        
        this.initSortable();
    },
    
    updateStats(stats) {
        Object.keys(stats).forEach(key => {
            const element = document.querySelector(`[data-stat="${key}"]`);
            if (element) {
                this.animateNumber(element, stats[key]);
            }
        });
    },
    
    animateNumber(element, target) {
        const start = parseInt(element.textContent) || 0;
        const duration = 1000;
        const startTime = performance.now();
        
        const animate = (currentTime) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const easing = 1 - Math.pow(1 - progress, 3);
            
            const current = Math.floor(start + (target - start) * easing);
            element.textContent = current.toLocaleString();
            
            if (progress < 1) {
                requestAnimationFrame(animate);
            }
        };
        
        requestAnimationFrame(animate);
    },
    
    showEmptyState(containerId, message = 'No data found', icon = null) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        container.innerHTML = `
            <div class="empty-state">
                ${icon || `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>`}
                <h3>${message}</h3>
            </div>
        `;
    },
    
    formatBadge(status) {
        const statusMap = {
            'active': 'success',
            'inactive': 'danger',
            'pending': 'warning',
            'sent': 'success',
            'completed': 'success',
            'overdue': 'danger',
        };
        
        const type = statusMap[status.toLowerCase()] || 'info';
        return `<span class="badge badge-${type}">${status}</span>`;
    },
};

document.addEventListener('DOMContentLoaded', () => UI.init());

function applyServiceTableLabels() {
  const table = document.querySelector(".service-table");
  if (!table) return;

  const headers = Array.from(
    table.querySelectorAll("thead th")
  ).map(th => th.innerText.trim());

  table.querySelectorAll("tbody tr").forEach(row => {
    row.querySelectorAll("td").forEach((td, index) => {
      if (!td.dataset.label) {
        td.dataset.label = headers[index] || "";
      }
    });
  });
}

document.addEventListener("DOMContentLoaded", applyServiceTableLabels);

/* ===============================
   MOBILE SIDEBAR FIX – COMPANY & STAFF
   =============================== */
document.addEventListener('DOMContentLoaded', function () {

  const menuToggle = document.querySelector('.menu-toggle');
  const sidebar = document.querySelector('.sidebar');
  const overlay = document.querySelector('.sidebar-overlay');

  // Safety check
  if (!menuToggle || !sidebar) {
    console.warn('Menu toggle or sidebar not found');
    return;
  }

  // Hamburger click
  menuToggle.addEventListener('click', function (e) {
    e.preventDefault();
    e.stopPropagation();

    sidebar.classList.toggle('open');

    if (overlay) {
      overlay.classList.toggle('active');
    }
  });

  // Close sidebar when clicking overlay
  if (overlay) {
    overlay.addEventListener('click', function () {
      sidebar.classList.remove('open');
      overlay.classList.remove('active');
    });
  }

});

