<!-- Tool Invocation Detail Panel -->
<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden" x-data="{ activeTab: 'timeline', selectedSession: null }">
    <!-- Header -->
    <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
        <div>
            <div class="flex items-center gap-3">
                <div class="flex-shrink-0 h-10 w-10 flex items-center justify-center bg-[#0770E3] bg-opacity-10 rounded-lg">
                    <svg class="h-6 w-6 text-[#0770E3]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                    </svg>
                </div>
                <h3 class="text-lg font-semibold text-gray-900">{{ tool.tool_name }}</h3>
            </div>
            <p class="text-sm text-gray-500 mt-1">Tool Usage Details</p>
        </div>
        <button 
            onclick="document.getElementById('tool-detail-panel').innerHTML = ''"
            class="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
        </button>
    </div>

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

    <!-- Tab Navigation -->
    <div class="border-b border-gray-200">
        <nav class="flex -mb-px px-6" aria-label="Tabs">
            <button @click="activeTab = 'timeline'" 
                :class="activeTab === 'timeline' ? 'border-[#0770E3] text-[#0770E3]' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                class="py-3 px-4 border-b-2 font-medium text-sm transition-colors">
                Timeline
            </button>
            <button @click="activeTab = 'sessions'; selectedSession = null" 
                :class="activeTab === 'sessions' ? 'border-[#0770E3] text-[#0770E3]' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                class="py-3 px-4 border-b-2 font-medium text-sm transition-colors">
                Conversations
            </button>
            <button @click="activeTab = 'tokens'" 
                :class="activeTab === 'tokens' ? 'border-[#0770E3] text-[#0770E3]' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                class="py-3 px-4 border-b-2 font-medium text-sm transition-colors">
                Token Breakdown
            </button>
        </nav>
    </div>

    <!-- Tab Content -->
    <div class="p-6">
        <!-- Timeline Tab -->
        <div x-show="activeTab === 'timeline'" x-cloak>
            {% if chart_data and chart_data.datasets %}
            <!-- Timeline Chart -->
            <div class="mb-6">
                <div class="flex items-center justify-between mb-4">
                    <h4 class="font-medium text-gray-900">Invocation Timeline</h4>
                    <p class="text-sm text-gray-500">Click a point to see invocation details</p>
                </div>
                <div class="h-64">
                    <canvas id="toolTimelineChart-{{ tool.tool_name|replace(' ', '_')|replace('/', '_') }}"></canvas>
                </div>
            </div>

            <script>
            (function() {
                const chartId = 'toolTimelineChart-{{ tool.tool_name|replace(' ', '_')|replace('/', '_') }}';
                const existing = Chart.getChart(chartId);
                if (existing) existing.destroy();

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

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

                        // 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,
                                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,
                        }));

                        new Chart(ctx, {
                            type: 'bubble',
                            data: { datasets },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                scales: {
                                    x: {
                                        type: 'time',
                                        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: {
                                            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: false
                                    }
                                },
                                onClick: function(event, elements) {
                                    if (elements.length > 0) {
                                        const element = elements[0];
                                        const datasetIndex = element.datasetIndex;
                                        const index = element.index;
                                        const invocationId = this.data.datasets[datasetIndex].data[index].invocation_id;
                                        if (invocationId) {
                                            htmx.ajax('GET', '/api/tool/{{ tool.tool_name }}/invocation/' + encodeURIComponent(invocationId), {target: '#tool-invocation-detail', swap: 'innerHTML'});
                                        }
                                    }
                                }
                            }
                        });
                    });
                });
            })();
            </script>
            {% else %}
            <div class="text-center py-8 text-gray-500">
                <p>No timeline data available</p>
            </div>
            {% endif %}

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

        <!-- Sessions Tab -->
        <div x-show="activeTab === 'sessions'" x-cloak>
            <!-- Session Selector Timeline -->
            <div class="mb-6">
                <h4 class="font-medium text-gray-900 mb-3">Select a conversation to view details</h4>
                <div class="space-y-2 max-h-96 overflow-y-auto">
                    {% for session in tool.sessions %}
                    <div 
                        @click="selectedSession = selectedSession === '{{ session.session_id }}' ? null : '{{ session.session_id }}'"
                        :class="selectedSession === '{{ session.session_id }}' ? 'border-[#0770E3] bg-blue-50' : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'"
                        class="p-4 border rounded-lg cursor-pointer transition-colors">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <div class="flex-shrink-0">
                                    <div class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center">
                                        <svg class="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                                        </svg>
                                    </div>
                                </div>
                                <div>
                                    <div class="text-sm font-medium text-gray-900">{{ session.project_name }}</div>
                                    <div class="text-xs text-gray-500">{{ session.last_timestamp[:10] }} {{ session.last_timestamp[11:19] }}</div>
                                </div>
                            </div>
                            <div class="text-right">
                                <div class="text-sm font-medium text-gray-900">{{ session.invocation_count }} calls</div>
                                <div class="text-xs text-gray-500">{{ session.total_tokens|format_compact }} tokens</div>
                                <div class="text-xs text-[#0770E3] font-medium">${{ "%.4f"|format(session.cost) }}</div>
                            </div>
                        </div>
                        
                        <!-- Expanded session detail -->
                        <div x-show="selectedSession === '{{ session.session_id }}'" x-cloak class="mt-4 pt-4 border-t border-gray-200">
                            <!-- Token breakdown for this session -->
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                                <div class="bg-gray-50 rounded p-2 text-center">
                                    <div class="text-xs text-gray-500">Input</div>
                                    <div class="text-sm font-medium">{{ session.input_tokens|format_compact }}</div>
                                </div>
                                <div class="bg-gray-50 rounded p-2 text-center">
                                    <div class="text-xs text-gray-500">Output</div>
                                    <div class="text-sm font-medium">{{ session.output_tokens|format_compact }}</div>
                                </div>
                                <div class="bg-gray-50 rounded p-2 text-center">
                                    <div class="text-xs text-gray-500">Cache Read</div>
                                    <div class="text-sm font-medium">{{ session.cache_read_tokens|format_compact }}</div>
                                </div>
                                <div class="bg-gray-50 rounded p-2 text-center">
                                    <div class="text-xs text-gray-500">Cache Write</div>
                                    <div class="text-sm font-medium">{{ session.cache_write_tokens|format_compact }}</div>
                                </div>
                            </div>
                            
                            <!-- Invocation timeline -->
                            <div class="text-xs text-gray-500 mb-2">Invocation Timeline</div>
                            <div class="space-y-1 max-h-40 overflow-y-auto">
                                {% for inv in session.invocations %}
                                <div class="flex items-center justify-between py-1 px-2 bg-gray-50 rounded text-xs">
                                    <span class="text-gray-500">{{ inv.time }}</span>
                                    <span class="text-gray-700">{{ inv.total_tokens|format_compact }} tokens</span>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- Token Breakdown Tab -->
        <div x-show="activeTab === 'tokens'" x-cloak>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Total Token Usage -->
                <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                    <h4 class="font-medium text-gray-900 mb-4 flex items-center gap-2">
                        <svg class="w-5 h-5 text-[#0770E3]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        Token Distribution
                    </h4>
                    
                    <!-- Token Bar Chart -->
                    <div class="space-y-3">
                        {% set max_tokens = [tool.input_tokens, tool.output_tokens, tool.cache_read_tokens, tool.cache_write_tokens]|max %}
                        
                        <div>
                            <div class="flex justify-between text-sm mb-1">
                                <span class="text-gray-600">Input</span>
                                <span class="font-medium">{{ tool.input_tokens|format_compact }}</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-blue-500 h-2 rounded-full" style="width: {{ (tool.input_tokens / max_tokens * 100) if max_tokens > 0 else 0 }}%"></div>
                            </div>
                        </div>
                        
                        <div>
                            <div class="flex justify-between text-sm mb-1">
                                <span class="text-gray-600">Output</span>
                                <span class="font-medium">{{ tool.output_tokens|format_compact }}</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-green-500 h-2 rounded-full" style="width: {{ (tool.output_tokens / max_tokens * 100) if max_tokens > 0 else 0 }}%"></div>
                            </div>
                        </div>
                        
                        <div>
                            <div class="flex justify-between text-sm mb-1">
                                <span class="text-gray-600">Cache Read</span>
                                <span class="font-medium">{{ tool.cache_read_tokens|format_compact }}</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-purple-500 h-2 rounded-full" style="width: {{ (tool.cache_read_tokens / max_tokens * 100) if max_tokens > 0 else 0 }}%"></div>
                            </div>
                        </div>
                        
                        <div>
                            <div class="flex justify-between text-sm mb-1">
                                <span class="text-gray-600">Cache Write</span>
                                <span class="font-medium">{{ tool.cache_write_tokens|format_compact }}</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-amber-500 h-2 rounded-full" style="width: {{ (tool.cache_write_tokens / max_tokens * 100) if max_tokens > 0 else 0 }}%"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Total -->
                    <div class="mt-4 pt-3 border-t border-gray-200">
                        <div class="flex justify-between">
                            <span class="font-medium text-gray-900">Total Tokens</span>
                            <span class="font-bold text-gray-900">{{ tool.total_tokens|format_compact }}</span>
                        </div>
                    </div>
                </div>

                <!-- Per-Session Breakdown -->
                <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                    <h4 class="font-medium text-gray-900 mb-4 flex items-center gap-2">
                        <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4z"></path>
                        </svg>
                        Usage by Conversation
                    </h4>
                    
                    <div class="space-y-3 max-h-64 overflow-y-auto">
                        {% set session_max = tool.sessions|map(attribute='total_tokens')|max if tool.sessions else 1 %}
                        {% for session in tool.sessions[:10] %}
                        <div>
                            <div class="flex justify-between text-sm mb-1">
                                <span class="text-gray-600 truncate" title="{{ session.project_name }}">{{ session.project_name }}</span>
                                <span class="font-medium">{{ session.total_tokens|format_compact }}</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-[#0770E3] h-2 rounded-full" style="width: {{ (session.total_tokens / session_max * 100) if session_max > 0 else 0 }}%"></div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>

            <!-- Token Legend -->
            <div class="mt-6 flex flex-wrap justify-center gap-4 text-sm">
                <div class="flex items-center gap-2">
                    <div class="w-3 h-3 rounded-full bg-blue-500"></div>
                    <span class="text-gray-600">Input</span>
                </div>
                <div class="flex items-center gap-2">
                    <div class="w-3 h-3 rounded-full bg-green-500"></div>
                    <span class="text-gray-600">Output</span>
                </div>
                <div class="flex items-center gap-2">
                    <div class="w-3 h-3 rounded-full bg-purple-500"></div>
                    <span class="text-gray-600">Cache Read</span>
                </div>
                <div class="flex items-center gap-2">
                    <div class="w-3 h-3 rounded-full bg-amber-500"></div>
                    <span class="text-gray-600">Cache Write</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer with metadata -->
    <div class="px-6 py-3 bg-gray-50 border-t border-gray-200 text-xs text-gray-500 flex flex-wrap gap-4">
        <span><strong>Tool:</strong> {{ tool.tool_name }}</span>
        <span><strong>Sessions:</strong> {{ tool.session_count }}</span>
        <span><strong>Total Calls:</strong> {{ tool.total_invocations }}</span>
    </div>
</div>
