<!--
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>

<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/prompt-analytics') }}" class="btn btn-secondary" style="text-decoration: none;">
            🧠 Prompt Analytics
        </a>
        {% if is_config_admin %}
        <a href="{{ url_for(request, '/dashboard/traffic-visits') }}" class="btn btn-secondary" style="text-decoration: none;">
            👣 Traffic &amp; Visits
        </a>
        {% endif %}
        <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>

<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 &amp; 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 &amp; 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>

<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;">
        <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="">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="">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="">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="">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="">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" 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 }},
    isConfigAdmin: {{ 'true' if is_config_admin else 'false' }},
    dashboardVisitSeries: {{ dashboard_visit_series|default('[]')|safe }},
    promptAnalysisSeries: {{ prompt_analysis_series|default('[]')|safe }}
};
</script>

<script>
const BASE_PATH = {{ request.scope.get('root_path', '') | tojson }};

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

document.getElementById('timeRangeSelect').addEventListener('change', function() {
    const customRange = document.getElementById('customDateRange');
    customRange.style.display = this.value === 'custom' ? 'flex' : 'none';
});

{% 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) {
                userSelect.value = '';
                userSelect.disabled = true;
                userSelect.style.opacity = '0.5';
                userSelect.style.cursor = 'not-allowed';
            } else {
                userSelect.disabled = false;
                userSelect.style.opacity = '1';
                userSelect.style.cursor = 'pointer';
            }
        });
        if (globalOnlyCheckbox.checked) {
            userSelect.disabled = true;
            userSelect.style.opacity = '0.5';
            userSelect.style.cursor = 'not-allowed';
        }
    }
})();
{% endif %}

{% 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;

    if (analyticsData.selectedUser) {
        const user = analyticsData.availableUsers.find(u => u.id == analyticsData.selectedUser);
        if (user) {
            searchInput.value = user.username + (user.role === 'admin' ? ' (admin)' : '');
        }
    }

    async function searchUsers(query) {
        try {
            const response = await fetch(`${BASE_PATH}/api/users/search?q=${encodeURIComponent(query)}`);
            const data = await response.json();
            return data.users || [];
        } catch (error) {
            console.error('Error searching users:', error);
            return [];
        }
    }

    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';

        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';
            });
        });
    }

    searchInput.addEventListener('input', function() {
        const query = this.value.trim();
        clearTimeout(debounceTimer);

        if (query.length === 0) {
            resultsDiv.innerHTML = '<div class="user-result-item" data-user-id="" data-username="" style="padding: 10px; cursor: pointer; border-bottom: 1px solid #2a4a7a;">All Users</div>';
            resultsDiv.style.display = 'block';
            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);
    });

    searchInput.addEventListener('focus', function() {
        if (this.value.trim().length === 0) {
            resultsDiv.innerHTML = '<div class="user-result-item" data-user-id="" data-username="" style="padding: 10px; cursor: pointer; border-bottom: 1px solid #2a4a7a;">All Users</div>';
            resultsDiv.style.display = 'block';
            document.querySelector('.user-result-item').addEventListener('click', function() {
                searchInput.value = '';
                hiddenInput.value = '';
                selectedUserId = null;
                resultsDiv.style.display = 'none';
            });
        }
    });

    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !resultsDiv.contains(e.target)) {
            resultsDiv.style.display = 'none';
        }
    });

    const globalOnlyCheckbox = document.getElementById('globalOnlyCheckbox');
    if (globalOnlyCheckbox) {
        globalOnlyCheckbox.addEventListener('change', function() {
            if (this.checked) {
                searchInput.value = '';
                hiddenInput.value = '';
                selectedUserId = null;
                searchInput.disabled = true;
                searchInput.style.opacity = '0.5';
                searchInput.style.cursor = 'not-allowed';
            } else {
                searchInput.disabled = false;
                searchInput.style.opacity = '1';
                searchInput.style.cursor = 'text';
            }
        });

        if (globalOnlyCheckbox.checked) {
            searchInput.disabled = true;
            searchInput.style.opacity = '0.5';
            searchInput.style.cursor = 'not-allowed';
        }
    }
})();
{% endif %}

