<!--
Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->
{% extends "base.html" %}

{% block title %}Analytics - AISBF Dashboard{% endblock %}

{% macro format_tokens(value) %}
{% if value is none or value == 0 %}0{% else %}
{% set val = value | float %}
{% if val >= 1000000000 %}
{{ "%.2f"|format(val / 1000000000) }}B
{% elif val >= 1000000 %}
{{ "%.2f"|format(val / 1000000) }}M
{% elif val >= 1000 %}
{{ "%.2f"|format(val / 1000) }}K
{% else %}
{{ value }}
{% endif %}
{% endif %}
{% endmacro %}

{% block content %}
<h2 style="margin-bottom: 30px;">Token Usage Analytics</h2>

<!-- Quick Links Navigation -->
<div style="background: var(--bg-page); padding: 15px; border-radius: 8px; margin-bottom: 30px;">
    <div style="display: flex; gap: 15px; flex-wrap: wrap;">
        <a href="{{ url_for(request, '/dashboard/analytics') }}" class="btn" style="text-decoration: none;">
            📊 Analytics
        </a>
        <a href="{{ url_for(request, '/dashboard/response-cache') }}" class="btn btn-secondary" style="text-decoration: none;">
            💾 Response Cache
        </a>
        <a href="{{ url_for(request, '/dashboard/rate-limits') }}" class="btn btn-secondary" style="text-decoration: none;">
            ⏱️ Rate Limits
        </a>
    </div>
</div>

<!-- Date Range Filter Section -->
<div style="background: var(--bg-page); padding: 20px; border-radius: 8px; margin-bottom: 30px;">
    <h3 style="margin-bottom: 15px;">Filter by Date Range</h3>
    <form method="get" action="{{ url_for(request, "/dashboard/analytics") }}" style="display: flex; flex-wrap: wrap; gap: 15px; align-items: flex-end;">
        <div style="flex: 1; min-width: 200px;">
            <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">Time Range</label>
            <select name="time_range" id="timeRangeSelect" style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
                <option value="1h" {% if selected_time_range == '1h' %}selected{% endif %}>Last 1 Hour</option>
                <option value="6h" {% if selected_time_range == '6h' %}selected{% endif %}>Last 6 Hours</option>
                <option value="24h" {% if selected_time_range == '24h' %}selected{% endif %}>Last 24 Hours (Default)</option>
                <option value="yesterday" {% if selected_time_range == 'yesterday' %}selected{% endif %}>Yesterday</option>
                <option value="7d" {% if selected_time_range == '7d' %}selected{% endif %}>Last 7 Days</option>
                <option value="30d" {% if selected_time_range == '30d' %}selected{% endif %}>Last 30 Days</option>
                <option value="90d" {% if selected_time_range == '90d' %}selected{% endif %}>Last 90 Days</option>
                <option value="custom" {% if selected_time_range == 'custom' %}selected{% endif %}>Custom Range</option>
            </select>
        </div>
        
        <div id="customDateRange" style="display: {% if selected_time_range == 'custom' or from_date %}flex{% else %}none{% endif %}; flex-wrap: wrap; gap: 15px; flex: 2;">
            <div style="flex: 1; min-width: 200px;">
                <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">From Date & Time</label>
                <input type="datetime-local" name="from_date" value="{{ from_date or '' }}" 
                       style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
            </div>
            <div style="flex: 1; min-width: 200px;">
                <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">To Date & Time</label>
                <input type="datetime-local" name="to_date" value="{{ to_date or '' }}" 
                       style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
            </div>
        </div>
        
        <div>
            <button type="submit" style="padding: 10px 20px; background: var(--color-primary); color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: bold;">
                Apply Filter
            </button>
        </div>
    </form>
    
    {% if from_date or to_date %}
    <div style="margin-top: 15px; padding: 10px; background:var(--bg-accent); border-radius: 4px;">
        <strong style="color: var(--color-link);">Selected Range: </strong>
        <span style="color: var(--color-text);">
            {% if from_date %}{{ from_date }}{% else %}Beginning{% endif %}
            to 
            {% if to_date %}{{ to_date }}{% else %}Now{% endif %}
        </span>
        {% if date_range_usage %}
        <span style="margin-left: 20px; color: var(--color-muted);">
            | Total: {{ format_tokens(date_range_usage.total_tokens) }} tokens | Estimated Cost: {{ currency_symbol }}{{ "%.2f"|format(date_range_usage.estimated_cost) }}
        </span>
        {% endif %}
    </div>
    {% endif %}
</div>

