let currentNetworkId = null;
let updateInterval = null;

async function setNetwork() {
    const networkId = document.getElementById('networkId').value.trim();
    
    if (!networkId) {
        showError('Inserisci un Network ID');
        return;
    }
    
    if (networkId.length !== 16) {
        showError('Il Network ID deve essere lungo 16 caratteri');
        return;
    }
    
    currentNetworkId = networkId;
    clearError();
    
    // Avvia il polling automatico
    if (updateInterval) {
        clearInterval(updateInterval);
    }
    
    // Primo aggiornamento immediato
    await updateNodes();
    
    // Poi ogni 5 secondi
    updateInterval = setInterval(updateNodes, 5000);
}

async function updateNodes() {
    if (!currentNetworkId) {
        return;
    }
    
    try {
        const response = await fetch(`/api/nodes?network_id=${currentNetworkId}`);
        
        if (!response.ok) {
            const error = await response.json();
            console.error('API Error:', error);
            updateStatusIndicator(false);
            showError(error.error || 'Errore nel caricamento dei nodi');
            return;
        }
        
        const data = await response.json();
        updateStatusIndicator(true);
        renderNodes(data);
        updateStats(data);
        clearError();
        
    } catch (error) {
        console.error('Fetch error:', error);
        updateStatusIndicator(false);
        showError('Errore di connessione al server');
    }
}

function updateStatusIndicator(isOnline) {
    const indicator = document.getElementById('status-indicator');
    if (isOnline) {
        indicator.classList.remove('offline');
        indicator.classList.add('online');
    } else {
        indicator.classList.remove('online');
        indicator.classList.add('offline');
    }
}

function showError(message) {
    let errorDiv = document.getElementById('error-message');
    if (!errorDiv) {
        errorDiv = document.createElement('div');
        errorDiv.id = 'error-message';
        errorDiv.className = 'error-banner';
        document.querySelector('.container').insertBefore(errorDiv, document.querySelector('header').nextSibling);
    }
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
}

function clearError() {
    const errorDiv = document.getElementById('error-message');
    if (errorDiv) {
        errorDiv.style.display = 'none';
    }
}

function updateStats(data) {
    document.getElementById('total-nodes').textContent = data.total_nodes || 0;
    document.getElementById('online-nodes').textContent = data.online_nodes || 0;
    
    const now = new Date();
    const timeString = now.toLocaleTimeString('it-IT');
    document.getElementById('last-update').textContent = timeString;
}

function renderNodes(data) {
    const container = document.getElementById('nodes-container');
    
    if (!data.nodes || data.nodes.length === 0) {
        container.innerHTML = '<p class="empty-state">Nessun nodo trovato</p>';
        return;
    }
    
    container.innerHTML = data.nodes.map(node => createNodeCard(node)).join('');
}

function createNodeCard(node) {
    const isOnline = node.online;
    const statusClass = isOnline ? 'online' : 'offline';
    const statusText = isOnline ? '🟢 Online' : '🔴 Offline';
    
    const lastCheck = new Date(node.last_check);
    const timeAgo = getTimeAgo(lastCheck);
    
    return `
        <div class="node-card ${statusClass}">
            <div class="node-header">
                <div class="node-hostname">${escapeHtml(node.hostname)}</div>
                <div class="node-status-badge ${statusClass}"></div>
            </div>
            
            <div class="node-info">
                <div class="node-info-label">IP ZeroTier</div>
                <div class="node-info-value">${escapeHtml(node.ip)}</div>
            </div>
            
            <div class="node-info">
                <div class="node-info-label">ID</div>
                <div class="node-info-value" style="font-size: 0.8em;">${escapeHtml(node.id)}</div>
            </div>
            
            <div class="node-status-text ${statusClass}">
                ${statusText}
            </div>
            
            <div class="node-timestamp">
                Verificato ${timeAgo}
            </div>
        </div>
    `;
}

function getTimeAgo(date) {
    const now = new Date();
    const seconds = Math.floor((now - date) / 1000);
    
    if (seconds < 60) return 'proprio ora';
    if (seconds < 120) return 'un minuto fa';
    
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m fa`;
    
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h fa`;
    
    const days = Math.floor(hours / 24);
    return `${days}d fa`;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Load network ID from localStorage if exists
document.addEventListener('DOMContentLoaded', () => {
    const networkIdInput = document.getElementById('networkId');
    const saved = localStorage.getItem('zerotier_network_id');
    if (saved) {
        networkIdInput.value = saved;
    }
    
    // Salva network ID nel localStorage quando cambia
    networkIdInput.addEventListener('change', (e) => {
        if (e.target.value) {
            localStorage.setItem('zerotier_network_id', e.target.value);
        }
    });
});
