<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Analytics Dashboard</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f7fa;
            color: #2d3748;
        }
        
        .header {
            background: white;
            padding: 1rem 2rem;
            border-bottom: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1a202c;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
        }
        
        .stat-card h3 {
            font-size: 0.875rem;
            font-weight: 500;
            color: #718096;
            text-transform: uppercase;
            letter-spacing: 0.025em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1a202c;
            margin-bottom: 0.25rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .stat-change.positive {
            color: #38a169;
        }
        
        .stat-change.negative {
            color: #e53e3e;
        }
        
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .metrics-card {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
        }
        
        .metrics-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1a202c;
            margin-bottom: 1rem;
        }
        
        .metric-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .metric-item:last-child {
            border-bottom: none;
        }
        
        .metric-label {
            font-weight: 500;
            color: #4a5568;
        }
        
        .metric-value {
            font-weight: 600;
            color: #1a202c;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
        }
        
        .table-header {
            background: #f7fafc;
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1a202c;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 0.75rem 1.5rem;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        
        th {
            background: #f7fafc;
            font-weight: 600;
            color: #4a5568;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .loading {
            text-align: center;
            padding: 2rem;
            color: #718096;
        }
        
        .error {
            background: #fed7d7;
            color: #c53030;
            padding: 1rem;
            border-radius: 4px;
            margin: 1rem 0;
        }
        
        .period-selector {
            margin-bottom: 1.5rem;
        }
        
        .period-buttons {
            display: flex;
            gap: 0.5rem;
        }
        
        .period-btn {
            padding: 0.5rem 1rem;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.875rem;
            transition: all 0.2s;
        }
        
        .period-btn:hover {
            background: #f7fafc;
        }
        
        .period-btn.active {
            background: #3182ce;
            color: white;
            border-color: #3182ce;
        }
        
        @media (max-width: 768px) {
            .metrics-grid {
                grid-template-columns: 1fr;
            }
            
            .container {
                padding: 1rem;
            }
            
            .header {
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>📊 Analytics Dashboard</h1>
    </div>
    
    <div class="container">
        <div class="period-selector">
            <div class="period-buttons">
                <button class="period-btn active" data-days="7">7 Tage</button>
                <button class="period-btn" data-days="30">30 Tage</button>
                <button class="period-btn" data-days="90">90 Tage</button>
            </div>
        </div>
        
        <div class="stats-grid">
            <div class="stat-card">
                <h3>Seitenaufrufe</h3>
                <div class="stat-value" id="pageViews">-</div>
                <div class="stat-change positive" id="pageViewsChange">+0%</div>
            </div>
            
            <div class="stat-card">
                <h3>Eindeutige Besucher</h3>
                <div class="stat-value" id="uniqueVisitors">-</div>
                <div class="stat-change positive" id="visitorsChange">+0%</div>
            </div>
            
            <div class="stat-card">
                <h3>Absprungrate</h3>
                <div class="stat-value" id="bounceRate">-</div>
                <div class="stat-change negative" id="bounceChange">0%</div>
            </div>
            
            <div class="stat-card">
                <h3>Conversion Rate</h3>
                <div class="stat-value" id="conversionRate">-</div>
                <div class="stat-change positive" id="conversionChange">+0%</div>
            </div>
        </div>
        
        <div class="metrics-grid">
            <div class="metrics-card">
                <div class="metrics-title">Traffic-Quellen</div>
                <div id="trafficSourcesList">
                    <div class="loading">Lade Daten...</div>
                </div>
            </div>
            
            <div class="metrics-card">
                <div class="metrics-title">Performance-Metriken</div>
                <div class="metric-item">
                    <span class="metric-label">Durchschnittliche Sitzungsdauer</span>
                    <span class="metric-value" id="avgSessionDuration">-</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">Fehlerrate</span>
                    <span class="metric-value" id="errorRate">-</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">Conversion Rate</span>
                    <span class="metric-value" id="performanceConversionRate">-</span>
                </div>
            </div>
        </div>
        
        <div class="table-container">
            <div class="table-header">
                <div class="table-title">Top-Seiten</div>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>Seite</th>
                        <th>Aufrufe</th>
                        <th>Eindeutige Besucher</th>
                        <th>Absprungrate</th>
                    </tr>
                </thead>
                <tbody id="topPagesTable">
                    <tr>
                        <td colspan="4" class="loading">Lade Daten...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        class AnalyticsDashboard {
            constructor() {
                this.currentPeriod = 30;
                this.init();
            }
            
            async init() {
                this.setupEventListeners();
                await this.loadData();
            }
            
            setupEventListeners() {
                document.querySelectorAll('.period-btn').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        document.querySelectorAll('.period-btn').forEach(b => b.classList.remove('active'));
                        e.target.classList.add('active');
                        this.currentPeriod = parseInt(e.target.dataset.days);
                        this.loadData();
                    });
                });
            }
            
            async loadData() {
                try {
                    await Promise.all([
                        this.loadOverview(),
                        this.loadTopPages(),
                        this.loadTrafficSources()
                    ]);
                } catch (error) {
                    console.error('Error loading data:', error);
                    this.showError('Fehler beim Laden der Analytics-Daten');
                }
            }
            
            async loadOverview() {
                try {
                    const response = await fetch(`/admin/analytics/api/overview?days=${this.currentPeriod}`);
                    const result = await response.json();
                    
                    if (result.success) {
                        this.updateOverviewStats(result.data);
                    }
                } catch (error) {
                    console.error('Error loading overview:', error);
                }
            }
            
            updateOverviewStats(data) {
                document.getElementById('pageViews').textContent = this.formatNumber(data.total_page_views || 0);
                document.getElementById('uniqueVisitors').textContent = this.formatNumber(data.unique_visitors || 0);
                document.getElementById('bounceRate').textContent = this.formatPercent(data.bounce_rate || 0);
                document.getElementById('conversionRate').textContent = this.formatPercent(data.conversion_rate || 0);
                
                // Update performance metrics
                document.getElementById('avgSessionDuration').textContent = this.formatDuration(data.avg_session_duration || 0);
                document.getElementById('errorRate').textContent = this.formatPercent(data.error_rate || 0);
                document.getElementById('performanceConversionRate').textContent = this.formatPercent(data.conversion_rate || 0);
            }
            
            async loadTrafficSources() {
                try {
                    const response = await fetch(`/admin/analytics/api/traffic-sources?days=${this.currentPeriod}`);
                    const result = await response.json();
                    
                    if (result.success) {
                        this.updateTrafficSources(result.data);
                    }
                } catch (error) {
                    console.error('Error loading traffic sources:', error);
                }
            }
            
            updateTrafficSources(data) {
                const container = document.getElementById('trafficSourcesList');
                
                if (!data || Object.keys(data).length === 0) {
                    container.innerHTML = '<div class="loading">Keine Traffic-Daten verfügbar</div>';
                    return;
                }
                
                const total = Object.values(data).reduce((sum, val) => sum + val, 0);
                
                container.innerHTML = Object.entries(data).map(([source, count]) => {
                    const percentage = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
                    return `
                        <div class="metric-item">
                            <span class="metric-label">${source}</span>
                            <span class="metric-value">${count} (${percentage}%)</span>
                        </div>
                    `;
                }).join('');
            }
            
            async loadTopPages() {
                try {
                    const response = await fetch(`/admin/analytics/api/top-pages?days=${this.currentPeriod}&limit=10`);
                    const result = await response.json();
                    
                    if (result.success) {
                        this.updateTopPagesTable(result.data);
                    }
                } catch (error) {
                    console.error('Error loading top pages:', error);
                }
            }
            
            updateTopPagesTable(data) {
                const tbody = document.getElementById('topPagesTable');
                
                if (!data || data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="4" class="loading">Keine Daten verfügbar</td></tr>';
                    return;
                }
                
                tbody.innerHTML = data.map(page => `
                    <tr>
                        <td>${page.path || '-'}</td>
                        <td>${this.formatNumber(page.views || 0)}</td>
                        <td>${this.formatNumber(page.unique_visitors || 0)}</td>
                        <td>${this.formatPercent(page.bounce_rate || 0)}</td>
                    </tr>
                `).join('');
            }
            
            formatNumber(num) {
                if (num >= 1000000) {
                    return (num / 1000000).toFixed(1) + 'M';
                } else if (num >= 1000) {
                    return (num / 1000).toFixed(1) + 'K';
                }
                return num.toLocaleString();
            }
            
            formatPercent(num) {
                return (num * 100).toFixed(1) + '%';
            }
            
            formatDuration(seconds) {
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = Math.floor(seconds % 60);
                return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
            }
            
            showError(message) {
                const container = document.querySelector('.container');
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error';
                errorDiv.textContent = message;
                container.insertBefore(errorDiv, container.firstChild);
            }
        }
        
        // Initialize dashboard when DOM is loaded
        document.addEventListener('DOMContentLoaded', () => {
            new AnalyticsDashboard();
        });
    </script>
</body>
</html>