{% extends "base.html" %}
{% block title %}Statistiken - Admin{% endblock %}

{% block head %}
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
{% endblock %}

{% block content %}
<div class="mb-8">
    <h1 class="text-3xl font-bold text-white mb-2">Statistiken</h1>
    <p class="text-gray-400">API-Nutzung und Kosten</p>
</div>

{% if error %}
<div class="bg-red-900/50 border border-red-500 text-red-200 px-4 py-3 rounded-lg mb-6">
    <strong>Error:</strong> {{ error }}
</div>
{% endif %}

<!-- Filters -->
<div class="flex flex-wrap items-center gap-4 mb-6">
    <!-- Period Selector -->
    <div class="flex gap-2">
        <button onclick="loadStats('today')" id="period-today"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors bg-brand-bg-light text-gray-300 hover:bg-brand-bg">
            Heute
        </button>
        <button onclick="loadStats('week')" id="period-week"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors bg-brand-bg-light text-gray-300 hover:bg-brand-bg">
            7 Tage
        </button>
        <button onclick="loadStats('month')" id="period-month"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors btn-primary">
            30 Tage
        </button>
        <button onclick="loadStats('all')" id="period-all"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors bg-brand-bg-light text-gray-300 hover:bg-brand-bg">
            Gesamt
        </button>
    </div>

    <!-- User/Company Filter -->
    <div class="flex items-center gap-2">
        <label for="entityFilter" class="text-sm text-gray-400">Filter:</label>
        <select id="entityFilter" onchange="onEntityFilterChange()"
                class="input-bg border rounded-lg px-3 py-2 text-sm text-white min-w-[250px]">
            <option value="">Alle</option>
            {% if companies %}
            <optgroup label="Firmen">
                {% for cd in companies %}
                <option value="company:{{ cd.company.id }}">{{ cd.company.name }}</option>
                {% endfor %}
            </optgroup>
            {% endif %}
            {% if ghostwriters %}
            <optgroup label="Ghostwriter">
                {% for gw in ghostwriters %}
                <option value="user:{{ gw.id }}">{{ gw.display_name or gw.email }}</option>
                {% endfor %}
            </optgroup>
            {% endif %}
            {% if companies %}
            <optgroup label="Firmen-Mitglieder">
                {% for cd in companies %}
                    {% for emp in cd.employees %}
                    <option value="user:{{ emp.id }}">{{ emp.display_name or emp.email }} ({{ cd.company.name }})</option>
                    {% endfor %}
                {% endfor %}
            </optgroup>
            {% endif %}
        </select>
    </div>
</div>

<!-- Overview Cards Row 1 -->
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-4">
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-brand-highlight/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Tokens</p>
        <p class="text-xl font-bold text-white" id="stat-tokens">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-green-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-green-400" 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"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Kosten (USD)</p>
        <p class="text-xl font-bold text-white" id="stat-cost">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-blue-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">API Calls</p>
        <p class="text-xl font-bold text-white" id="stat-calls">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-purple-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Erstellt</p>
        <p class="text-xl font-bold text-white" id="stat-created">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-amber-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Freigegeben</p>
        <p class="text-xl font-bold text-white" id="stat-approved">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-emerald-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Veröffentlicht</p>
        <p class="text-xl font-bold text-white" id="stat-published">-</p>
    </div>
</div>

<!-- Overview Cards Row 2 -->
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-8">
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-orange-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Kosten/Post</p>
        <p class="text-xl font-bold text-white" id="stat-avg-cost">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-rose-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-rose-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Monatsprognose</p>
        <p class="text-xl font-bold text-white" id="stat-projection">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-cyan-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Tokens/Post</p>
        <p class="text-xl font-bold text-white" id="stat-avg-tokens">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-amber-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Bis Freigabe</p>
        <p class="text-xl font-bold text-white" id="stat-time-approval">-</p>
    </div>
    <div class="card-bg rounded-xl border p-5 text-center">
        <div class="w-10 h-10 bg-emerald-600/20 rounded-lg flex items-center justify-center mx-auto mb-2">
            <svg class="w-5 h-5 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        </div>
        <p class="text-gray-400 text-xs">Bis Veröffentl.</p>
        <p class="text-xl font-bold text-white" id="stat-time-publish">-</p>
    </div>