<!-- Filter by Provider/Model/Rotation/Autoselect -->
<div style="background: var(--bg-page); padding: 20px; border-radius: 8px; margin-bottom: 30px;">
    <h3 style="margin-bottom: 15px;">Filter by Provider, Model, Rotation, Autoselect, or User</h3>
    <form method="get" action="{{ url_for(request, "/dashboard/analytics") }}" style="display: flex; flex-wrap: wrap; gap: 15px; align-items: flex-end;">
        <!-- Preserve date filter parameters -->
        <input type="hidden" name="time_range" value="{{ selected_time_range }}">
        {% if from_date %}<input type="hidden" name="from_date" value="{{ from_date }}">{% endif %}
        {% if to_date %}<input type="hidden" name="to_date" value="{{ to_date }}">{% endif %}
        
        <div style="flex: 1; min-width: 150px;">
            <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">Provider</label>
            <select name="provider_filter" style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
                <option value="" data-i18n="analytics_page.all_providers">All Providers</option>
                {% for provider in available_providers %}
                <option value="{{ provider }}" {% if selected_provider == provider %}selected{% endif %}>{{ provider }}</option>
                {% endfor %}
            </select>
        </div>
        
        <div style="flex: 1; min-width: 150px;">
            <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">Model</label>
            <select name="model_filter" style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
                <option value="" data-i18n="analytics_page.all_models">All Models</option>
                {% for model in available_models %}
                <option value="{{ model }}" {% if selected_model == model %}selected{% endif %}>{{ model }}</option>
                {% endfor %}
            </select>
        </div>
        
        <div style="flex: 1; min-width: 150px;">
            <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">Rotation</label>
            <select name="rotation_filter" style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
                <option value="" data-i18n="analytics_page.all_rotations">All Rotations</option>
                {% for rotation in available_rotations %}
                <option value="{{ rotation }}" {% if selected_rotation == rotation %}selected{% endif %}>{{ rotation }}</option>
                {% endfor %}
            </select>
        </div>
        
        <div style="flex: 1; min-width: 150px;">
            <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">Autoselect</label>
            <select name="autoselect_filter" style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
                <option value="" data-i18n="analytics_page.all_autoselects">All Autoselects</option>
                {% for autoselect in available_autoselects %}
                <option value="{{ autoselect }}" {% if selected_autoselect == autoselect %}selected{% endif %}>{{ autoselect }}</option>
                {% endfor %}
            </select>
        </div>
        
        {% if is_admin %}
        <div style="flex: 1; min-width: 150px;">
            <label style="display: block; margin-bottom: 5px; color: var(--color-muted); font-size: 14px;">User</label>
            {% if available_users|length < 25 %}
            <select name="user_filter" id="userFilterSelect" style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
                <option value="" data-i18n="analytics_page.all_users">All Users</option>
                {% for user in available_users %}
                <option value="{{ user.id }}" {% if selected_user == user.id %}selected{% endif %}>{{ user.username }}{% if user.role == 'admin' %} (admin){% endif %}</option>
                {% endfor %}
            </select>
            {% else %}
            <div style="position: relative;">
                <input type="text" id="userSearchInput" data-i18n="analytics_page.search_users_placeholder" placeholder="Search users..." autocomplete="off"
                       style="width: 100%; padding: 10px; border-radius: 4px; background:var(--bg-accent); color: white; border: 1px solid #2a4a7a;">
                <input type="hidden" name="user_filter" id="userFilterValue" value="{{ selected_user or '' }}">
                <div id="userSearchResults" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background:var(--bg-accent); border: 1px solid #2a4a7a; border-top: none; border-radius: 0 0 4px 4px; max-height: 300px; overflow-y: auto; z-index: 1000;">
                </div>
            </div>
            {% endif %}
        </div>
        
        <div style="flex: 1; min-width: 150px; display: flex; align-items: center;">
            <label style="display: flex; align-items: center; color: var(--color-text); cursor: pointer; user-select: none;">
                <input type="checkbox" name="global_only" value="1" id="globalOnlyCheckbox" {% if global_only == '1' %}checked{% endif %}
                       style="margin-right: 8px; width: 18px; height: 18px; cursor: pointer;">
                <span style="font-size: 14px;">Global requests only</span>
            </label>
        </div>
        {% endif %}
        
        <div>
            <button type="submit" style="padding: 10px 20px; background: var(--color-link); color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: bold;">
                Apply Filters
            </button>
        </div>
        
        {% if selected_provider or selected_model or selected_rotation or selected_autoselect or selected_user %}
        <div>
            <a href="{{ url_for(request, "/dashboard/analytics?time_range=%s%s%s"|format(selected_time_range, "&from_date=" + from_date if from_date else "", "&to_date=" + to_date if to_date else "")) }}" style="padding: 10px 20px; background: var(--color-secondary); color: var(--color-text); border: none; border-radius: 4px; text-decoration: none; display: inline-block;">
                Clear Filters
            </a>
        </div>
        {% endif %}
    </form>
    
    {% if selected_provider or selected_model or selected_rotation or selected_autoselect or selected_user %}
    <div style="margin-top: 15px; padding: 10px; background:var(--bg-accent); border-radius: 4px;">
        <strong style="color: var(--color-link);">Active Filters: </strong>
        <span style="color: var(--color-text);">
            {% if selected_provider %}Provider: {{ selected_provider }}{% endif %}
            {% if selected_model %}{% if selected_provider %} | {% endif %}Model: {{ selected_model }}{% endif %}
            {% if selected_rotation %}{% if selected_provider or selected_model %} | {% endif %}Rotation: {{ selected_rotation }}{% endif %}
            {% if selected_autoselect %}{% if selected_provider or selected_model or selected_rotation %} | {% endif %}Autoselect: {{ selected_autoselect }}{% endif %}
            {% if selected_user %}{% if selected_provider or selected_model or selected_rotation or selected_autoselect %} | {% endif %}User: {% for user in available_users %}{% if user.id == selected_user %}{{ user.username }}{% endif %}{% endfor %}{% endif %}
        </span>
    </div>
    {% endif %}
</div>

<script>
const analyticsData = {
    selectedUser: {{ selected_user or 'null' }},
    availableUsers: {{ available_users|tojson }}
};
</script>

<script>
document.getElementById('timeRangeSelect').addEventListener('change', function() {
    var customRange = document.getElementById('customDateRange');
    if (this.value === 'custom') {
        customRange.style.display = 'flex';
    } else {
        customRange.style.display = 'none';
    }
});

