<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sessioni — Console MEB</title>
    <link rel="stylesheet" href="/static/style/style.css">
    <style>
        main { padding: 24px 30px; }
        main h2 { font-size: 1.1rem; margin-bottom: 20px; color: var(--text-secondary); font-weight: 500; }
        .session-card {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 20px;
            border: 1px solid var(--header-border);
            border-radius: var(--radius-lg);
            margin-bottom: 12px;
        }
        .session-card .info h3 { font-size: 0.95rem; margin-bottom: 4px; }
        .session-card .info p { font-size: 0.8rem; color: var(--text-secondary); margin: 2px 0; }
        .session-card button { font-size: 0.8rem; padding: 6px 14px; color: #dc2626; border-color: #fca5a5; }
        .session-card button:hover { background-color: #fef2f2; border-color: #dc2626; color: #dc2626; }
        #loading { color: var(--text-tertiary); font-size: 0.9rem; }
    </style>
</head>

<body>
    <div class="header">
        <h1>Console MEB</h1>
        <div class="profile">
            <p>{{ user.username }}</p>
            <form action="/api/auth/logout" method="post">
                <button type="submit">Logout</button>
            </form>
        </div>
    </div>

    <main>
        <h2>Sessioni attive</h2>
        <div id="sessions-container">
            <p id="loading">Caricamento...</p>
        </div>
    </main>

    <script>
        function escapeHtml(str) {
            const d = document.createElement('div');
            d.appendChild(document.createTextNode(str || ''));
            return d.innerHTML;
        }

        function formatDate(iso) {
            if (!iso) return 'N/D';
            return new Date(iso).toLocaleString('it-IT', {
                day: 'numeric', month: 'short', year: 'numeric',
                hour: '2-digit', minute: '2-digit'
            });
        }

        async function loadSessions() {
            try {
                const res = await fetch('/api/sessions');
                if (res.status === 401) { window.location.href = '/login'; return; }
                if (!res.ok) throw new Error('Network error');

                const sessions = await res.json();
                const container = document.getElementById('sessions-container');

                if (sessions.length === 0) {
                    container.innerHTML = '<p style="color:var(--text-tertiary)">Nessuna sessione attiva.</p>';
                    return;
                }

                container.innerHTML = sessions.map(s => `
                    <div class="session-card" id="session-${escapeHtml(s.id)}">
                        <div class="info">
                            <h3>${escapeHtml(s.browser || 'Browser sconosciuto')} su ${escapeHtml(s.os || 'OS sconosciuto')}</h3>
                            <p>${escapeHtml(s.device_type || '')}${s.ip_address ? ' — ' + escapeHtml(s.ip_address) : ''}</p>
                            <p>Ultima attività: ${formatDate(s.last_active)}</p>
                        </div>
                        <button onclick="revokeSession('${escapeHtml(s.id)}')">Revoca</button>
                    </div>
                `).join('');
            } catch {
                document.getElementById('sessions-container').innerHTML =
                    '<p style="color:#dc2626">Errore nel caricamento delle sessioni.</p>';
            }
        }

        async function revokeSession(id) {
            if (!confirm('Revocare questa sessione?')) return;
            try {
                const res = await fetch('/api/sessions/' + encodeURIComponent(id), { method: 'DELETE' });
                if (res.status === 401) { window.location.href = '/login'; return; }
                if (!res.ok) throw new Error();
                const el = document.getElementById('session-' + id);
                if (el) el.remove();
            } catch {
                alert('Errore durante la revoca della sessione.');
            }
        }

        loadSessions();
    </script>
</body>

</html>
