<!-- Unified Tools Timeline -->
<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden" x-data="{ showTable: false }">
    <!-- Header -->
    <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
            <div>
                <h3 class="text-lg font-semibold text-gray-900">Tools Timeline</h3>
                <p class="text-sm text-gray-500 mt-1">All tool calls across conversations - click a point to see details</p>
            </div>
            <div class="flex items-center gap-4">
                <!-- Session Filter -->
                <div class="flex items-center gap-2">
                    <label for="session-filter" class="text-sm text-gray-500">Filter by session:</label>
                    <select 
                        id="session-filter"
                        class="text-sm border-gray-300 rounded-md shadow-sm focus:ring-[#0770E3] focus:border-[#0770E3]"
                        hx-get="/api/tools/timeline"
                        hx-target="#unified-timeline-container"
                        hx-swap="innerHTML"
                        hx-include="[name='period']"
                        name="session_id"
                    >
                        <option value="">All sessions</option>
                        {% for session in timeline.sessions %}
                        <option value="{{ session.session_id }}" {% if timeline.selected_session == session.session_id %}selected{% endif %}>
                            {{ session.project_name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Stats Row -->
    <div class="px-6 py-3 bg-gray-50 border-b border-gray-200 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
        <div>
            <span class="text-gray-500">Total Calls</span>
            <p class="font-medium text-gray-900">{{ timeline.total_invocations }}</p>
        </div>
        <div>
            <span class="text-gray-500">Tools Used</span>
            <p class="font-medium text-gray-900">{{ timeline.tool_counts|length }}</p>
        </div>
        <div>
            <span class="text-gray-500">Total Tokens</span>
            <p class="font-medium text-gray-900">{{ timeline.total_tokens|format_compact }}</p>
        </div>
        <div>
            <span class="text-gray-500">Est. Cost</span>
            <p class="font-medium text-[#0770E3]">${{ "%.4f"|format(timeline.total_cost) }}</p>
        </div>
    </div>

    <!-- Tool Legend -->
    <div class="px-6 py-3 border-b border-gray-200">
        <div class="flex flex-wrap gap-3">
            {% for tool_name, count in timeline.tool_counts.items()|sort(attribute='1', reverse=true) %}
            <div class="flex items-center gap-1.5 text-xs">
                <span class="w-3 h-3 rounded-full" style="background-color: {{ {
                    'Read': '#3B82F6',
                    'Write': '#10B981',
                    'Edit': '#F59E0B',
                    'Bash': '#6366F1',
                    'Glob': '#8B5CF6',
                    'Grep': '#EC4899',
                    'Task': '#EF4444',
                    'WebFetch': '#06B6D4',
                    'TodoWrite': '#84CC16',
                    'TodoRead': '#22C55E'
                }.get(tool_name, '#6B7280') }};"></span>
                <span class="text-gray-700">{{ tool_name }}</span>
                <span class="text-gray-400">({{ count }})</span>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- Chart -->
    <div class="p-6">
        {% if timeline.datasets %}
        <div class="h-80">
            <canvas id="unifiedToolsTimelineChart"></canvas>
        </div>

        <!-- Date Range Slider -->
        <div class="mt-4 px-2">
            <div class="flex items-center justify-between mb-2">
                <span class="text-sm text-gray-500">Zoom into time range:</span>
                <button id="resetZoomBtn" class="text-xs text-[#0770E3] hover:underline">Reset zoom</button>
            </div>
            <div class="relative pt-1">
                <div class="flex items-center gap-4">
                    <span id="rangeStartLabel" class="text-xs text-gray-500 w-32"></span>
                    <div class="flex-1 relative">
                        <!-- Track background -->
                        <div class="h-2 bg-gray-200 rounded-full"></div>
                        <!-- Selected range highlight -->
                        <div id="rangeHighlight" class="absolute top-0 h-2 bg-[#0770E3] bg-opacity-30 rounded-full"></div>
                        <!-- Min handle -->
                        <input type="range" id="rangeMin" 
                            class="absolute top-0 w-full h-2 appearance-none bg-transparent pointer-events-none [&::-webkit-slider-thumb]:pointer-events-auto [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:bg-[#0770E3] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer [&::-webkit-slider-thumb]:shadow-md [&::-moz-range-thumb]:pointer-events-auto [&::-moz-range-thumb]:appearance-none [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:bg-[#0770E3] [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:cursor-pointer [&::-moz-range-thumb]:border-0"
                            min="0" max="100" value="0">
                        <!-- Max handle -->
                        <input type="range" id="rangeMax" 
                            class="absolute top-0 w-full h-2 appearance-none bg-transparent pointer-events-none [&::-webkit-slider-thumb]:pointer-events-auto [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:bg-[#0770E3] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer [&::-webkit-slider-thumb]:shadow-md [&::-moz-range-thumb]:pointer-events-auto [&::-moz-range-thumb]:appearance-none [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:bg-[#0770E3] [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:cursor-pointer [&::-moz-range-thumb]:border-0"
                            min="0" max="100" value="100">
                    </div>
                    <span id="rangeEndLabel" class="text-xs text-gray-500 w-32 text-right"></span>
                </div>
            </div>
        </div>

        <script>
        (function() {
            const chartId = 'unifiedToolsTimelineChart';
            const existing = Chart.getChart(chartId);
            if (existing) existing.destroy();

            requestAnimationFrame(function() {
                requestAnimationFrame(function() {
                    const ctx = document.getElementById(chartId);
                    if (!ctx) return;

                    const chartData = {{ timeline|tojson|safe }};

                    // Collect all timestamps to find min/max
                    let allTimestamps = [];
                    chartData.datasets.forEach(ds => {
                        ds.data.forEach(point => {
                            allTimestamps.push(new Date(point.x).getTime());
                        });
                    });
                    
                    const minTime = Math.min(...allTimestamps);
                    const maxTime = Math.max(...allTimestamps);
                    const timeRange = maxTime - minTime;

                    // Transform data for bubble chart
                    const datasets = chartData.datasets.map(ds => ({
                        label: ds.label,
                        data: ds.data.map(point => ({
                            x: new Date(point.x),
                            y: point.y,
                            r: point.r || 5,
                            invocation_id: point.invocation_id,
                            tool_name: point.tool_name,
                            session_id: point.session_id,
                            project: point.project,
                            cost: point.cost,
                            input_tokens: point.input_tokens,
                            output_tokens: point.output_tokens,
                            params_preview: point.params_preview
                        })),
                        backgroundColor: ds.backgroundColor,
                        borderColor: ds.borderColor,
                        borderWidth: 1,
                    }));

                    const chart = new Chart(ctx, {
                        type: 'bubble',
                        data: { datasets },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                x: {
                                    type: 'time',
                                    min: minTime,
                                    max: maxTime,
                                    time: {
                                        unit: 'hour',
                                        displayFormats: {
                                            hour: 'MMM d, HH:mm'
                                        }
                                    },
                                    title: {
                                        display: true,
                                        text: 'Time'
                                    }
                                },
                                y: {
                                    beginAtZero: true,
                                    title: {
                                        display: true,
                                        text: 'Tokens'
                                    }
                                }
                            },
                            plugins: {
                                tooltip: {
                                    callbacks: {
                                        title: function(context) {
                                            const point = context[0].raw;
                                            return point.tool_name;
                                        },
                                        label: function(context) {
                                            const point = context.raw;
                                            return [
                                                `Tokens: ${point.y.toLocaleString()}`,
                                                `Input: ${point.input_tokens.toLocaleString()}`,
                                                `Output: ${point.output_tokens.toLocaleString()}`,
                                                `Cost: $${point.cost}`,
                                                `Project: ${point.project}`,
                                                point.params_preview ? `"${point.params_preview}"` : ''
                                            ].filter(Boolean);
                                        }
                                    }
                                },
                                legend: {
                                    display: true,
                                    position: 'bottom',
                                    labels: {
                                        usePointStyle: true,
                                        pointStyle: 'circle'
                                    }
                                }
                            },
                            onClick: function(event, elements) {
                                if (elements.length > 0) {
                                    const element = elements[0];
                                    const datasetIndex = element.datasetIndex;
                                    const index = element.index;
                                    const point = this.data.datasets[datasetIndex].data[index];
                                    const toolName = chartData.datasets[datasetIndex].label;
                                    const invocationId = point.invocation_id;
                                    if (invocationId && toolName) {
                                        htmx.ajax('GET', '/api/tool/' + encodeURIComponent(toolName) + '/invocation/' + encodeURIComponent(invocationId), {target: '#unified-invocation-detail', swap: 'innerHTML'});
                                    }
                                }
                            }
                        }
                    });

                    // Range slider functionality
                    const rangeMin = document.getElementById('rangeMin');
                    const rangeMax = document.getElementById('rangeMax');
                    const rangeHighlight = document.getElementById('rangeHighlight');
                    const rangeStartLabel = document.getElementById('rangeStartLabel');
                    const rangeEndLabel = document.getElementById('rangeEndLabel');
                    const resetZoomBtn = document.getElementById('resetZoomBtn');

                    function formatDate(timestamp) {
                        const d = new Date(timestamp);
                        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + 
                               ' ' + d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
                    }

                    function updateRangeHighlight() {
                        const minVal = parseInt(rangeMin.value);
                        const maxVal = parseInt(rangeMax.value);
                        rangeHighlight.style.left = minVal + '%';
                        rangeHighlight.style.width = (maxVal - minVal) + '%';
                    }

                    function updateChart() {
                        const minPercent = parseInt(rangeMin.value) / 100;
                        const maxPercent = parseInt(rangeMax.value) / 100;
                        
                        const newMin = minTime + (timeRange * minPercent);
                        const newMax = minTime + (timeRange * maxPercent);
                        
                        chart.options.scales.x.min = newMin;
                        chart.options.scales.x.max = newMax;
                        chart.update('none');
                        
                        rangeStartLabel.textContent = formatDate(newMin);
                        rangeEndLabel.textContent = formatDate(newMax);
                        updateRangeHighlight();
                    }

                    // Prevent handles from crossing
                    rangeMin.addEventListener('input', function() {
                        if (parseInt(rangeMin.value) >= parseInt(rangeMax.value) - 5) {
                            rangeMin.value = parseInt(rangeMax.value) - 5;
                        }
                        updateChart();
                    });

                    rangeMax.addEventListener('input', function() {
                        if (parseInt(rangeMax.value) <= parseInt(rangeMin.value) + 5) {
                            rangeMax.value = parseInt(rangeMin.value) + 5;
                        }
                        updateChart();
                    });

                    resetZoomBtn.addEventListener('click', function() {
                        rangeMin.value = 0;
                        rangeMax.value = 100;
                        updateChart();
                    });

                    // Initialize labels
                    updateChart();
                });
            });
        })();
        </script>

        <!-- Invocation Detail Panel -->
        <div id="unified-invocation-detail" class="mt-6"></div>

        <!-- Toggle for Table View -->
        <div class="mt-6 border-t border-gray-200 pt-4">
            <button 
                @click="showTable = !showTable"
                class="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900"
            >
                <svg class="w-4 h-4 transition-transform" :class="showTable ? 'rotate-90' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
                <span x-text="showTable ? 'Hide table view' : 'Show table view'"></span>
            </button>

            <!-- Table View -->
            <div x-show="showTable" x-cloak class="mt-4">
                <div class="overflow-x-auto max-h-96 overflow-y-auto">
                    <table class="min-w-full divide-y divide-gray-200 text-sm">
                        <thead class="bg-gray-50 sticky top-0">
                            <tr>
                                <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Time</th>
                                <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tool</th>
                                <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Details</th>
                                <th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Tokens</th>
                                <th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Cost</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            {% for inv in timeline.invocations|reverse %}
                            <tr class="hover:bg-gray-50 cursor-pointer"
                                hx-get="/api/tool/{{ inv.tool_name }}/invocation/{{ inv.invocation_id|urlencode }}"
                                hx-target="#unified-invocation-detail"
                                hx-swap="innerHTML">
                                <td class="px-3 py-2 whitespace-nowrap text-gray-500">
                                    {{ inv.x.split('T')[1][:8] if inv.x and 'T' in inv.x else inv.x }}
                                </td>
                                <td class="px-3 py-2 whitespace-nowrap">
                                    <span class="inline-flex items-center gap-1.5">
                                        <span class="w-2 h-2 rounded-full" style="background-color: {{ {
                                            'Read': '#3B82F6',
                                            'Write': '#10B981',
                                            'Edit': '#F59E0B',
                                            'Bash': '#6366F1',
                                            'Glob': '#8B5CF6',
                                            'Grep': '#EC4899',
                                            'Task': '#EF4444',
                                            'WebFetch': '#06B6D4',
                                            'TodoWrite': '#84CC16',
                                            'TodoRead': '#22C55E'
                                        }.get(inv.tool_name, '#6B7280') }};"></span>
                                        {{ inv.tool_name }}
                                    </span>
                                </td>
                                <td class="px-3 py-2 text-gray-600 truncate max-w-xs" title="{{ inv.params_preview }}">
                                    {{ inv.params_preview|truncate(40) if inv.params_preview else '-' }}
                                </td>
                                <td class="px-3 py-2 text-right text-gray-900">
                                    {{ inv.y|format_compact }}
                                </td>
                                <td class="px-3 py-2 text-right text-[#0770E3]">
                                    ${{ "%.4f"|format(inv.cost) }}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        {% else %}
        <div class="text-center py-12 text-gray-500">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
            </svg>
            <p class="mt-2">No tool invocations found</p>
        </div>
        {% endif %}
    </div>
</div>