// Handle global_only checkbox for select dropdown (when < 25 users)
{% if is_admin and available_users|length < 25 %}
(function() {
    const userSelect = document.getElementById('userFilterSelect');
    const globalOnlyCheckbox = document.getElementById('globalOnlyCheckbox');
    
    if (globalOnlyCheckbox && userSelect) {
        globalOnlyCheckbox.addEventListener('change', function() {
            if (this.checked) {
                // When global_only is checked, clear user filter and disable select
                userSelect.value = '';
                userSelect.disabled = true;
                userSelect.style.opacity = '0.5';
                userSelect.style.cursor = 'not-allowed';
            } else {
                // Re-enable user select
                userSelect.disabled = false;
                userSelect.style.opacity = '1';
                userSelect.style.cursor = 'pointer';
            }
        });
        
        // Initialize state on page load
        if (globalOnlyCheckbox.checked) {
            userSelect.disabled = true;
            userSelect.style.opacity = '0.5';
            userSelect.style.cursor = 'not-allowed';
        }
    }
})();
{% endif %}

function escHtml(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

// User search autocomplete functionality
{% if is_admin and available_users|length >= 25 %}
(function() {
    const searchInput = document.getElementById('userSearchInput');
    const resultsDiv = document.getElementById('userSearchResults');
    const hiddenInput = document.getElementById('userFilterValue');
    let debounceTimer;
    let selectedUserId = analyticsData.selectedUser;

    // Set initial display value if a user is selected
    if (analyticsData.selectedUser) {
        const user = analyticsData.availableUsers.find(u => u.id == analyticsData.selectedUser);
        if (user) {
            searchInput.value = user.username + (user.role === 'admin' ? ' (admin)' : '');
        }
    }
    
    // Search users via API
    async function searchUsers(query) {
        try {
            const response = await fetch(`/api/users/search?q=${encodeURIComponent(query)}`);
            const data = await response.json();
            return data.users || [];
        } catch (error) {
            console.error('Error searching users:', error);
            return [];
        }
    }
    
    // Display search results
    function displayResults(users) {
        if (users.length === 0) {
            resultsDiv.innerHTML = '<div style="padding: 10px; color: var(--color-muted);">No users found</div>';
            resultsDiv.style.display = 'block';
            return;
        }
        
        resultsDiv.innerHTML = users.map(user => `
            <div class="user-result-item" data-user-id="${user.id}" data-username="${escHtml(user.username)}" data-role="${escHtml(user.role)}"
                 style="padding: 10px; cursor: pointer; border-bottom: 1px solid #2a4a7a;">
                ${escHtml(user.username)}${user.role === 'admin' ? ' <span style="color: var(--color-link);">(admin)</span>' : ''}
            </div>
        `).join('');
        resultsDiv.style.display = 'block';
        
        // Add click handlers
        document.querySelectorAll('.user-result-item').forEach(item => {
            item.addEventListener('mouseenter', function() {
                this.style.background = 'var(--color-secondary-hover)';
            });
            item.addEventListener('mouseleave', function() {
                this.style.background = '';
            });
            item.addEventListener('click', function() {
                const userId = this.dataset.userId;
                const username = this.dataset.username;
                const role = this.dataset.role;
                
                searchInput.value = username + (role === 'admin' ? ' (admin)' : '');
                hiddenInput.value = userId;
                selectedUserId = userId;
                resultsDiv.style.display = 'none';
            });
        });
    }
    
    // Handle input
    searchInput.addEventListener('input', function() {
        const query = this.value.trim();
        
        clearTimeout(debounceTimer);
        
        if (query.length === 0) {
            // Show all users option
            resultsDiv.innerHTML = '<div class="user-result-item" data-user-id="" data-username=window.i18n.t('analytics.all_users') style="padding: 10px; cursor: pointer; border-bottom: 1px solid #2a4a7a;">All Users</div>';
            resultsDiv.style.display = 'block';
            
            document.querySelector('.user-result-item').addEventListener('mouseenter', function() {
                this.style.background = 'var(--color-secondary-hover)';
            });
            document.querySelector('.user-result-item').addEventListener('mouseleave', function() {
                this.style.background = '';
            });
            document.querySelector('.user-result-item').addEventListener('click', function() {
                searchInput.value = '';
                hiddenInput.value = '';
                selectedUserId = null;
                resultsDiv.style.display = 'none';
            });
            return;
        }
        
        debounceTimer = setTimeout(async () => {
            const users = await searchUsers(query);
            displayResults(users);
        }, 300);
    });
    
    // Handle focus
    searchInput.addEventListener('focus', function() {
        if (this.value.trim().length === 0) {
            resultsDiv.innerHTML = '<div class="user-result-item" data-user-id="" data-username=window.i18n.t('analytics.all_users') style="padding: 10px; cursor: pointer; border-bottom: 1px solid #2a4a7a;">All Users</div>';
            resultsDiv.style.display = 'block';
            
            document.querySelector('.user-result-item').addEventListener('mouseenter', function() {
                this.style.background = 'var(--color-secondary-hover)';
            });
            document.querySelector('.user-result-item').addEventListener('mouseleave', function() {
                this.style.background = '';
            });
            document.querySelector('.user-result-item').addEventListener('click', function() {
                searchInput.value = '';
                hiddenInput.value = '';
                selectedUserId = null;
                resultsDiv.style.display = 'none';
            });
        }
    });
    
    // Close results when clicking outside
    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !resultsDiv.contains(e.target)) {
            resultsDiv.style.display = 'none';
        }
    });
    
    // Handle global_only checkbox interaction
    const globalOnlyCheckbox = document.getElementById('globalOnlyCheckbox');
    if (globalOnlyCheckbox) {
        globalOnlyCheckbox.addEventListener('change', function() {
            if (this.checked) {
                // When global_only is checked, clear user filter
                searchInput.value = '';
                hiddenInput.value = '';
                selectedUserId = null;
                searchInput.disabled = true;
                searchInput.style.opacity = '0.5';
                searchInput.style.cursor = 'not-allowed';
            } else {
                // Re-enable user search
                searchInput.disabled = false;
                searchInput.style.opacity = '1';
                searchInput.style.cursor = 'text';
            }
        });
        
        // Initialize state on page load
        if (globalOnlyCheckbox.checked) {
            searchInput.disabled = true;
            searchInput.style.opacity = '0.5';
            searchInput.style.cursor = 'not-allowed';
        }
    }
})();
{% endif %}
</script>