</div>

<!-- Charts Row 1 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
    <!-- Daily Token Usage -->
    <div class="card-bg rounded-xl border p-6">
        <h3 class="text-lg font-semibold text-white mb-4">Token-Verbrauch pro Tag</h3>
        <div id="chart-daily-tokens"></div>
    </div>

    <!-- Daily Cost -->
    <div class="card-bg rounded-xl border p-6">
        <h3 class="text-lg font-semibold text-white mb-4">Kosten pro Tag (USD)</h3>
        <div id="chart-daily-cost"></div>
    </div>
</div>

<!-- Charts Row 2 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
    <!-- By Model (Pie) -->
    <div class="card-bg rounded-xl border p-6">
        <h3 class="text-lg font-semibold text-white mb-4">Nutzung nach Modell</h3>
        <div id="chart-by-model"></div>
    </div>

    <!-- By Operation (Bar) -->
    <div class="card-bg rounded-xl border p-6">
        <h3 class="text-lg font-semibold text-white mb-4">Nutzung nach Operation</h3>
        <div id="chart-by-operation"></div>
    </div>
</div>

<!-- Charts Row 3: Posts -->
<div class="grid grid-cols-1 gap-6 mb-6">
    <div class="card-bg rounded-xl border p-6">
        <h3 class="text-lg font-semibold text-white mb-4">Posts pro Tag</h3>
        <div id="chart-posts-daily"></div>
    </div>
</div>

<!-- Post Pipeline Funnel -->
<div class="card-bg rounded-xl border p-6 mb-6">
    <h3 class="text-lg font-semibold text-white mb-4">Post-Pipeline</h3>
    <div class="flex items-center justify-center gap-2">
        <div class="text-center flex-1">
            <div class="bg-purple-600/20 rounded-lg py-4 px-2">
                <p class="text-2xl font-bold text-purple-400" id="funnel-created">-</p>
                <p class="text-xs text-gray-400 mt-1">Erstellt</p>
            </div>
        </div>
        <div class="text-center flex-shrink-0">
            <p class="text-sm font-semibold text-amber-400" id="funnel-approval-rate">-</p>
            <svg class="w-6 h-6 text-gray-500 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
        </div>
        <div class="text-center flex-1">
            <div class="bg-amber-600/20 rounded-lg py-4 px-2">
                <p class="text-2xl font-bold text-amber-400" id="funnel-approved">-</p>
                <p class="text-xs text-gray-400 mt-1">Freigegeben</p>
            </div>
        </div>
        <div class="text-center flex-shrink-0">
            <p class="text-sm font-semibold text-emerald-400" id="funnel-publish-rate">-</p>
            <svg class="w-6 h-6 text-gray-500 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
        </div>
        <div class="text-center flex-1">
            <div class="bg-emerald-600/20 rounded-lg py-4 px-2">
                <p class="text-2xl font-bold text-emerald-400" id="funnel-published">-</p>
                <p class="text-xs text-gray-400 mt-1">Veröffentlicht</p>
            </div>
        </div>
    </div>
</div>

<!-- No Data Message -->
<div id="no-data-msg" class="hidden card-bg rounded-xl border p-8 text-center text-gray-400 mb-6">
    Noch keine API-Nutzungsdaten vorhanden. Statistiken werden automatisch erfasst, sobald Posts erstellt oder Research durchgeführt wird.
</div>
{% endblock %}

{% block scripts %}
<script>
let currentPeriod = 'month';
let filterType = '';   // '' | 'user' | 'company'
let filterId = '';     // UUID
let charts = {};

const chartTheme = {
    chart: { background: 'transparent', foreColor: '#9CA3AF' },
    grid: { borderColor: '#4a5858' },
    tooltip: { theme: 'dark' },
    colors: ['#ffc700', '#60A5FA', '#34D399', '#A78BFA', '#F87171']
};

function formatTokens(n) {
    if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
    if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
    return n.toString();
}

function formatHours(h) {
    if (h === null || h === undefined || h === 0) return '0 Std';
    if (h < 1) return Math.round(h * 60) + ' Min';
    if (h >= 24) return (h / 24).toFixed(1) + ' Tage';
    return h.toFixed(1) + ' Std';
}

