{% extends "base.html" %}

{% block title %}Monitoring{% endblock %}

{% block extra_css %}
<style>
    /* Header Status Bar */
    .status-header {
        background: #f8f9fa;
        border-bottom: 2px solid #dee2e6;
        padding: 0.75rem;
        position: sticky;
        top: 0;
        z-index: 100;
        margin: -1rem -1rem 1rem -1rem;
    }
    
    .status-indicator {
        display: inline-flex;
        align-items: center;
        font-weight: 500;
    }
    
    .status-indicator .badge {
        margin-left: 0.5rem;
    }
    
    /* Metric Cards */
    .metric-card {
        background: white;
        border: 1px solid #dee2e6;
        border-radius: 0.5rem;
        padding: 1rem;
        position: relative;
        transition: all 0.2s;
    }
    
    .metric-card:hover {
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
    }
    
    .metric-value {
        font-size: 2rem;
        font-weight: bold;
        margin: 0.5rem 0;
    }
    
    .metric-label {
        color: #6c757d;
        font-size: 0.875rem;
        text-transform: uppercase;
    }
    
    .metric-trend {
        position: absolute;
        top: 1rem;
        right: 1rem;
        font-size: 0.875rem;
    }
    
    .metric-alert {
        position: absolute;
        top: -8px;
        right: -8px;
        width: 20px;
        height: 20px;
        background: #dc3545;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 0.75rem;
        font-weight: bold;
    }
    
    /* Activity Stream */
    .activity-stream {
        max-height: 500px;
        overflow-y: auto;
        border: 1px solid #dee2e6;
        border-radius: 0.5rem;
        background: white;
    }
    
    .activity-item {
        padding: 0.75rem;
        border-bottom: 1px solid #f8f9fa;
        transition: background 0.2s;
    }
    
    .activity-item:hover {
        background: #f8f9fa;
    }
    
    .activity-item.validation {
        border-left: 3px solid #28a745;
    }
    
    .activity-item.anomaly-warning {
        border-left: 3px solid #ffc107;
        background-color: #fff3cd;
    }
    
    .activity-item.anomaly-critical {
        border-left: 3px solid #dc3545;
        background-color: #f8d7da;
    }
    
    /* Statistics Panel */
    .stats-panel {
        background: white;
        border: 1px solid #dee2e6;
        border-radius: 0.5rem;
        padding: 1rem;
    }
    
    .license-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.5rem 0;
        border-bottom: 1px solid #f8f9fa;
    }
    
    .license-item:last-child {
        border-bottom: none;
    }
    
    /* Tabs */
    .analysis-tabs .nav-link {
        color: #495057;
        border: none;
        border-bottom: 2px solid transparent;
        padding: 0.5rem 1rem;
    }
    
    .analysis-tabs .nav-link.active {
        color: #0d6efd;
        border-bottom-color: #0d6efd;
        background: none;
    }
    
    /* Charts */
    .chart-container {
        height: 300px;
        position: relative;
    }
    
    /* Expandable sections */
    .expandable-section {
        border: 1px solid #dee2e6;
        border-radius: 0.5rem;
        margin-bottom: 1rem;
        overflow: hidden;
    }
    
    .expandable-header {
        background: #f8f9fa;
        padding: 0.75rem;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .expandable-header:hover {
        background: #e9ecef;
    }
    
    .expandable-content {
        padding: 1rem;
        display: none;
    }
    
    .expandable-content.show {
        display: block;
    }
    
    /* Auto-refresh indicator */
    .refresh-indicator {
        font-size: 0.875rem;
        color: #6c757d;
    }
    
    .refresh-indicator.active {
        color: #28a745;
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
        .metric-card {
            margin-bottom: 1rem;
        }
        
        .activity-stream {
            max-height: 300px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid p-3">
    <!-- Status Header -->
    <div class="status-header">
        <div class="d-flex justify-content-between align-items-center">
            <div class="status-indicator">
                {% if system_status == 'normal' %}
                    <span class="text-success">🟢 System Normal</span>
                {% elif system_status == 'warning' %}
                    <span class="text-warning">🟡 System Warning</span>
                {% else %}
                    <span class="text-danger">🔴 System Critical</span>
                {% endif %}
                <span class="badge bg-{{ status_color }}">{{ active_alerts }} Aktive Alerts</span>
            </div>
            <div class="d-flex align-items-center gap-3">
                <span class="text-muted">Letzte Aktualisierung: <span id="last-update">jetzt</span></span>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="auto-refresh" checked>
                    <label class="form-check-label" for="auto-refresh">Auto-Refresh</label>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Executive Summary (Collapsible) -->
    <div class="expandable-section" id="executive-summary">
        <div class="expandable-header" onclick="toggleSection('executive-summary')">
            <h5 class="mb-0">📊 Executive Summary</h5>
            <i class="bi bi-chevron-down"></i>
        </div>
        <div class="expandable-content show">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-label">Aktive Lizenzen</div>
                        <div class="metric-value text-primary">{{ live_metrics.active_licenses or 0 }}</div>
                        <div class="metric-trend text-success">
                            <i class="bi bi-arrow-up"></i> <span class="trend-value">0%</span>
                        </div>
                        {% if live_metrics.active_licenses > 100 %}
                        <div class="metric-alert">!</div>
                        {% endif %}
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-label">Validierungen (5 Min)</div>
                        <div class="metric-value text-info">{{ live_metrics.total_validations or 0 }}</div>
                        <div class="metric-trend text-muted">
                            <i class="bi bi-dash"></i> <span class="trend-value">0%</span>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-label">Aktive Geräte</div>
                        <div class="metric-value text-success">{{ live_metrics.unique_devices or 0 }}</div>
                        <div class="metric-trend text-success">
                            <i class="bi bi-arrow-up"></i> <span class="trend-value">0%</span>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-label">Response Zeit</div>
                        <div class="metric-value text-warning">{{ (live_metrics.avg_response_time or 0)|round(1) }}ms</div>
                        <div class="metric-trend text-warning">
                            <i class="bi bi-arrow-up"></i> <span class="trend-value">0%</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-12">
                    <canvas id="trend-chart" height="80"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Main Content Area -->
    <div class="row g-3">
        <!-- Activity Stream (Left Panel) -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">🔄 Activity Stream</h5>
                    <div class="btn-group btn-group-sm" role="group">
                        <button type="button" class="btn btn-outline-secondary active" data-filter="all">Alle</button>
                        <button type="button" class="btn btn-outline-success" data-filter="normal">Normal</button>
                        <button type="button" class="btn btn-outline-warning" data-filter="warning">Warnungen</button>
                        <button type="button" class="btn btn-outline-danger" data-filter="critical">Kritisch</button>
                    </div>
                </div>
                <div class="activity-stream">
                    {% for event in activity_stream %}
                    <div class="activity-item {{ event.event_type }} {% if event.event_type == 'anomaly' %}anomaly-{{ event.severity }}{% endif %}" 
                         data-severity="{{ event.severity or 'normal' }}">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <div class="d-flex align-items-center mb-1">
                                    {% if event.event_type == 'validation' %}
                                        <i class="bi bi-check-circle text-success me-2"></i>
                                    {% else %}
                                        <i class="bi bi-exclamation-triangle text-{{ 'warning' if event.severity == 'warning' else 'danger' }} me-2"></i>
                                    {% endif %}
                                    <strong>{{ event.customer_name or 'Unbekannt' }}</strong>
                                    <span class="text-muted ms-2">{{ event.license_key[:8] }}...</span>
                                </div>
                                <div class="small text-muted">
                                    {% if event.event_type == 'anomaly' %}
                                        <span class="badge bg-{{ 'warning' if event.severity == 'warning' else 'danger' }} me-2">
                                            {{ event.anomaly_type }}
                                        </span>
                                        {{ event.description }}
                                    {% else %}
                                        Validierung von {{ event.ip_address }} • Gerät: {{ event.hardware_id[:8] }}...
                                    {% endif %}
                                </div>
                            </div>
                            <div class="text-end">
                                <small class="text-muted">{{ event.timestamp.strftime('%H:%M:%S') if event.timestamp else '-' }}</small>
                                {% if event.event_type == 'anomaly' and event.severity == 'critical' %}
                                <div class="mt-1">
                                    <button class="btn btn-sm btn-danger" onclick="blockIP('{{ event.ip_address }}')">
                                        <i class="bi bi-slash-circle"></i> Block
                                    </button>
                                </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                    {% if not activity_stream %}
                    <div class="text-center text-muted p-5">
                        <i class="bi bi-inbox fs-1"></i>
                        <p class="mt-2">Keine Aktivitäten in den letzten 60 Minuten</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <!-- Statistics Panel (Right Panel) -->
        <div class="col-lg-4">
            <!-- Top Active Licenses -->
            <div class="stats-panel mb-3">
                <h6 class="mb-3">🏆 Top Aktive Lizenzen</h6>
                {% for license in top_licenses %}
                <div class="license-item">
                    <div>
                        <div class="fw-bold">{{ license.customer_name }}</div>
                        <small class="text-muted">{{ license.device_count }} Geräte • {{ license.validation_count }} Validierungen</small>
                    </div>
                    {% if license.anomaly_count > 0 %}
                    <span class="badge bg-warning">{{ license.anomaly_count }} ⚠️</span>
                    {% else %}
                    <span class="badge bg-success">OK</span>
                    {% endif %}
                </div>
                {% endfor %}
                {% if not top_licenses %}
                <p class="text-muted text-center">Keine aktiven Lizenzen</p>
                {% endif %}
            </div>
            
            <!-- Anomaly Distribution -->
            <div class="stats-panel mb-3">
                <h6 class="mb-3">🎯 Anomalie-Verteilung</h6>
                <canvas id="anomaly-chart" height="200"></canvas>
                {% if not anomaly_distribution %}
                <p class="text-muted text-center">Keine Anomalien erkannt</p>
                {% endif %}
            </div>
            
            <!-- Geographic Distribution -->
            <div class="stats-panel">
                <h6 class="mb-3">🌍 Geografische Verteilung</h6>
                <div style="max-height: 200px; overflow-y: auto;">
                    {% for geo in geo_data[:5] %}
                    <div class="d-flex justify-content-between align-items-center py-1">
                        <span class="text-truncate">{{ geo.ip_address }}</span>
                        <span class="badge bg-secondary">{{ geo.request_count }}</span>
                    </div>
                    {% endfor %}
                </div>
                {% if geo_data|length > 5 %}
                <small class="text-muted">+{{ geo_data|length - 5 }} weitere IPs</small>
                {% endif %}
            </div>
        </div>
    </div>
    
    <!-- Analysis Tabs -->
    <div class="card mt-4">
        <div class="card-header">
            <ul class="nav nav-tabs analysis-tabs card-header-tabs" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" data-bs-toggle="tab" href="#patterns">🔍 Patterns</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#performance">⚡ Performance</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#forensics">🔬 Forensics</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#predictions">📈 Predictions</a>
                </li>
            </ul>
        </div>
        <div class="card-body">
            <div class="tab-content">
                <div class="tab-pane active" id="patterns">
                    <p class="text-muted">Ungewöhnliche Verhaltensmuster werden hier angezeigt...</p>
                </div>
                <div class="tab-pane" id="performance">
                    <div class="chart-container">
                        <canvas id="performance-chart"></canvas>
                    </div>
                </div>
                <div class="tab-pane" id="forensics">
                    <p class="text-muted">Detaillierte Analyse spezifischer Lizenzen...</p>
                </div>
                <div class="tab-pane" id="predictions">
                    <p class="text-muted">Vorhersagen und Kapazitätsplanung...</p>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Auto-refresh functionality
let refreshInterval;
const AUTO_REFRESH_INTERVAL = 30000; // 30 seconds

function startAutoRefresh() {
    if ($('#auto-refresh').is(':checked')) {
        refreshInterval = setInterval(() => {
            location.reload();
        }, AUTO_REFRESH_INTERVAL);
    }
}

function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
}

$('#auto-refresh').change(function() {
    if (this.checked) {
        startAutoRefresh();
    } else {
        stopAutoRefresh();
    }
});

// Toggle expandable sections
function toggleSection(sectionId) {
    const section = document.getElementById(sectionId);
    const content = section.querySelector('.expandable-content');
    const icon = section.querySelector('.bi');
    
    content.classList.toggle('show');
    icon.classList.toggle('bi-chevron-down');
    icon.classList.toggle('bi-chevron-up');
}

// Filter activity stream
document.querySelectorAll('[data-filter]').forEach(button => {
    button.addEventListener('click', function() {
        const filter = this.dataset.filter;
        document.querySelectorAll('[data-filter]').forEach(btn => btn.classList.remove('active'));
        this.classList.add('active');
        
        document.querySelectorAll('.activity-item').forEach(item => {
            if (filter === 'all') {
                item.style.display = 'block';
            } else {
                const severity = item.dataset.severity;
                item.style.display = severity === filter ? 'block' : 'none';
            }
        });
    });
});

// Block IP function
function blockIP(ip) {
    if (confirm(`IP-Adresse ${ip} wirklich blockieren?`)) {
        // Implementation for blocking IP
        alert(`IP ${ip} wurde blockiert.`);
    }
}

// Initialize charts
const trendData = {{ trend_data|tojson }};
const anomalyData = {{ anomaly_distribution|tojson }};
const performanceData = {{ performance_data|tojson }};

// Trend Chart
if (trendData && trendData.length > 0) {
    const trendCtx = document.getElementById('trend-chart').getContext('2d');
    new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: trendData.map(d => new Date(d.hour).toLocaleTimeString('de-DE', {hour: '2-digit'})),
            datasets: [{
                label: 'Validierungen',
                data: trendData.map(d => d.validations),
                borderColor: '#0d6efd',
                backgroundColor: 'rgba(13, 110, 253, 0.1)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
}

// Anomaly Distribution Chart
if (anomalyData && anomalyData.length > 0) {
    const anomalyCtx = document.getElementById('anomaly-chart').getContext('2d');
    new Chart(anomalyCtx, {
        type: 'doughnut',
        data: {
            labels: anomalyData.map(d => d.anomaly_type),
            datasets: [{
                data: anomalyData.map(d => d.count),
                backgroundColor: ['#ffc107', '#dc3545', '#fd7e14', '#6f42c1']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { boxWidth: 12 }
                }
            }
        }
    });
}

// Performance Chart
if (performanceData && performanceData.length > 0) {
    const perfCtx = document.getElementById('performance-chart').getContext('2d');
    new Chart(perfCtx, {
        type: 'line',
        data: {
            labels: performanceData.map(d => new Date(d.minute).toLocaleTimeString('de-DE', {hour: '2-digit', minute: '2-digit'})),
            datasets: [{
                label: 'Avg Response Time',
                data: performanceData.map(d => d.avg_response_time),
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.4
            }, {
                label: 'Max Response Time',
                data: performanceData.map(d => d.max_response_time),
                borderColor: '#dc3545',
                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Response Time (ms)'
                    }
                }
            }
        }
    });
}

// Update last refresh time
function updateLastRefresh() {
    const now = new Date();
    document.getElementById('last-update').textContent = now.toLocaleTimeString('de-DE');
}

// Start auto-refresh on load
startAutoRefresh();
updateLastRefresh();
</script>
{% endblock %}