{% if recommendations %}
<h3 style="margin-bottom: 15px;">Optimization Recommendations</h3>
<div style="margin-bottom: 30px;">
    {% for rec in recommendations %}
    <div style="background: {% if rec.severity == 'high' %}#3a1a1a{% elif rec.severity == 'medium' %}#3a2a1a{% else %}#1a2a3a{% endif %}; 
                padding: 15px; border-radius: 4px; margin-bottom: 10px; 
                border: 1px solid {% if rec.severity == 'high' %}#ef4444{% elif rec.severity == 'medium' %}#f39c12{% else %}#3b82f6{% endif %};">
        <strong style="color: {% if rec.severity == 'high' %}#f87171{% elif rec.severity == 'medium' %}#fcd34d{% else %}#60a5fa{% endif %};">
            {{ rec.type|replace('_', ' ')|title }}
        </strong>
        <p style="margin: 5px 0;">{{ rec.message }}</p>
        <small style="color: var(--color-muted);">{{ rec.action }}</small>
    </div>
    {% endfor %}
</div>
{% endif %}

<h3 style="margin-bottom: 15px;">Provider Statistics</h3>
{% if provider_stats %}
<table>
    <tr>
        <th data-i18n="analytics_page.col_provider">Provider</th>
        <th>Model</th>
        <th>Rotation</th>
        <th>Autoselect</th>
        <th data-i18n="analytics_page.col_total_requests">Total Requests</th>
        <th data-i18n="analytics_page.col_success">Success</th>
        <th data-i18n="analytics_page.col_errors">Errors</th>
        <th data-i18n="analytics_page.col_error_rate">Error Rate</th>
        <th data-i18n="analytics_page.col_avg_latency">Avg Latency</th>
        <th data-i18n="analytics_page.col_input_tokens">Input Tokens</th>
        <th data-i18n="analytics_page.col_output_tokens">Output Tokens</th>
        <th data-i18n="analytics_page.col_total_tokens">Total Tokens</th>
    </tr>
    {% for provider in provider_stats %}
    <tr style="cursor: pointer;" onclick="showProviderDetails('{{ provider.provider_id }}', '{{ provider.model_name or '' }}', '{{ provider.rotation_id or '' }}', '{{ provider.autoselect_id or '' }}', {{ provider.tokens.TPM }}, {{ provider.tokens.TPH }}, {{ provider.tokens.TPD }})">
        <td><strong>{{ provider.provider_id }}</strong></td>
        <td>{{ provider.model_name or '' }}</td>
        <td>{{ provider.rotation_id or '' }}</td>
        <td>{{ provider.autoselect_id or '' }}</td>
        <td>{{ provider.requests.total }}</td>
        <td>{{ provider.requests.success }}</td>
        <td>{{ provider.requests.error }}</td>
        <td {% if provider.error_rate > 0.1 %}style="color: #f87171;"{% endif %}>
            {{ "%.1f"|format(provider.error_rate * 100) }}%
        </td>
        <td {% if provider.avg_latency_ms > 5000 %}style="color: #fcd34d;"{% endif %}>
            {% if provider.avg_latency_ms > 1000 %}{{ "%.1f"|format(provider.avg_latency_ms / 1000) }}s{% else %}{{ "%.0f"|format(provider.avg_latency_ms) }}ms{% endif %}
        </td>
        <td><strong>{{ format_tokens(provider.tokens.prompt or 0) }}</strong></td>
        <td><strong>{{ format_tokens(provider.tokens.completion or 0) }}</strong></td>
        <td><strong>{{ format_tokens(provider.tokens.total or 0) }}</strong></td>
    </tr>
    {% endfor %}
    {% if provider_stats %}
    <tr style="background:var(--bg-accent); font-weight: bold;">
        <td><strong data-i18n="analytics_page.total">Total</strong></td>
        <td></td><td></td><td></td>
        <td>{{ provider_stats | sum(attribute='requests.total') }}</td>
        <td>{{ provider_stats | sum(attribute='requests.success') }}</td>
        <td>{{ provider_stats | sum(attribute='requests.error') }}</td>
        <td>
            {% set total_requests = provider_stats | sum(attribute='requests.total') %}
            {% set total_errors = provider_stats | sum(attribute='requests.error') %}
            {% if total_requests > 0 %}
                {{ "%.1f"|format((total_errors / total_requests) * 100) }}%
            {% else %}
                0.0%
            {% endif %}
        </td>
        <td>
            {% set total_requests = provider_stats | sum(attribute='requests.total') %}
            {% if total_requests > 0 %}
                {% set weighted_sum = namespace(value=0) %}
                {% for provider in provider_stats %}
                    {% set weighted_sum.value = weighted_sum.value + (provider.avg_latency_ms | float * provider.requests.total) %}
                {% endfor %}
                {% set avg_latency = weighted_sum.value / total_requests %}
                {% if avg_latency > 1000 %}{{ "%.1f"|format(avg_latency / 1000) }}s{% else %}{{ "%.0f"|format(avg_latency) }}ms{% endif %}
            {% else %}
                N/A
            {% endif %}
        </td>
        <td><strong>{{ format_tokens(provider_stats | sum(attribute='tokens.prompt') or 0) }}</strong></td>
        <td><strong>{{ format_tokens(provider_stats | sum(attribute='tokens.completion') or 0) }}</strong></td>
        <td><strong>{{ format_tokens(provider_stats | sum(attribute='tokens.total') or 0) }}</strong></td>
    </tr>
    {% endif %}