</script>

<div>
    <h3 style="margin-bottom: 15px;">Provider Statistics</h3>
    {% if provider_stats %}
    <table>
        <tr>
            <th>Provider</th>
            <th>Model</th>
            <th>Rotation</th>
            <th>Autoselect</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 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 %}
        <tr style="background:var(--bg-accent); font-weight: bold;">
            <td><strong>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>
    </table>

    <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>
    {% 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>
        </div>
        <div style="background: #3498db; color: white; padding: 20px; border-radius: 8px;">
            <h4 style="font-size: 14px; margin-bottom: 10px;">Combined Savings Estimate</h4>
            <p style="font-size: 28px; font-weight: bold;">{{ currency_symbol }}{{ "%.2f"|format((optimization_savings.total_cost_saved if optimization_savings else 0) or 0) }}</p>
        </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>
        </div>
        <div style="background: #16a085; color: white; padding: 20px; border-radius: 8px;">
            <h4 style="font-size: 14px; margin-bottom: 10px;">Total Combined Estimate</h4>
            <p style="font-size: 28px; font-weight: bold;">${{ "%.2f"|format(optimization_savings.total_cost_saved) }}</p>
        </div>
        <div style="background: #1abc9c; color: white; padding: 20px; border-radius: 8px;">
            <h4 style="font-size: 14px; margin-bottom: 10px;">Cache / Batching Savings</h4>
            <p style="font-size: 28px; font-weight: bold;">${{ "%.2f"|format((optimization_savings.direct_feature_savings.cost_saved if optimization_savings else 0) or 0) }}</p>
        </div>
        <div style="background: #2980b9; color: white; padding: 20px; border-radius: 8px;">
            <h4 style="font-size: 14px; margin-bottom: 10px;">Free-Tier Equivalent</h4>
            <p style="font-size: 28px; font-weight: bold;">${{ "%.2f"|format((optimization_savings.free_tier_equivalent_savings.cost_saved if optimization_savings else 0) or 0) }}</p>
        </div>
    </div>
    <p style="color: var(--color-muted); margin-top: -6px; margin-bottom: 18px;">The combined estimate includes direct execution savings from response caching and batching plus free-tier/subscription-equivalent avoided cost estimates.</p>
    {% else %}
    <p style="color: var(--color-muted);">No optimization savings recorded yet. Increase usage on providers with known upstream free tiers, or enable deduplication, condensation, batching, or caching to see savings.</p>
    {% endif %}

    <h3 style="margin-top: 30px; margin-bottom: 15px;">Model Performance</h3>
    {% if model_performance %}
    <table>
        <tr>
            <th>Provider</th>
            <th>Model</th>
            <th>Type</th>
            <th>Context Size</th>
            <th>Condense %</th>
            <th>Condense Method</th>
            <th>Tokens/Day</th>
            <th>Error Rate</th>
            <th>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</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>
    {% else %}
    <p style="color: var(--color-muted);">No token usage data available for the selected period.</p>
    {% endif %}

    {% 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 }}</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>{{ e.hit_pct }}%</td>
                <td>{{ format_tokens(e.tokens) }}</td>
                <td>{{ e.token_pct }}%</td>
                <td>{% 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 %}

    {% 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 }}</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>{{ e.hit_pct }}%</td>
                <td>{{ format_tokens(e.tokens) }}</td>
                <td>{{ e.token_pct }}%</td>
                <td>{% 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 %}

