<layout name="admin" />

<div class="section">
    <h2>Performance Übersicht</h2>
    <div class="stats-grid">
        <div class="stat-card">
            <h3>💾 Speicher <span id="realtime-indicator" class="indicator"></span></h3>
            <p><strong>Aktuell:</strong> <span id="current-memory">{{ performance.currentMemoryUsage }}</span></p>
            <p><strong>Peak:</strong> <span id="peak-memory">{{ performance.peakMemoryUsage }}</span></p>
            <p><strong>Limit:</strong> {{ performance.memoryLimit }}</p>
            <p><strong>Auslastung:</strong> <span id="memory-percentage">{{ performance.memoryUsagePercentage }}</span>%</p>
            <div class="progress-bar">
                <div class="progress-fill" id="memory-progress" style="width: {{ performance.memoryUsagePercentage }}%"></div>
            </div>
        </div>

        <div class="stat-card">
            <h3>System</h3>
            <p><strong>Ausführungszeit:</strong> {{ performance.executionTime }}</p>
            <p><strong>Geladene Dateien:</strong> {{ performance.includedFiles }}</p>
            <p><strong>OPCache:</strong> {{ performance.opcacheEnabled }}</p>
        </div>

        <if condition="{{ performance.opcacheMemoryUsage }}">
            <div class="stat-card">
                <h3>OPCache</h3>
                <p><strong>Speicher:</strong> {{ performance.opcacheMemoryUsage }}</p>
                <p><strong>Cache Hits:</strong> {{ performance.opcacheCacheHits }}</p>
                <p><strong>Miss Rate:</strong> {{ performance.opcacheMissRate }}</p>
            </div>
        </if>
    </div>

    <!-- Real-time Controls -->
    <div class="admin-card" style="margin-top: var(--space-lg);">
        <div class="admin-card__header">
            <h3 class="admin-card__title">⚙️ Real-time Monitoring</h3>
        </div>
        <div class="admin-card__content">
            <label style="display: flex; align-items: center; gap: 10px;">
                <input type="checkbox" id="realtime-toggle">
                <span>Enable Real-time Updates</span>
                <span id="realtime-status" class="status-indicator"></span>
            </label>
            <p style="margin-top: 10px; font-size: 0.9em; color: var(--text-muted);">
                <span id="last-update">Last Updated: {{ timestamp }}</span>
            </p>
        </div>
    </div>
</div>

<style>
    .progress-bar {
        height: 8px;
        background: var(--bg-muted);
        border-radius: 4px;
        overflow: hidden;
        margin: 8px 0;
    }

    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, var(--success), var(--success-dark));
        transition: width 0.3s ease;
    }

    .indicator {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: var(--text-muted);
        margin-left: 8px;
    }

    .indicator.active {
        background: var(--success);
        animation: pulse 1s infinite;
    }

    .status-indicator {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background: var(--text-muted);
        display: inline-block;
    }

    .status-indicator.active {
        background: var(--success);
        animation: pulse 1s infinite;
    }

    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: var(--space-lg);
        margin-bottom: var(--space-lg);
    }

    .stat-card {
        background: var(--bg-surface);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: var(--space-lg);
    }

    .stat-card h3 {
        margin: 0 0 var(--space-md) 0;
        color: var(--text-primary);
        display: flex;
        align-items: center;
    }

    .stat-card p {
        margin: var(--space-sm) 0;
        color: var(--text-secondary);
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const toggle = document.getElementById('realtime-toggle');
    const statusIndicator = document.getElementById('realtime-status');
    const realtimeIndicator = document.getElementById('realtime-indicator');
    const lastUpdate = document.getElementById('last-update');
    let updateInterval = null;

    toggle?.addEventListener('change', function() {
        if (this.checked) {
            startRealtimeUpdates();
        } else {
            stopRealtimeUpdates();
        }
    });

    function startRealtimeUpdates() {
        statusIndicator?.classList.add('active');
        realtimeIndicator?.classList.add('active');

        updateInterval = setInterval(async () => {
            try {
                const response = await fetch('/admin/system/performance/api/realtime');
                const data = await response.json();
                updateMetrics(data);
            } catch (error) {
                console.error('Failed to fetch realtime metrics:', error);
                stopRealtimeUpdates();
                toggle.checked = false;
            }
        }, 3000); // Update every 3 seconds
    }

    function stopRealtimeUpdates() {
        statusIndicator?.classList.remove('active');
        realtimeIndicator?.classList.remove('active');

        if (updateInterval) {
            clearInterval(updateInterval);
            updateInterval = null;
        }
    }

    function updateMetrics(data) {
        // Update memory metrics
        const currentMemory = document.getElementById('current-memory');
        if (currentMemory && data.memory?.current) {
            currentMemory.textContent = data.memory.current;
        }

        const peakMemory = document.getElementById('peak-memory');
        if (peakMemory && data.memory?.peak) {
            peakMemory.textContent = data.memory.peak;
        }

        const memoryPercentage = document.getElementById('memory-percentage');
        const memoryProgress = document.getElementById('memory-progress');
        if (data.memory?.usage_percentage !== undefined) {
            if (memoryPercentage) {
                memoryPercentage.textContent = data.memory.usage_percentage.toFixed(1);
            }
            if (memoryProgress) {
                memoryProgress.style.width = data.memory.usage_percentage + '%';
            }
        }

        // Update timestamp
        if (lastUpdate && data.timestamp) {
            lastUpdate.textContent = 'Last Updated: ' + data.timestamp;
        }
    }
});
</script>