document.addEventListener('DOMContentLoaded', function() {
    loadClients();
    
    document.getElementById('clientForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveClient();
    });
    
    document.getElementById('clearForm').addEventListener('click', function() {
        clearForm();
    });
});

function loadClients() {
    fetch('/admin/clients')
        .then(response => response.json())
        .then(clients => {
            const tbody = document.querySelector('#clientsTable tbody');
            tbody.innerHTML = '';
            
            clients.forEach(client => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${client.clientId}</td>
                    <td>${client.name}</td>
                    <td>${client.collection}</td>
                    <td><span class="${client.active ? 'status-active' : 'status-inactive'}">${client.active ? 'Active' : 'Inactive'}</span></td>
                    <td>
                        <button onclick="editClient('${client.clientId}')">Edit</button>
                        <button class="danger" onclick="deleteClient('${client.clientId}')">Delete</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        })
        .catch(error => {
            showMessage('Error loading clients: ' + error.message, 'error');
        });
}

function saveClient() {
    const form = document.getElementById('clientForm');
    const formData = new FormData(form);
    
    const client = {
        clientId: formData.get('clientId'),
        name: formData.get('name'),
        collection: formData.get('collection'),
        active: formData.has('active')
    };
    
    fetch('/admin/clients', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(client)
    })
    .then(response => response.text())
    .then(message => {
        showMessage(message, 'success');
        clearForm();
        loadClients();
    })
    .catch(error => {
        showMessage('Error saving client: ' + error.message, 'error');
    });
}

function editClient(clientId) {
    fetch(`/admin/clients/${clientId}`)
        .then(response => response.json())
        .then(client => {
            document.getElementById('clientId').value = client.clientId;
            document.getElementById('name').value = client.name;
            document.getElementById('collection').value = client.collection;
            document.getElementById('active').checked = client.active;
        })
        .catch(error => {
            showMessage('Error loading client: ' + error.message, 'error');
        });
}

function deleteClient(clientId) {
    if (confirm(`Are you sure you want to delete client ${clientId}?`)) {
        fetch(`/admin/clients/${clientId}`, {
            method: 'DELETE'
        })
        .then(response => response.text())
        .then(message => {
            showMessage(message, 'success');
            loadClients();
        })
        .catch(error => {
            showMessage('Error deleting client: ' + error.message, 'error');
        });
    }
}

function clearForm() {
    document.getElementById('clientForm').reset();
    document.getElementById('active').checked = true;
}

function showMessage(message, type) {
    const existingMessage = document.querySelector('.message');
    if (existingMessage) {
        existingMessage.remove();
    }
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    
    const container = document.querySelector('.container');
    container.insertBefore(messageDiv, container.firstChild);
    
    setTimeout(() => {
        messageDiv.remove();
    }, 5000);
}