{% 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; margin-bottom: 30px;">
    <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>
{% endif %}

<div style="margin-top: 30px; display: flex; gap: 10px; flex-wrap: wrap;">
    <a href="{{ url_for(request, '/dashboard') }}" class="btn btn-secondary" data-i18n="analytics_page.back">Back to Dashboard</a>
    <a href="{{ url_for(request, '/dashboard/analytics/provider-quotas') }}" class="btn btn-secondary">Provider Quota Debug</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>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>
<script>
function showProviderDetails(providerId, modelName, rotationId, autoselectId, tpm, tph, tpd) {
    const modal = document.getElementById('providerModal');
    const content = document.getElementById('modalContent');
    if (!modal || !content) return;
    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>
    `;
    modal.style.display = 'block';
}

function closeProviderModal() {
    const modal = document.getElementById('providerModal');
    if (modal) modal.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();
}

window.onclick = function(event) {
    const modal = document.getElementById('providerModal');
    if (modal && event.target == modal) {
        closeProviderModal();
    }
}

const tokenData = {{ token_over_time|safe }};
if (document.getElementById('tokenChart') && tokenData.length) {
    const providers = [...new Set(tokenData.map(d => d.provider_id || 'all'))];
    if (providers.length > 1) {
        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, backgroundColor: colors[i % colors.length], borderColor: colors[i % colors.length], fill: false, tension: 0.1 };
        });
        new Chart(document.getElementById('tokenChart'), {
            type: 'line',
            data: { datasets },
            options: { responsive: true, scales: { x: { type: 'time', time: { unit: 'hour' }, title: { display: true, text: 'Time' } }, y: { beginAtZero: true, title: { display: true, text: 'Tokens' } } } }
        });
    } else {
        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: 'hour' }, title: { display: true, text: 'Time' } }, y: { beginAtZero: true, title: { display: true, text: 'Tokens' } } } }
        });
    }
}

if (document.getElementById('promptAnalysisChart') && analyticsData.promptAnalysisSeries.length) {
    new Chart(document.getElementById('promptAnalysisChart'), {
        type: 'line',
        data: {
            datasets: [
                { label: 'Runs', data: analyticsData.promptAnalysisSeries.map(d => ({x: d.bucket, y: d.runs})), borderColor: '#2563eb', backgroundColor: 'rgba(37,99,235,0.10)', fill: true, tension: 0.2 },
                { label: 'High Risk', data: analyticsData.promptAnalysisSeries.map(d => ({x: d.bucket, y: d.high_risk})), borderColor: '#f59e0b', backgroundColor: 'rgba(245,158,11,0.08)', fill: false, tension: 0.2 },
                { label: 'Blocked', data: analyticsData.promptAnalysisSeries.map(d => ({x: d.bucket, y: d.blocked})), borderColor: '#dc2626', backgroundColor: 'rgba(220,38,38,0.08)', fill: false, tension: 0.2 }
            ]
        },
        options: { responsive: true, scales: { x: { type: 'time', time: { unit: 'hour' }, title: { display: true, text: 'Time' } }, y: { beginAtZero: true, title: { display: true, text: 'Count' } } } }
    });
}

if (analyticsData.isConfigAdmin && document.getElementById('dashboardVisitChart') && analyticsData.dashboardVisitSeries.length) {
    new Chart(document.getElementById('dashboardVisitChart'), {
        type: 'line',
        data: {
            datasets: [
                { label: 'Events', data: analyticsData.dashboardVisitSeries.map(d => ({x: d.bucket, y: d.events})), borderColor: '#1f6feb', backgroundColor: 'rgba(31,111,235,0.12)', fill: true, tension: 0.2 },
                { label: 'Unique IPs', data: analyticsData.dashboardVisitSeries.map(d => ({x: d.bucket, y: d.unique_ips})), borderColor: '#0f766e', backgroundColor: 'rgba(15,118,110,0.08)', fill: false, tension: 0.2 },
                { label: 'Unique Visitors', data: analyticsData.dashboardVisitSeries.map(d => ({x: d.bucket, y: d.unique_visitors})), borderColor: '#7c3aed', backgroundColor: 'rgba(124,58,237,0.08)', fill: false, tension: 0.2 }
            ]
        },
        options: { responsive: true, scales: { x: { type: 'time', time: { unit: 'hour' }, title: { display: true, text: 'Time' } }, y: { beginAtZero: true, title: { display: true, text: 'Count' } } } }
    });
}

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(`${BASE_PATH}/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>
{% endblock %}
