{% from "components/card.html" import stat_card %}

<!-- Summary Cards -->
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-6">
    {{ stat_card(
        label="Total Exchanges",
        value=(summary.total_exchanges|default(0)|int)|string,
        icon='<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path></svg>'
    ) }}

    {{ stat_card(
        label="Total Tokens",
        value=(summary.total_tokens|default(0)|format_compact),
        icon='<svg class="w-6 h-6" 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>'
    ) }}

    {{ stat_card(
        label="Total Cost",
        value="$" + (summary.total_cost|default(0.0)|float|round(2)|string),
        icon='<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>'
    ) }}

    {{ stat_card(
        label="Avg Tokens/Exchange",
        value=(summary.avg_tokens_per_exchange|default(0)|format_compact),
        icon='<svg class="w-6 h-6" 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>'
    ) }}

    {{ stat_card(
        label="Unique Types",
        value=(summary.unique_types|default(0)|int)|string,
        icon='<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>'
    ) }}
</div>

<!-- Sub-Agent Type Breakdown -->
{% if summary.type_breakdown %}
<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mt-8">
    <h3 class="text-lg font-semibold text-gray-900 mb-4">Sub-Agent Types</h3>
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
        {% for type_info in summary.type_breakdown %}
        <div class="p-4 bg-gray-50 rounded-lg border border-gray-200">
            <div class="flex items-center gap-2 mb-2">
                <div class="w-3 h-3 rounded-full {% if type_info.type == 'explore' or type_info.type == 'Explore' %}bg-blue-500{% elif type_info.type == 'general' %}bg-green-500{% else %}bg-purple-500{% endif %}"></div>
                <span class="text-sm font-medium text-gray-900 truncate" title="{{ type_info.type }}">{{ type_info.type }}</span>
            </div>
            <div class="text-2xl font-bold text-gray-900">{{ type_info.count }}</div>
            <div class="text-xs text-gray-500 mt-1">{{ type_info.total_tokens|format_compact }} tokens</div>
            <div class="text-xs text-[#0770E3] font-medium">${{ type_info.total_cost }}</div>
        </div>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- Timeline Chart -->
{% if chart_data.datasets %}
<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mt-8">
    <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-semibold text-gray-900">Sub-Agent Exchanges Timeline</h3>
        <p class="text-sm text-gray-500">Click a point to see details</p>
    </div>
    <div class="h-80">
        <canvas id="subagentTimelineChart"></canvas>
    </div>
</div>

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

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

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

            // Transform data for scatter 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,
                    agent_id: point.agent_id,
                    cost: point.cost,
                    duration: point.duration,
                    description: point.description
                })),
                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: 'day',
                                displayFormats: {
                                    day: 'MMM d'
                                }
                            },
                            title: {
                                display: true,
                                text: 'Date'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Tokens'
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const point = context.raw;
                                    return [
                                        `Type: ${context.dataset.label}`,
                                        `Tokens: ${point.y.toLocaleString()}`,
                                        `Cost: $${point.cost}`,
                                        `Duration: ${point.duration}s`,
                                        point.description ? `"${point.description}"` : ''
                                    ].filter(Boolean);
                                }
                            }
                        },
                        legend: {
                            position: 'bottom'
                        }
                    },
                    onClick: function(event, elements) {
                        if (elements.length > 0) {
                            const element = elements[0];
                            const datasetIndex = element.datasetIndex;
                            const index = element.index;
                            const agentId = this.data.datasets[datasetIndex].data[index].agent_id;
                            if (agentId) {
                                htmx.ajax('GET', '/api/subagent/' + agentId, {target: '#subagent-detail-panel', swap: 'innerHTML'});
                            }
                        }
                    }
                }
            });
        });
    });
})();
</script>
{% endif %}

<!-- Detail Panel (loaded via HTMX) -->
<div id="subagent-detail-panel" class="mt-8"></div>

<!-- Exchanges Table -->
{% if exchanges.exchanges %}
<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mt-8">
    <div class="px-6 py-4 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-900">Recent Sub-Agent Exchanges</h3>
        <p class="text-sm text-gray-500 mt-1">Click a row to see detailed token breakdown</p>
    </div>
    <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Time</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Model</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Description</th>
                    <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Tokens</th>
                    <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Tools</th>
                    <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Duration</th>
                    <th scope="col" class="px-6 py-3 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 exchange in exchanges.exchanges %}
                <tr class="hover:bg-gray-50 transition-colors cursor-pointer"
                    hx-get="/api/subagent/{{ exchange.agent_id }}"
                    hx-target="#subagent-detail-panel"
                    hx-swap="innerHTML"
                    hx-indicator="this">
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        <div>{{ exchange.date }}</div>
                        <div class="text-xs text-gray-400">{{ exchange.time }}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                            {% if exchange.subagent_type == 'explore' or exchange.subagent_type == 'Explore' %}bg-blue-100 text-blue-800
                            {% elif exchange.subagent_type == 'general' %}bg-green-100 text-green-800
                            {% else %}bg-purple-100 text-purple-800{% endif %}">
                            {{ exchange.subagent_type }}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        {% if exchange.model %}
                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                            {% if 'opus' in exchange.model %}bg-amber-100 text-amber-800
                            {% elif 'haiku' in exchange.model %}bg-emerald-100 text-emerald-800
                            {% else %}bg-indigo-100 text-indigo-800{% endif %}"
                            title="{{ exchange.model }}">
                            {{ exchange.model_display }}
                        </span>
                        {% else %}
                        <span class="text-xs text-gray-400">—</span>
                        {% endif %}
                    </td>
                    <td class="px-6 py-4 text-sm text-gray-900 max-w-xs truncate" title="{{ exchange.description }}">
                        {{ exchange.description or exchange.prompt_preview[:50] }}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-right text-gray-900 font-medium">
                        {{ exchange.total_tokens|format_compact }}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-right text-gray-600">
                        {{ exchange.total_tool_use_count }}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-right text-gray-600">
                        {{ exchange.duration_seconds }}s
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-right font-medium text-[#0770E3]">
                        ${{ "%.4f"|format(exchange.cost) }}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% else %}
<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mt-8">
    <div class="px-6 py-12 text-center">
        <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="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
        </svg>
        <p class="mt-2 text-gray-500">No sub-agent exchanges found</p>
        <p class="text-sm text-gray-400 mt-1">Use the Task tool in Claude Code to see sub-agent analytics</p>
    </div>
</div>
{% endif %}
