"""Performance testing example for AuroraView.

This example demonstrates:
1. Loading screen for better perceived performance
2. Performance monitoring and metrics
3. Optimized HTML loading
"""

import sys
import os

# Add parent directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'python'))

from auroraview import NativeWebView

# HTML with heavy content to test loading performance
HEAVY_HTML = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Performance Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 32px;
        }
        
        .metrics {
            background: #f7fafc;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .metric {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .metric:last-child {
            border-bottom: none;
        }
        
        .metric-label {
            font-weight: 600;
            color: #4a5568;
        }
        
        .metric-value {
            color: #667eea;
            font-weight: 700;
        }
        
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        .card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 10px;
        }
        
        .card-content {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            background: #48bb78;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>[LIGHTNING] Performance Test <span class="status">Ready</span></h1>
        
        <div class="metrics">
            <h2 style="margin-bottom: 15px; color: #2d3748;">Performance Metrics</h2>
            <div class="metric">
                <span class="metric-label">DOM Ready</span>
                <span class="metric-value" id="domReady">-</span>
            </div>
            <div class="metric">
                <span class="metric-label">Fully Loaded</span>
                <span class="metric-value" id="fullyLoaded">-</span>
            </div>
            <div class="metric">
                <span class="metric-label">JavaScript Init</span>
                <span class="metric-value" id="jsInit">-</span>
            </div>
            <div class="metric">
                <span class="metric-label">First Paint</span>
                <span class="metric-value" id="firstPaint">-</span>
            </div>
        </div>
        
        <h2 style="margin: 20px 0; color: #2d3748;">Test Cards</h2>
        <div class="grid" id="cardGrid">
            <!-- Cards will be generated by JavaScript -->
        </div>
    </div>
    
    <script>
        console.log(' Performance test starting...');
        
        // Generate test cards
        const grid = document.getElementById('cardGrid');
        for (let i = 1; i <= 50; i++) {
            const card = document.createElement('div');
            card.className = 'card';
            card.innerHTML = `
                <div class="card-title">Card ${i}</div>
                <div class="card-content">This is test card number ${i}</div>
            `;
            grid.appendChild(card);
        }
        
        // Update metrics display
        function updateMetrics() {
            if (window.auroraViewPerf) {
                const perf = window.auroraViewPerf;
                
                if (perf.marks.domReady) {
                    document.getElementById('domReady').textContent = 
                        (perf.marks.domReady - perf.start).toFixed(2) + ' ms';
                }
                
                if (perf.marks.loaded) {
                    document.getElementById('fullyLoaded').textContent = 
                        (perf.marks.loaded - perf.start).toFixed(2) + ' ms';
                }
                
                if (perf.marks.jsInit) {
                    document.getElementById('jsInit').textContent = 
                        (perf.marks.jsInit - perf.start).toFixed(2) + ' ms';
                }
            }
        }
        
        // Listen for first paint event
        window.addEventListener('first_paint', (e) => {
            console.log('[OK] First paint event received:', e.detail);
            document.getElementById('firstPaint').textContent = 
                e.detail.time.toFixed(2) + ' ms';
        });
        
        // Update metrics periodically
        setInterval(updateMetrics, 100);
        
        // Initial update
        updateMetrics();
        
        console.log('[OK] Performance test initialized');
    </script>
</body>
</html>
"""

print("=" * 70)
print("Performance Test - AuroraView")
print("=" * 70)
print("")
print("This example demonstrates:")
print(" Performance monitoring")
print(" Loading time metrics")
print(" Heavy content rendering")
print("")

# Create WebView with performance monitoring
print("Creating WebView...")
webview = NativeWebView.standalone(
    title="Performance Test",
    width=1000,
    height=700,
    dev_tools=True,
    decorations=True,
)

# Register performance event handler
@webview.on("first_paint")
def handle_first_paint(data):
    print(f"[OK] First paint: {data.get('time', 0):.2f} ms")

# Load HTML
print("Loading HTML...")
webview.load_html(HEAVY_HTML)

# Show window
print("Showing window...")
print("")
print("Check the browser console for performance metrics!")
print("Press Ctrl+C to close")
print("")

try:
    webview.show()
except KeyboardInterrupt:
    print("\n\n[OK] Test completed")

