// WebSocket connection
let ws = null;
let reconnectTimeout = null;

// Connect to WebSocket
function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws`;
    
    ws = new WebSocket(wsUrl);
    
    ws.onopen = () => {
        console.log('WebSocket connected');
        document.getElementById('connection-status').classList.remove('disconnected');
    };
    
    ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.type === 'update') {
            updateDashboard(data);
        }
    };
    
    ws.onclose = () => {
        console.log('WebSocket disconnected');
        document.getElementById('connection-status').classList.add('disconnected');
        reconnectTimeout = setTimeout(connectWebSocket, 3000);
    };
    
    ws.onerror = (error) => {
        console.error('WebSocket error:', error);
    };
}

// Tab switching
document.querySelectorAll('.tab').forEach(tab => {
    tab.addEventListener('click', () => {
        const tabName = tab.dataset.tab;
        
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        
        tab.classList.add('active');
        document.getElementById(tabName).classList.add('active');
        
        if (tabName === 'config') {
            loadConfig();
        } else if (tabName === 'subscriptions') {
            loadSubscriptions();
        }
    });
});

// Update dashboard with WebSocket data
function updateDashboard(data) {
    if (data.status) {
        updateStatus(data.status);
    }
    if (data.graph) {
        updateGraph(data.graph);
    }
}

// Update status
function updateStatus(statusData) {
    const publishers = statusData.publishers;
    const totalPublishers = publishers.length;
    const activePublishers = publishers.filter(p => p.active).length;
    
    document.getElementById('total-publishers').textContent = totalPublishers;
    document.getElementById('active-publishers').textContent = activePublishers;
    
    const statusList = document.getElementById('status-list');
    statusList.innerHTML = '';
    
    publishers.forEach(pub => {
        const item = document.createElement('div');
        item.className = `status-item ${pub.active ? 'active' : 'inactive'}`;
        
        let dataTypesStr = '-';
        if (pub.data_types) {
            dataTypesStr = Object.entries(pub.data_types)
                .map(([k, v]) => `${k}:${v}`)
                .join(', ');
        }
        
        item.innerHTML = `
            <div class="status-info">
                <h3>${pub.name}</h3>
                <p><strong>Port:</strong> ${pub.host}:${pub.port}</p>
                <p><strong>Data Types:</strong> ${dataTypesStr}</p>
                ${pub.description ? `<p><strong>Description:</strong> ${pub.description}</p>` : ''}
            </div>
            <div>
                <span class="status-badge ${pub.active ? 'active' : 'inactive'}">
                    ${pub.active ? '✓ Active' : '✗ Inactive'}
                </span>
            </div>
        `;
        
        statusList.appendChild(item);
    });
    
    updatePublishersTable(publishers);
}

// Update graph visualization
function updateGraph(graphData) {
    const graphContainer = document.getElementById('graph-container');
    graphContainer.innerHTML = '';
    
    let totalSubs = 0;
    
    for (const [pubName, pubInfo] of Object.entries(graphData.graph)) {
        const node = document.createElement('div');
        node.className = 'graph-node';
        
        const subscribers = pubInfo.subscribers || [];
        totalSubs += subscribers.length;
        
        let subsHTML = '';
        if (subscribers.length > 0) {
            subsHTML = subscribers.map(sub => `
                <div class="graph-subscriber">
                    <span>${sub.name}</span>
                    <span style="color: #999;">@ ${sub.host}</span>
                </div>
            `).join('');
        } else {
            subsHTML = '<div class="no-subscribers">(no subscribers)</div>';
        }
        
        node.innerHTML = `
            <div class="graph-node-header">
                <span class="graph-node-title">📡 ${pubName}</span>
                <span class="graph-node-info">(${pubInfo.host}:${pubInfo.port})</span>
            </div>
            <div class="graph-subscribers">
                ${subsHTML}
            </div>
        `;
        
        graphContainer.appendChild(node);
    }
    
    document.getElementById('total-subscriptions').textContent = totalSubs;
}

// Update publishers table
function updatePublishersTable(publishers) {
    const tbody = document.getElementById('publishers-table');
    tbody.innerHTML = '';
    
    publishers.forEach(pub => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${pub.name}</td>
            <td>${pub.port}</td>
            <td>${pub.host}</td>
            <td>
                <span class="status-badge ${pub.active ? 'active' : 'inactive'}">
                    ${pub.active ? '✓' : '✗'}
                </span>
            </td>
            <td>${pub.description || '-'}</td>
            <td>
                <button class="btn btn-danger" onclick="deletePublisher('${pub.name}')">Delete</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Load subscriptions
async function loadSubscriptions() {
    try {
        const response = await fetch('/api/subscriptions');
        const data = await response.json();
        
        const tbody = document.getElementById('subscriptions-table');
        tbody.innerHTML = '';
        
        if (data.subscriptions.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #999;">No active subscriptions</td></tr>';
            return;
        }
        
        data.subscriptions.forEach(sub => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${sub.publisher_name}</td>
                <td>${sub.subscriber_name}</td>
                <td>${sub.subscriber_host}</td>
                <td>${sub.created_at}</td>
                <td>${sub.last_active}</td>
            `;
            tbody.appendChild(row);
        });
    } catch (error) {
        console.error('Failed to load subscriptions:', error);
    }
}