</table>

<!-- Modal for provider details -->
<div id="providerModal" style="display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6);">
    <div style="background-color: var(--bg-page); margin: 10% auto; padding: 30px; border: 1px solid #888; border-radius: 8px; width: 60%; max-width: 600px;">
        <span onclick="closeProviderModal()" style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer;">&times;</span>
        <h3 style="margin-top: 0;">Provider Rate Details</h3>
        <div id="modalContent"></div>
    </div>
</div>

<script>
function showProviderDetails(providerId, modelName, rotationId, autoselectId, tpm, tph, tpd) {
    const modal = document.getElementById('providerModal');
    const content = document.getElementById('modalContent');
    
    let title = '<strong>' + providerId + '</strong>';
    if (modelName) title += ' / ' + modelName;
    if (rotationId) title += ' (Rotation: ' + rotationId + ')';
    if (autoselectId) title += ' (Autoselect: ' + autoselectId + ')';
    
    content.innerHTML = `
        <p style="margin-bottom: 20px;">${title}</p>
        <table style="width: 100%;">
            <tr>
                <th style="text-align: left; padding: 10px; background: var(--bg-accent);">Metric</th>
                <th style="text-align: right; padding: 10px; background: var(--bg-accent);">Value</th>
            </tr>
            <tr>
                <td style="padding: 10px;">Tokens per Minute</td>
                <td style="padding: 10px; text-align: right;"><strong>${formatTokens(tpm)}</strong></td>
            </tr>
            <tr>
                <td style="padding: 10px;">Tokens per Hour</td>
                <td style="padding: 10px; text-align: right;"><strong>${formatTokens(tph)}</strong></td>
            </tr>
            <tr>
                <td style="padding: 10px;">Tokens per Day</td>
                <td style="padding: 10px; text-align: right;"><strong>${formatTokens(tpd)}</strong></td>
            </tr>
        </table>
        <p style="margin-top: 20px; color: var(--color-muted); font-size: 14px;">
            These rates are calculated based on the selected time range and filters.
        </p>
    `;
    
    modal.style.display = 'block';
}

function closeProviderModal() {
    document.getElementById('providerModal').style.display = 'none';
}

function formatTokens(value) {
    if (!value || value === 0) return '0';
    const val = parseFloat(value);
    if (val >= 1000000000) return (val / 1000000000).toFixed(2) + 'B';
    if (val >= 1000000) return (val / 1000000).toFixed(2) + 'M';
    if (val >= 1000) return (val / 1000).toFixed(2) + 'K';
    return value.toString();
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('providerModal');
    if (event.target == modal) {
        closeProviderModal();
    }
}
</script>

{% else %}
<p style="color: var(--color-muted);">No provider statistics available yet. Make API requests to see analytics.</p>
{% endif %}

<h3 style="margin-top: 30px; margin-bottom: 15px;">Cost Overview</h3>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
    <div style="background: #2ecc71; color: white; padding: 20px; border-radius: 8px;">
        <h4 style="font-size: 14px; margin-bottom: 10px;">
            {% if from_date or to_date %}Selected Period Cost{% else %}Today's Estimated Cost{% endif %}
        </h4>
        <p style="font-size: 28px; font-weight: bold;">{{ currency_symbol }}{{ "%.2f"|format(cost_overview.total_estimated_cost_today) }}</p>
        {% if cost_overview.date_range %}
        <small style="color: rgba(255,255,255,0.8);">
            {{ cost_overview.date_range.start[:10] }} to {{ cost_overview.date_range.end[:10] }}
        </small>
        {% endif %}
    </div>
    
    <div style="background: #3498db; color: white; padding: 20px; border-radius: 8px;">
        <h4 style="font-size: 14px; margin-bottom: 10px;">💰 Estimated Savings</h4>
        <p style="font-size: 28px; font-weight: bold;" id="savings-amount">{{ currency_symbol }}0.00</p>
        <small style="color: rgba(255,255,255,0.8);">From cache hits & optimization</small>
    </div>
    
    {% for pc in cost_overview.providers %}
    <div style="background:var(--bg-accent); padding: 15px; border-radius: 8px;">
        <h4 style="font-size: 14px; margin-bottom: 5px;">{{ pc.provider_id }}</h4>
        <p style="font-size: 20px; font-weight: bold;">${{ "%.2f"|format(pc.estimated_cost) }}</p>
        <small style="color: var(--color-muted);">{{ format_tokens(pc.tokens_today) }} tokens</small>
    </div>
    {% endfor %}
</div>

<h3 style="margin-top: 30px; margin-bottom: 15px;">Optimization Savings</h3>
{% if optimization_savings and optimization_savings.total_tokens_saved > 0 %}
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px;">
    <div style="background: #27ae60; color: white; padding: 20px; border-radius: 8px;">
        <h4 style="font-size: 14px; margin-bottom: 10px;">Total Tokens Saved</h4>
        <p style="font-size: 28px; font-weight: bold;">{{ format_tokens(optimization_savings.total_tokens_saved) }}</p>
        {% if optimization_savings.date_range %}
        <small style="color: rgba(255,255,255,0.8);">
            {{ optimization_savings.date_range.start[:10] }} to {{ optimization_savings.date_range.end[:10] }}
        </small>
        {% endif %}
    </div>
    <div style="background: #16a085; color: white; padding: 20px; border-radius: 8px;">
        <h4 style="font-size: 14px; margin-bottom: 10px;">Total Cost Saved</h4>
        <p style="font-size: 28px; font-weight: bold;">${{ "%.2f"|format(optimization_savings.total_cost_saved) }}</p>
        <small style="color: rgba(255,255,255,0.8);">From optimizations</small>
    </div>
