<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }} - PipelineScope Report</title>
    <style>
        :root {
            --navy: #1E293B;
            --navy-light: #334155;
            --navy-lighter: #475569;
            --amber: #F59E0B;
            --amber-light: #FBBF24;
            --amber-dark: #D97706;
            --success: #10B981;
            --success-light: #D1FAE5;
            --error: #F43F5E;
            --error-light: #FFE4E6;
            --warning: #F97316;
            --warning-light: #FFEDD5;
            --info: #0EA5E9;
            --info-light: #CFFAFE;
            --gray-50: #F8FAFC;
            --gray-100: #F1F5F9;
            --gray-200: #E2E8F0;
            --gray-300: #CBD5E1;
            --gray-400: #94A3B8;
            --gray-600: #64748B;
            --gray-700: #475569;
            --gradient-card: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(248, 250, 252, 0.95));
        }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #0F172A 0%, #1A1F35 100%);
            color: var(--navy);
            line-height: 1.6;
            padding: 24px;
            min-height: 100vh;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            background: var(--gradient-card);
            backdrop-filter: blur(20px);
            padding: 40px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(30, 41, 59, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 32px;
            position: relative;
            overflow: hidden;
        }
        
        .header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(245, 158, 11, 0.05) 0%, transparent 70%);
            pointer-events: none;
        }
        
        .header h1 {
            font-size: 32px;
            font-weight: 800;
            color: var(--navy);
            margin-bottom: 8px;
            position: relative;
            z-index: 1;
        }
        
        .header .meta {
            color: var(--gray-600);
            font-size: 13px;
            position: relative;
            z-index: 1;
        }
        
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 32px;
        }

        .card {
            background: var(--gradient-card);
            backdrop-filter: blur(20px);
            padding: 28px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(30, 41, 59, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }
        
        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--amber), var(--amber-light));
        }

        .card:hover {
            transform: translateY(-4px);
            box-shadow: 0 16px 48px rgba(30, 41, 59, 0.2);
            border-color: rgba(245, 158, 11, 0.3);
        }
        
        .card-title {
            font-size: 12px;
            font-weight: 700;
            color: var(--gray-600);
            text-transform: uppercase;
            letter-spacing: 0.8px;
            margin-bottom: 12px;
        }
        
        .card-value {
            font-size: 36px;
            font-weight: 800;
            color: var(--navy);
            margin-bottom: 8px;
        }
        
        .card-subtitle {
            font-size: 13px;
            color: var(--gray-400);
        }

        .section {
            background: var(--gradient-card);
            backdrop-filter: blur(20px);
            padding: 32px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(30, 41, 59, 0.1);
            margin-bottom: 24px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .section:hover {
            box-shadow: 0 12px 40px rgba(30, 41, 59, 0.15);
            border-color: rgba(245, 158, 11, 0.2);
        }
        
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 2px solid rgba(30, 41, 59, 0.1);
        }

        .section-title {
            font-size: 20px;
            font-weight: 800;
            color: var(--navy);
        }

        .expandable-card {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.5), rgba(248, 250, 252, 0.5));
            border: 1px solid rgba(30, 41, 59, 0.1);
            border-radius: 12px;
            margin-bottom: 16px;
            overflow: visible;
            backdrop-filter: blur(10px);
        }
        
        .expandable-header {
            padding: 16px 20px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: linear-gradient(135deg, rgba(30, 41, 59, 0.04), rgba(245, 158, 11, 0.02));
            user-select: none;
            transition: all 0.2s;
        }
        
        .expandable-header:hover {
            background: linear-gradient(135deg, rgba(30, 41, 59, 0.08), rgba(245, 158, 11, 0.05));
            border-left: 3px solid var(--amber);
            padding-left: 17px;
        }
        
        .expandable-title {
            font-size: 15px;
            font-weight: 600;
            color: var(--navy-light);
        }
        
        .expandable-icon {
            transition: transform 0.3s;
            color: var(--amber);
        }
        
        .expandable-icon.expanded {
            transform: rotate(180deg);
        }

        .expandable-content {
            display: grid;
            grid-template-rows: 0fr;
            transition: grid-template-rows 0.3s ease-out;
            overflow: hidden;
        }

        .expandable-content.expanded {
            grid-template-rows: 1fr;
        }

        .expandable-body {
            min-height: 0;
            padding: 16px 20px;
            display: block;
            max-width: 100%;
        }

        .prompt-box {
            background: linear-gradient(135deg, rgba(30, 41, 59, 0.03), rgba(245, 158, 11, 0.01));
            border: 1px solid rgba(30, 41, 59, 0.1);
            border-radius: 8px;
            padding: 16px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            white-space: pre-wrap;
            word-wrap: break-word;
            overflow-wrap: break-word;
            max-height: 500px;
            overflow-y: auto;
            position: relative;
            backdrop-filter: blur(10px);
        }

        pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        
        .copy-btn {
            position: absolute;
            top: 12px;
            right: 12px;
            padding: 8px 16px;
            background: linear-gradient(135deg, var(--amber), var(--amber-light));
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.2s;
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
        }
        
        .copy-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(245, 158, 11, 0.4);
        }
        
        .copy-btn:active {
            transform: translateY(0);
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        
        th {
            background: linear-gradient(135deg, rgba(30, 41, 59, 0.08), rgba(245, 158, 11, 0.04));
            padding: 14px 12px;
            text-align: left;
            font-weight: 700;
            color: var(--navy);
            border-bottom: 2px solid rgba(245, 158, 11, 0.2);
            position: sticky;
            top: 0;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 0.5px;
        }
        
        td {
            padding: 14px 12px;
            border-bottom: 1px solid rgba(30, 41, 59, 0.05);
        }
        
        tbody tr:nth-child(odd) {
            background: rgba(30, 41, 59, 0.02);
        }
        
        tbody tr:hover {
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.08), rgba(245, 158, 11, 0.04));
            transition: all 0.2s;
        }
        
        .rank-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            border-radius: 8px;
            font-weight: 700;
            font-size: 12px;
            color: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .rank-1 { background: linear-gradient(135deg, #F43F5E, #E11D48); }
        .rank-2 { background: linear-gradient(135deg, #F97316, #EA580C); }
        .rank-3 { background: linear-gradient(135deg, #F59E0B, #D97706); color: white; }
        .rank-4 { background: linear-gradient(135deg, #10B981, #059669); }
        .rank-5 { background: linear-gradient(135deg, #0EA5E9, #0284C7); }
        
        .heat-bar {
            height: 8px;
            border-radius: 4px;
            background: linear-gradient(90deg, var(--success), var(--amber), var(--error));
            position: relative;
            margin-top: 6px;
            box-shadow: 0 2px 8px rgba(245, 158, 11, 0.2);
            overflow: hidden;
        }
        
        .heat-indicator {
            position: absolute;
            width: 3px;
            height: 16px;
            background: var(--navy);
            top: -4px;
            border-radius: 2px;
            box-shadow: 0 0 4px rgba(30, 41, 59, 0.4);
        }
        
        .filters {
            display: flex;
            gap: 16px;
            flex-wrap: wrap;
            margin-bottom: 24px;
            padding: 20px;
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.5), rgba(248, 250, 252, 0.5));
            border-radius: 12px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(10px);
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }
        
        .filter-label {
            font-size: 12px;
            font-weight: 700;
            color: var(--navy);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        select, input[type="range"], input[type="number"] {
            padding: 10px 14px;
            border: 1.5px solid rgba(30, 41, 59, 0.2);
            border-radius: 8px;
            font-size: 14px;
            background: rgba(255, 255, 255, 0.8);
            color: var(--navy);
            transition: all 0.2s;
            font-weight: 500;
        }
        
        select:hover, input[type="range"]:hover, input[type="number"]:hover {
            border-color: var(--amber);
            background: rgba(255, 255, 255, 0.95);
        }
        
        select:focus, input[type="range"]:focus, input[type="number"]:focus {
            outline: none;
            border-color: var(--amber);
            box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
        }
        
        select {
            min-width: 160px;
            cursor: pointer;
        }
        
        input[type="range"] {
            width: 200px;
            accent-color: var(--amber);
        }
        
        .badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .badge-primary { background: var(--info-light); color: var(--info); }
        .badge-success { background: var(--success-light); color: var(--success); }
        .badge-warning { background: var(--warning-light); color: var(--warning); }
        .badge-danger { background: var(--error-light); color: var(--error); }
        
        .table-container {
            max-height: 600px;
            overflow-y: auto;
            border: 1px solid rgba(30, 41, 59, 0.1);
            border-radius: 12px;
            backdrop-filter: blur(10px);
        }
        
        .table-container::-webkit-scrollbar {
            width: 8px;
        }
        
        .table-container::-webkit-scrollbar-track {
            background: rgba(30, 41, 59, 0.05);
            border-radius: 10px;
        }
        
        .table-container::-webkit-scrollbar-thumb {
            background: linear-gradient(180deg, var(--amber), var(--amber-dark));
            border-radius: 10px;
            box-shadow: 0 0 6px rgba(245, 158, 11, 0.4);
        }
        
        .table-container::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(180deg, var(--amber-light), var(--amber));
        }
        
        @media print {
            body { background: white; }
            .section { box-shadow: none; page-break-inside: avoid; }
            .filters { display: none; }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>{{ title }}</h1>
            <div class="meta">
                Generated: {{ timestamp_readable }} | Run ID: {{ timestamp }}
            </div>
        </div>
        
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="card">
                <div class="card-title">Total Runtime</div>
                <div class="card-value">{{ total_runtime_sec }}s</div>
                <div class="card-subtitle">{{ total_runtime_ms | round(2) }} milliseconds</div>
            </div>
            
            <div class="card">
                <div class="card-title">Functions Profiled</div>
                <div class="card-value">{{ total_functions }}</div>
                <div class="card-subtitle">User-defined functions</div>
            </div>
            
            <div class="card">
                <div class="card-title">Sample Size</div>
                <div class="card-value">{{ sample_size | int }}</div>
                <div class="card-subtitle">Records processed</div>
            </div>

            <div class="card">
                <div class="card-title">Projected Scale</div>
                <div class="card-value">
                    <input type="number" id="scale-input" value="{{ expected_size | int }}" 
                           min="1" step="1" 
                           style="font-size: 32px; font-weight: 700; width: 100%; border: 1px solid #dee2e6; border-radius: 4px; padding: 5px; text-align: center;"
                           oninput="recalculateProjections()">
                </div>
                <div class="card-subtitle">Adjust to see impact at any scale</div>
            </div>

        </div>

        <!-- Top Hotspots -->
        <div class="section">
            <div class="section-header">
                <!-- <div class="section-title">🔥 Hotspot Analysis</div> -->
                <div class="section-title">🔍 Function Analysis (Top 5)</div>
                <div class="filter-group">
                    <select id="hotspot-count" onchange="updateHotspotCount()">
                        <option value="5" selected>Top 5</option>
                        <option value="10">Top 10</option>
                        <option value="20">Top 20</option>
                        <option value="50">Top 50</option>
                        <option value="all">All</option>
                    </select>
                </div>
            </div>

            <div class="filters" style="margin-left: 20px;">
                    <div class="filter-group">
                        <label class="filter-label">Module</label>
                        <select id="module-filter" onchange="applyFunctionFilters()">
                            <option value="all">All Modules</option>
                            {% for module in all_modules %}
                            <option value="{{ module.module_name }}">{{ module.module_name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label class="filter-label">Min Time (ms): <span id="time-value">0</span></label>
                        <input type="range" id="time-filter" min="0" max="1000" step="0.1" value="0" oninput="applyFunctionFilters()">
                    </div>
                    
                    <div class="filter-group">
                        <label class="filter-label">Min %: <span id="percent-value">0</span></label>
                        <input type="range" id="percent-filter" min="0" max="20" step="0.1" value="0" oninput="applyFunctionFilters()">
                    </div>
            </div>

            <div class="table-container">
                <table id="hotspots-table">
                    <thead>
                        <tr>
                            <th>Rank</th>
                            <th>Function</th>
                            <th>Module</th>
                            <th>Self Time (ms)</th>
                            <th>Projected Time (ms)</th>
                            <th>% of Total</th>
                            <th>Calls</th>
                            <th>CPU %</th>
                            <th>Memory (MB)</th>
                            {% if has_gpu_data %}
                            <th>Avg GPU (%)</th>
                            <th>Peak GPU (MB)</th>
                            {% endif %}
                        </tr>
                    </thead>
                    <tbody id="hotspots-body">
                        {% for i in range(all_functions | length) %}
                        {% set func = all_functions[i] %}

                        <tr class="hotspot-row" 
                            data-func-name="{{ all_functions[i].display_name }}" 
                            style="{% if i >= 5 %}display:none;{% endif %}">
                            
                            <td><span class="rank-badge rank-{{ i + 1 if i < 5 else 'default' }}">{{ i + 1 }}</span></td>
                            <td><strong>{{ all_functions[i].display_name }}</strong></td>
                            <td>{{ all_functions[i].module }}</td>

                            <td class="self-time-cell">
                                <strong>{{ all_functions[i].self_time_ms | round(2) }}</strong>
                                <div class="time-hhmmss">{{ all_functions[i].self_time_ms | format_time }}</div>
                            </td>

                            <td class="proj-time-cell">
                                <strong>{{ "%.2f"|format(all_functions[i].projected_self_time_ms) }}</strong>
                                <div class="time-hhmmss">{{ all_functions[i].projected_self_time_ms | format_time }}</div>
                            </td>

                            <td class="percent-cell">
                                {{ all_functions[i].percentage | round(2) }}%
                                <div class="heat-bar">
                                    <div class="heat-indicator" style="left: {{ all_functions[i].percentage }}%;"></div>
                                </div>
                            </td>
                            <td>{{ all_functions[i].call_count }}</td>
                            <td>{{ all_functions[i].avg_cpu_percent | round(2) }}</td>
                            <td>{{ all_functions[i].peak_memory_mb | round(2) }}</td>
                            {% if has_gpu_data %}
                            <td>{{ all_functions[i].avg_gpu_utilization if all_functions[i].avg_gpu_utilization > 0 else "—" }}</td>
                            <td>{{ all_functions[i].peak_gpu_memory_mb if all_functions[i].peak_gpu_memory_mb > 0 else "—" }}</td>
                            {% endif %}
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

        </div>

        <!-- Module Summary -->
        <div class="section">
            <div class="section-header">
                <div class="section-title">🏆 Module Performance Ranking</div>
            </div>
            
            <table>

                <thead>
                    <tr>
                        <th style="width: 25%;">Function / Method</th>
                        <th style="width: 15%;">Self Time (ms)</th>
                        <th style="width: 20%;">Projected Time (ms)</th>
                        <th style="width: 15%;">% of Total</th>
                        <th style="width: 10%;">Calls</th>
                    </tr>
                </thead>

                <tbody>
                    {% for module in top_modules %}
                    <!-- {{ module | tojson }} -->
                    <tr>
                        <td><strong>{{ module.module_name }}</strong></td>
                        <td>{{ module.total_time_ms | round(2) }}</td>

                        <td>
                            <strong>{{ "%.2f"|format(module.projected_time_ms) }}</strong>
                            <div class="time-hhmmss">{{ module.projected_time_ms | format_time }}</div>
                        </td>
                        <td>{{ module.percentage | round(2) }}%</td>

                        <td>{{ module.total_calls }}</td>

                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- LLM Optimization Prompt -->
        <div class="expandable-card">
            <div class="expandable-header" onclick="toggleExpand('llm-prompt')">
                <div class="expandable-title">✨ AI Optimization Prompt</div>
                <div class="expandable-icon" id="llm-prompt-icon">▼</div>
            </div>

            <div class="expandable-content" id="llm-prompt-content">
                <div class="expandable-body">
                    <div class="prompt-box" style="position: relative;">
                        <button class="copy-btn" onclick="copyPrompt()">📋 Copy Prompt</button>
                        <pre id="optimizationPrompt">{{ llm_prompt }}</pre>
                    </div>
                </div>
            </div>
        </div>

    </div>
    
    <script>

        const state = {
            originalSampleSize: {{ sample_size }},
            data: {{ all_functions | tojson }}
        };

        // Toggle expandable card
        function toggleExpand(id) {
            document.getElementById(id + '-content').classList.toggle('expanded');
            document.getElementById(id + '-icon').classList.toggle('expanded');
        }
        
        // Copy LLM prompt to clipboard
        function copyPrompt() {
            const text = document.getElementById('optimizationPrompt').innerText;
            navigator.clipboard.writeText(text).then(() => {
                const btn = document.querySelector('.copy-btn');
                const originalText = btn.textContent;
                btn.innerHTML = '✅ Copied!';
                btn.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
                btn.style.transform = 'scale(1.05)';

                setTimeout(() => {
                    btn.innerHTML = originalText;
                    btn.style.background = '';
                    btn.style.transform = '';
                }, 2000);
            });
        }

        // Update hotspot count
        function updateHotspotCount() {
            const value = document.getElementById('hotspot-count').value;
            const rows = document.querySelectorAll('.hotspot-row');
            
            if (value === 'all') {
                document.querySelector('.section-title').textContent = '🔍 Function Analysis (All)';
                rows.forEach(row => row.style.display = '');
            } else {
                const count = parseInt(value);
                document.querySelector('.section-title').textContent = `🔍 Function Analysis (Top ${count})`;
                rows.forEach((row, index) => {
                    row.style.display = index < count ? '' : 'none';
                });
            }
        }

        function applyFunctionFilters() {
            const module = document.getElementById('module-filter').value;
            const minTime = parseFloat(document.getElementById('time-filter').value);
            const minPercent = parseFloat(document.getElementById('percent-filter').value);
            
            // Update labels
            document.getElementById('time-value').textContent = minTime.toFixed(1);
            document.getElementById('percent-value').textContent = minPercent.toFixed(1);
            
            // Filter rows
            const rows = document.querySelectorAll('.hotspot-row');
            const value = document.getElementById('hotspot-count').value;
            const topN = value === 'all' ? Infinity : parseInt(value);
            
            let visibleCount = 0;
            rows.forEach((row, index) => {
                const rowModule = row.querySelector('td:nth-child(3)').textContent.trim();
                const rowTime = parseFloat(row.querySelector('.self-time-cell strong').textContent);
                const rowPercent = parseFloat(row.querySelector('.percent-cell').textContent);
                
                const moduleMatch = module === 'all' || rowModule === module;
                const timeMatch = rowTime >= minTime;
                const percentMatch = rowPercent >= minPercent;
                const topNMatch = visibleCount < topN;
                
                if (moduleMatch && timeMatch && percentMatch && topNMatch) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
        }

        // Initialize
        applyFunctionFilters();

        // Store original observed values
        const originalSampleSize = {{ sample_size }};
        const allFunctionsData = [
            {% for func in all_functions %}
            {
                signature: "{{ func.display_name }}",
                observedTime: {{ func.total_time_ms }},
                observedSelfTime: {{ func.self_time_ms }},
                observedCalls: {{ func.call_count }},
                avgTime: {{ func.avg_time_ms }},
                percentage: {{ func.percentage }},
                module: "{{ func.module }}"
            },
            {% endfor %}
        ];

        function recalculateProjections() {
            const initialScale = {{ expected_size }};
            const newScale = parseInt(document.getElementById('scale-input').value) || initialScale;
            const scaleFactor = newScale / initialScale;

            document.querySelectorAll('.hotspot-row').forEach(row => {
                const funcName = row.getAttribute('data-func-name');
                const func = state.data.find(f => f.display_name === funcName);
                if (!func) return;

                const projTime = func.projected_self_time_ms * scaleFactor;

                row.querySelector('.proj-time-cell').innerHTML = `<strong>${projTime.toFixed(2)}</strong><div class="time-hhmmss">${formatTime(projTime)}</div>`;
            });
        }

        function formatTime(ms) {
            if (ms < 1000) {
                return `${Math.floor(ms)}ms`;
            }

            const totalSeconds = Math.floor(ms / 1000);
            const days = Math.floor(totalSeconds / 86400);
            const hours = Math.floor((totalSeconds % 86400) / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;

            const parts = [];
            if (days > 0) parts.push(`${days}d`);
            if (hours > 0) parts.push(`${hours}h`);
            if (minutes > 0) parts.push(`${minutes}m`);
            if (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);

            return parts.join(' ');
        }

    </script>
</body>
</html>