// Load config
async function loadConfig() {
    try {
        const response = await fetch('/api/config');
        const config = await response.json();
        
        document.getElementById('config-start').textContent = config.start_port;
        document.getElementById('config-end').textContent = config.end_port;
        document.getElementById('config-count').textContent = config.port_count;
        document.getElementById('config-used').textContent = config.used_ports;
        document.getElementById('config-available').textContent = config.available_ports;
        
        const portUsage = (config.used_ports / config.port_count * 100).toFixed(1);
        document.getElementById('port-usage').textContent = `${portUsage}%`;
        
        document.getElementById('new-start').value = config.start_port;
        document.getElementById('new-count').value = config.port_count;
    } catch (error) {
        console.error('Failed to load config:', error);
    }
}

// Show create publisher modal
function showCreatePublisher() {
    document.getElementById('create-publisher-form').classList.add('active');
}

// Hide create publisher modal
function hideCreatePublisher() {
    document.getElementById('create-publisher-form').classList.remove('active');
}

// Create publisher
async function createPublisher(event) {
    event.preventDefault();
    
    const name = document.getElementById('pub-name').value;
    const port = document.getElementById('pub-port').value;
    const description = document.getElementById('pub-desc').value;
    
    try {
        const response = await fetch('/api/publishers', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                name,
                port: port ? parseInt(port) : null,
                description
            })
        });
        
        if (response.ok) {
            alert('Publisher created successfully!');
            hideCreatePublisher();
            document.getElementById('pub-name').value = '';
            document.getElementById('pub-port').value = '';
            document.getElementById('pub-desc').value = '';
            
            setTimeout(() => location.reload(), 500);
        } else {
            const error = await response.json();
            alert(`Error: ${error.detail}`);
        }
    } catch (error) {
        alert(`Failed to create publisher: ${error.message}`);
    }
}

// Delete publisher
async function deletePublisher(name) {
    if (!confirm(`Are you sure you want to delete publisher "${name}"?`)) {
        return;
    }
    
    try {
        const response = await fetch(`/api/publishers/${name}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            alert('Publisher deleted successfully!');
            setTimeout(() => location.reload(), 500);
        } else {
            const error = await response.json();
            alert(`Error: ${error.detail}`);
        }
    } catch (error) {
        alert(`Failed to delete publisher: ${error.message}`);
    }
}

// Update config
async function updateConfig(event) {
    event.preventDefault();
    
    const start = parseInt(document.getElementById('new-start').value);
    const count = parseInt(document.getElementById('new-count').value);
    
    try {
        const response = await fetch('/api/config', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({start, count})
        });
        
        if (response.ok) {
            alert('Configuration updated successfully!');
            loadConfig();
        } else {
            const error = await response.json();
            alert(`Error: ${error.detail}`);
        }
    } catch (error) {
        alert(`Failed to update config: ${error.message}`);
    }
}

// Initialize
window.addEventListener('load', () => {
    connectWebSocket();
    loadConfig();
});