</div>

{% if optimization_savings.savings_by_type %}
<table>
    <tr>
        <th data-i18n="analytics_page.col_opt_type">Optimization Type</th>
        <th data-i18n="analytics_page.col_count">Count</th>
        <th data-i18n="analytics_page.col_tokens_saved">Tokens Saved</th>
        <th data-i18n="analytics_page.col_cost_saved">Cost Saved</th>
        <th data-i18n="analytics_page.col_avg_tokens_opt">Avg Tokens/Optimization</th>
        <th data-i18n="analytics_page.col_max_tokens_saved">Max Tokens Saved</th>
    </tr>
    {% for opt_type, stats in optimization_savings.savings_by_type.items() %}
    <tr>
        <td><strong>{{ opt_type.title() }}</strong></td>
        <td>{{ stats.count }}</td>
        <td>{{ format_tokens(stats.tokens_saved) }}</td>
        <td>${{ "%.4f"|format(stats.cost_saved) }}</td>
        <td>{{ format_tokens(stats.avg_tokens_saved) }}</td>
        <td>{{ format_tokens(stats.max_tokens_saved) }}</td>
    </tr>
    {% endfor %}
    <tr style="background:var(--bg-accent); font-weight: bold;">
        <td><strong data-i18n="analytics_page.total">Total</strong></td>
        <td>{{ optimization_savings.savings_by_type.values() | sum(attribute='count') }}</td>
        <td>{{ format_tokens(optimization_savings.total_tokens_saved) }}</td>
        <td>${{ "%.4f"|format(optimization_savings.total_cost_saved) }}</td>
        <td>-</td>
        <td>-</td>
    </tr>
</table>
{% endif %}
{% else %}
<p style="color: var(--color-muted);">No optimization savings recorded yet. Enable deduplication, condensation, batching, or caching to see savings.</p>
{% endif %}

<script>
// Fetch and display savings estimation
fetch('{{ url_for(request, "/dashboard/response-cache/stats") }}')
    .then(response => response.json())
    .then(data => {
        if (data.enabled && data.hits > 0) {
            // Estimate savings: assume average cost of $0.002 per cached request
            const avgCostPerRequest = 0.002;
            const estimatedSavings = data.hits * avgCostPerRequest;
            document.getElementById('savings-amount').textContent = '{{ currency_symbol }}' + estimatedSavings.toFixed(2);
        }
    })
    .catch(error => {
        console.error('Error fetching cache stats:', error);
    });
</script>

<h3 style="margin-top: 30px; margin-bottom: 15px;">Model Performance</h3>
{% if model_performance %}
<table>
    <tr>
        <th data-i18n="analytics_page.col_provider">Provider</th>
        <th data-i18n="analytics_page.col_model">Model</th>
        <th data-i18n="analytics_page.col_type">Type</th>
        <th data-i18n="analytics_page.col_context_size">Context Size</th>
        <th>Condense %</th>
        <th data-i18n="analytics_page.col_condense_method">Condense Method</th>
        <th data-i18n="analytics_page.col_tpd">Tokens/Day</th>
        <th data-i18n="analytics_page.col_error_rate">Error Rate</th>
        <th data-i18n="analytics_page.col_avg_latency">Avg Latency</th>
    </tr>
    {% for model in model_performance %}
    <tr>
        <td>{{ model.provider_id }}</td>
        <td>{{ model.model_name }}</td>
        <td>
            {% if model.is_rotation %}
            <span style="color: #f39c12;">Rotation: {{ model.rotation_id }}</span>
            {% elif model.is_autoselect %}
            <span style="color: #9b59b6;">Autoselect: {{ model.autoselect_id }}</span>
            {% else %}
            <span style="color: #3498db;">{{ model.provider_type|title }}</span>
            {% endif %}
        </td>
        <td>{{ model.context_size|default('N/A') }}</td>
        <td>{{ model.condense_context|default('N/A') }}%</td>
        <td>{{ model.condense_method|default('None') }}</td>
        <td>{{ format_tokens(model.tokens_per_day) }}</td>
        <td {% if model.error_rate > 0.1 %}style="color: #f87171;"{% endif %}>
            {{ "%.1f"|format(model.error_rate * 100) }}%
        </td>
        <td {% if model.avg_latency_ms > 5000 %}style="color: #fcd34d;"{% endif %}>
            {% if model.avg_latency_ms > 1000 %}{{ "%.1f"|format(model.avg_latency_ms / 1000) }}s{% else %}{{ "%.0f"|format(model.avg_latency_ms) }}ms{% endif %}
        </td>
    </tr>
    {% endfor %}
</table>
{% else %}
<p style="color: var(--color-muted);">No model performance data available yet.</p>
{% endif %}

<h3 style="margin-top: 30px; margin-bottom: 15px;">
    Token Usage Over Time 
    {% if from_date or to_date %}
        (Custom Range)
    {% elif selected_time_range == '1h' %}
        (Last 1 Hour)
    {% elif selected_time_range == '6h' %}
        (Last 6 Hours)
    {% elif selected_time_range == '24h' %}
        (Last 24 Hours)
    {% elif selected_time_range == 'yesterday' %}
        (Yesterday)
    {% elif selected_time_range == '7d' %}
        (Last 7 Days)
    {% elif selected_time_range == '30d' %}
        (Last 30 Days)
    {% elif selected_time_range == '90d' %}
        (Last 90 Days)
    {% else %}
        (Last 24 Hours)
    {% endif %}