function destroyCharts() {
    Object.values(charts).forEach(c => { try { c.destroy(); } catch(e) {} });
    charts = {};
}

function renderCharts(data) {
    destroyCharts();

    const hasData = data.total_calls > 0 || data.total_created > 0;
    document.getElementById('no-data-msg').classList.toggle('hidden', hasData);

    // Update summary cards
    document.getElementById('stat-tokens').textContent = formatTokens(data.total_tokens);
    document.getElementById('stat-cost').textContent = '$' + data.total_cost.toFixed(4);
    document.getElementById('stat-calls').textContent = data.total_calls.toString();
    document.getElementById('stat-created').textContent = (data.total_created || 0).toString();
    document.getElementById('stat-approved').textContent = (data.total_approved || 0).toString();
    document.getElementById('stat-published').textContent = (data.total_published || 0).toString();

    // Derived metrics cards
    document.getElementById('stat-avg-cost').textContent = '$' + (data.avg_cost_per_post || 0).toFixed(4);
    document.getElementById('stat-projection').textContent = '$' + (data.monthly_projection || 0).toFixed(2);
    document.getElementById('stat-avg-tokens').textContent = formatTokens(data.avg_tokens_per_post || 0);
    document.getElementById('stat-time-approval').textContent = formatHours(data.avg_hours_to_approval);
    document.getElementById('stat-time-publish').textContent = formatHours(data.avg_hours_to_publish);

    // Funnel
    document.getElementById('funnel-created').textContent = (data.total_created || 0).toString();
    document.getElementById('funnel-approved').textContent = (data.total_approved || 0).toString();
    document.getElementById('funnel-published').textContent = (data.total_published || 0).toString();
    document.getElementById('funnel-approval-rate').textContent = (data.approval_rate || 0) + '%';
    document.getElementById('funnel-publish-rate').textContent = (data.publish_rate || 0) + '%';

    // Daily tokens line chart (total + per model)
    if (data.daily.length > 0) {
        const tokenSeries = [{ name: 'Gesamt', data: data.daily.map(d => ({ x: d.date, y: d.tokens })) }];
        const costSeries = [{ name: 'Gesamt', data: data.daily.map(d => ({ x: d.date, y: parseFloat(d.cost.toFixed(4)) })) }];
        const modelColors = {
            'gpt-4o': '#60A5FA',
            'gpt-4o-mini': '#A78BFA',
            'claude-sonnet-4.6': '#F59E0B',
            'sonar': '#F87171'
        };

        if (data.daily_by_model) {
            for (const [model, days] of Object.entries(data.daily_by_model)) {
                tokenSeries.push({ name: model, data: days.map(d => ({ x: d.date, y: d.tokens })) });
                costSeries.push({ name: model, data: days.map(d => ({ x: d.date, y: parseFloat(d.cost.toFixed(4)) })) });
            }
        }

        const seriesColors = ['#ffc700'].concat(tokenSeries.slice(1).map(s => modelColors[s.name] || '#9CA3AF'));
        const strokeWidths = [2].concat(tokenSeries.slice(1).map(() => 2));
        // Gesamt = filled gradient, model lines = no fill
        const fillOpacity = [0.3].concat(tokenSeries.slice(1).map(() => 0));

        charts.dailyTokens = new ApexCharts(document.getElementById('chart-daily-tokens'), {
            ...chartTheme,
            chart: { ...chartTheme.chart, type: 'area', height: 300 },
            series: tokenSeries,
            xaxis: { type: 'category', labels: { rotate: -45 } },
            yaxis: { labels: { formatter: formatTokens } },
            stroke: { curve: 'smooth', width: strokeWidths },
            fill: { opacity: fillOpacity },
            colors: seriesColors,
            legend: { position: 'top', labels: { colors: '#9CA3AF' } },
            dataLabels: { enabled: false }
        });
        charts.dailyTokens.render();

        const costColors = ['#34D399'].concat(costSeries.slice(1).map(s => modelColors[s.name] || '#9CA3AF'));

        charts.dailyCost = new ApexCharts(document.getElementById('chart-daily-cost'), {
            ...chartTheme,
            chart: { ...chartTheme.chart, type: 'area', height: 300 },
            series: costSeries,
            xaxis: { type: 'category', labels: { rotate: -45 } },
            yaxis: { labels: { formatter: v => '$' + v.toFixed(4) } },
            stroke: { curve: 'smooth', width: strokeWidths },
            fill: { opacity: fillOpacity },
            colors: costColors,
            legend: { position: 'top', labels: { colors: '#9CA3AF' } },
            dataLabels: { enabled: false }
        });
        charts.dailyCost.render();
    }

    // By model pie chart
    if (data.by_model.length > 0) {
        charts.byModel = new ApexCharts(document.getElementById('chart-by-model'), {
            ...chartTheme,
            chart: { ...chartTheme.chart, type: 'donut', height: 280 },
            series: data.by_model.map(m => m.tokens),
            labels: data.by_model.map(m => m.model),
            legend: { position: 'bottom', labels: { colors: '#9CA3AF' } },
            plotOptions: { pie: { donut: { size: '60%' } } }
        });
        charts.byModel.render();
    }

    // By operation bar chart
    if (data.by_operation.length > 0) {
        charts.byOperation = new ApexCharts(document.getElementById('chart-by-operation'), {
            ...chartTheme,
            chart: { ...chartTheme.chart, type: 'bar', height: 280 },
            series: [{ name: 'Tokens', data: data.by_operation.map(o => o.tokens) }],
            xaxis: { categories: data.by_operation.map(o => o.operation) },
            yaxis: { labels: { formatter: formatTokens } },
            plotOptions: { bar: { borderRadius: 4, horizontal: false } },
            dataLabels: { enabled: false }
        });
        charts.byOperation.render();
    }

    // Posts daily chart (created / approved / published)
    if (data.posts_daily && data.posts_daily.length > 0) {
        charts.postsByDay = new ApexCharts(document.getElementById('chart-posts-daily'), {
            ...chartTheme,
            chart: { ...chartTheme.chart, type: 'bar', height: 300 },
            series: [
                { name: 'Erstellt', data: data.posts_daily.map(d => ({ x: d.date, y: d.created })) },
                { name: 'Freigegeben', data: data.posts_daily.map(d => ({ x: d.date, y: d.approved })) },
                { name: 'Veröffentlicht', data: data.posts_daily.map(d => ({ x: d.date, y: d.published })) }
            ],
            xaxis: { type: 'category', labels: { rotate: -45 } },
            yaxis: { labels: { formatter: v => Math.round(v).toString() }, forceNiceScale: true },
            plotOptions: { bar: { borderRadius: 3, columnWidth: '60%' } },
            colors: ['#A78BFA', '#FBBF24', '#34D399'],
            legend: { position: 'top', labels: { colors: '#9CA3AF' } },
            dataLabels: { enabled: false }
        });
        charts.postsByDay.render();
    }
}

function onEntityFilterChange() {
    const val = document.getElementById('entityFilter').value;
    if (!val) {
        filterType = '';
        filterId = '';
    } else {
        const parts = val.split(':');
        filterType = parts[0];  // 'user' or 'company'
        filterId = parts[1];
    }
    loadStats(currentPeriod);
}

async function loadStats(period) {
    currentPeriod = period;

    // Update period button styles
    ['today', 'week', 'month', 'all'].forEach(p => {
        const btn = document.getElementById('period-' + p);
        btn.className = p === period
            ? 'px-4 py-2 rounded-lg text-sm font-medium transition-colors btn-primary'
            : 'px-4 py-2 rounded-lg text-sm font-medium transition-colors bg-brand-bg-light text-gray-300 hover:bg-brand-bg';
    });

    try {
        let url = `/admin/api/statistics?period=${period}`;
        if (filterType === 'user' && filterId) {
            url += `&user_id=${filterId}`;
        } else if (filterType === 'company' && filterId) {
            url += `&company_id=${filterId}`;
        }
        const resp = await fetch(url);
        const data = await resp.json();
        renderCharts(data);
    } catch (e) {
        console.error('Failed to load stats:', e);
    }
}

// Load initial data
loadStats('month');
</script>
{% endblock %}