</h3>
{% if token_over_time != '[]' %}
<div style="background: var(--bg-page); padding: 20px; border-radius: 8px;">
    <canvas id="tokenChart" style="width: 100%; height: 300px;"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>
<script>
    const tokenData = {{ token_over_time|safe }};
    
    // Group by provider if multiple
    const providers = [...new Set(tokenData.map(d => d.provider_id || 'all'))];
    
    if (providers.length > 1) {
        // Multiple providers - show stacked
        const datasets = providers.map((provider, i) => {
            const colors = ['#e94560', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c'];
            const data = tokenData.filter(d => (d.provider_id || 'all') === provider).map(d => ({
                x: d.timestamp,
                y: d.tokens
            }));
            return {
                label: provider,
                data: data,
                backgroundColor: colors[i % colors.length],
                borderColor: colors[i % colors.length],
                fill: false,
                tension: 0.1
            };
        });
        
        new Chart(document.getElementById('tokenChart'), {
            type: 'line',
            data: { datasets: datasets },
            options: {
                responsive: true,
                scales: {
                    x: { 
                        type: 'time', 
                        time: { 
                            unit: {% if selected_time_range == '1h' or selected_time_range == '6h' %}'hour'{% elif selected_time_range == '24h' %}'hour'{% elif selected_time_range == '7d' %}'day'{% else %}'day'{% endif %}
                        },
                        title: { display: true, text: 'Time' }
                    },
                    y: { beginAtZero: true, title: { display: true, text: 'Tokens' } }
                }
            }
        });
    } else {
        // Single provider
        new Chart(document.getElementById('tokenChart'), {
            type: 'line',
            data: {
                datasets: [{
                    label: 'Tokens Used',
                    data: tokenData.map(d => ({x: d.timestamp, y: d.tokens})),
                    borderColor: '#e94560',
                    backgroundColor: 'rgba(233, 69, 96, 0.1)',
                    fill: true,
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    x: { 
                        type: 'time',
                        time: { 
                            unit: {% if selected_time_range == '1h' or selected_time_range == '6h' %}'hour'{% elif selected_time_range == '24h' %}'hour'{% elif selected_time_range == '7d' %}'day'{% else %}'day'{% endif %}
                        },
                        title: { display: true, text: 'Time' }
                    },
                    y: { beginAtZero: true, title: { display: true, text: 'Tokens' } }
                }
            }
        });
    }
</script>
{% else %}
<p style="color: var(--color-muted);">No token usage data available for the selected period.</p>
{% endif %}

<!-- Rotation Breakdown -->
{% if rotation_breakdown %}
<h3 style="margin-top: 30px; margin-bottom: 15px;">Rotation Breakdown</h3>
{% for rot in rotation_breakdown %}
<div style="background: var(--bg-page); padding: 15px; border-radius: 8px; margin-bottom: 20px;">
    <h4 style="margin: 0 0 10px 0; color: #f39c12;">⟳ {{ rot.rotation_id }}
        <span style="font-weight: normal; font-size: 13px; color: var(--color-muted); margin-left: 10px;">
            {{ rot.total_requests }} requests · {{ format_tokens(rot.total_tokens) }} tokens
        </span>
    </h4>
    <table>
        <tr>
            <th>Provider</th>
            <th>Model</th>
            <th>Requests</th>
            <th>Hit %</th>
            <th>Tokens</th>
            <th>Token %</th>
            <th>Avg Latency</th>
        </tr>
        {% for e in rot.entries %}
        <tr>
            <td>{{ e.provider_id }}</td>
            <td>{{ e.model_name or '' }}</td>
            <td>{{ e.requests }}</td>
            <td>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="background: #2a4a7a; border-radius: 4px; width: 80px; height: 8px; overflow: hidden;">
                        <div style="background: #f39c12; width: {{ e.hit_pct }}%; height: 100%;"></div>
                    </div>
                    {{ e.hit_pct }}%
                </div>
            </td>
            <td>{{ format_tokens(e.tokens) }}</td>
            <td>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="background: #2a4a7a; border-radius: 4px; width: 80px; height: 8px; overflow: hidden;">
                        <div style="background: #3498db; width: {{ e.token_pct }}%; height: 100%;"></div>
                    </div>
                    {{ e.token_pct }}%
                </div>
            </td>
            <td {% if e.avg_latency_ms > 5000 %}style="color: #fcd34d;"{% endif %}>
                {% if e.avg_latency_ms > 1000 %}{{ "%.1f"|format(e.avg_latency_ms / 1000) }}s{% else %}{{ "%.0f"|format(e.avg_latency_ms) }}ms{% endif %}
            </td>
        </tr>
        {% endfor %}
    </table>
</div>
{% endfor %}
{% endif %}

<!-- Autoselect Breakdown -->
{% if autoselect_breakdown %}
<h3 style="margin-top: 30px; margin-bottom: 15px;">Autoselect Breakdown</h3>
{% for asel in autoselect_breakdown %}
<div style="background: var(--bg-page); padding: 15px; border-radius: 8px; margin-bottom: 20px;">
    <h4 style="margin: 0 0 10px 0; color: #9b59b6;">⚡ {{ asel.autoselect_id }}
        <span style="font-weight: normal; font-size: 13px; color: var(--color-muted); margin-left: 10px;">
            {{ asel.total_requests }} requests · {{ format_tokens(asel.total_tokens) }} tokens
        </span>
    </h4>
    <table>
        <tr>
            <th>Selected Model / Rotation</th>
            <th>Requests</th>
            <th>Hit %</th>
            <th>Tokens</th>
            <th>Token %</th>
            <th>Selection Latency</th>
        </tr>
        {% for e in asel.entries %}
        <tr>
            <td><strong>{{ e.model_name or '(unknown)' }}</strong></td>
            <td>{{ e.requests }}</td>
            <td>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="background: #2a4a7a; border-radius: 4px; width: 80px; height: 8px; overflow: hidden;">
                        <div style="background: #9b59b6; width: {{ e.hit_pct }}%; height: 100%;"></div>
                    </div>
                    {{ e.hit_pct }}%
                </div>
            </td>
            <td>{{ format_tokens(e.tokens) }}</td>
            <td>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="background: #2a4a7a; border-radius: 4px; width: 80px; height: 8px; overflow: hidden;">
                        <div style="background: #3498db; width: {{ e.token_pct }}%; height: 100%;"></div>
                    </div>
                    {{ e.token_pct }}%
                </div>
            </td>
            <td {% if e.avg_latency_ms > 5000 %}style="color: #fcd34d;"{% endif %}>
                {% if e.avg_latency_ms > 1000 %}{{ "%.1f"|format(e.avg_latency_ms / 1000) }}s{% else %}{{ "%.0f"|format(e.avg_latency_ms) }}ms{% endif %}
            </td>
        </tr>
        {% endfor %}
    </table>
</div>
{% endfor %}
{% endif %}

<!-- Internal Models Stats (kiro, kilo, claude CLI, etc.) -->
{% set internal_providers = ['kiro', 'kilo', 'claude', 'codex'] %}
{% set internal_stats = provider_stats | selectattr('provider_id', 'in', internal_providers) | list %}
{% if not internal_stats %}
    {# also catch any provider_id that contains these keywords #}
    {% set internal_stats = [] %}
    {% for p in provider_stats %}
        {% if 'kiro' in p.provider_id or 'kilo' in p.provider_id or 'claude' in p.provider_id %}
            {% set _ = internal_stats.append(p) %}
        {% endif %}
    {% endfor %}
{% endif %}
{% if internal_stats %}
<h3 style="margin-top: 30px; margin-bottom: 15px;">Internal / CLI Provider Stats</h3>
<table>
    <tr>
        <th>Provider</th>
        <th>Model</th>
        <th>Total Requests</th>
        <th>Success</th>
        <th>Errors</th>
        <th>Error Rate</th>
        <th>Avg Latency</th>
        <th>Input Tokens</th>
        <th>Output Tokens</th>
        <th>Total Tokens</th>
    </tr>
    {% for p in internal_stats %}
    <tr>
        <td><strong>{{ p.provider_id }}</strong></td>
        <td>{{ p.model_name or '' }}</td>
        <td>{{ p.requests.total }}</td>
        <td>{{ p.requests.success }}</td>
        <td>{{ p.requests.error }}</td>
        <td {% if p.error_rate > 0.1 %}style="color: #f87171;"{% endif %}>{{ "%.1f"|format(p.error_rate * 100) }}%</td>
        <td {% if p.avg_latency_ms > 5000 %}style="color: #fcd34d;"{% endif %}>
            {% if p.avg_latency_ms > 1000 %}{{ "%.1f"|format(p.avg_latency_ms / 1000) }}s{% else %}{{ "%.0f"|format(p.avg_latency_ms) }}ms{% endif %}
        </td>
        <td>{{ format_tokens(p.tokens.prompt or 0) }}</td>
        <td>{{ format_tokens(p.tokens.completion or 0) }}</td>
        <td><strong>{{ format_tokens(p.tokens.total or 0) }}</strong></td>
    </tr>
    {% endfor %}
</table>
{% endif %}

<!-- Admin: Delete Analytics -->
{% if is_config_admin %}
<h3 style="margin-top: 40px; margin-bottom: 15px; color: #f87171;">⚠ Analytics Management</h3>
<div style="background: var(--bg-page); padding: 20px; border-radius: 8px; border: 1px solid #f87171;">
    <p style="margin: 0 0 15px 0; color: var(--color-muted);">These actions permanently delete analytics data from the database and cannot be undone.</p>
    <div style="display: flex; gap: 15px; flex-wrap: wrap;">
        <button onclick="confirmDeleteAnalytics('global')" class="btn" style="background: #e67e22; border: none; cursor: pointer;">
            🗑 Reset Global Analytics
        </button>
        <button onclick="confirmDeleteAnalytics('all')" class="btn" style="background: #e74c3c; border: none; cursor: pointer;">
            🗑 Reset All Analytics (Global + Users)
        </button>
    </div>
</div>
<script>
function confirmDeleteAnalytics(scope) {
    const msg = scope === 'global'
        ? 'Delete all analytics for global (non-user) providers/models? This cannot be undone.'
        : 'Delete ALL analytics including all user data? This cannot be undone.';
    if (!confirm(msg)) return;
    if (!confirm('Are you sure? This is irreversible.')) return;
    fetch('/api/admin/analytics/delete-' + scope, {method: 'POST'})
        .then(r => r.json())
        .then(d => {
            alert('Deleted ' + d.deleted + ' records.');
            location.reload();
        })
        .catch(e => alert('Error: ' + e));
}
</script>
{% endif %}

<div style="margin-top: 30px; display: flex; gap: 10px; flex-wrap: wrap;">
    <a href="/dashboard" class="btn btn-secondary" data-i18n="analytics_page.back">Back to Dashboard</a>
    {% if is_admin %}
    <a href="{{ url_for(request, '/dashboard/rate-limits') }}" class="btn">Rate Limits</a>
    <a href="{{ url_for(request, '/dashboard/response-cache') }}" class="btn">Response Cache</a>
    {% endif %}
</div>
{% endblock %}