{% extends "base.html" %}
{% block title %}Historico Scanner - Viral Social Pro{% endblock %}
{% block nav_scanner_history %}active{% endblock %}

{% block content %}
<div class="p-4 md:p-6 space-y-6" x-data="scannerHistory()" x-init="load()">

    <!-- Header -->
    <div class="gradient-bg rounded-2xl p-6 md:p-8 text-white">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
                <h1 class="text-2xl md:text-3xl font-bold mb-1">Historico do Scanner</h1>
                <p class="text-indigo-200 text-sm">Acompanhe todos os scans, creditos consumidos e performance por API</p>
            </div>
            <div class="flex gap-2">
                <select x-model="days" @change="load()" class="bg-white/10 border border-white/20 text-white rounded-xl px-4 py-2 text-sm backdrop-blur">
                    <option value="7">7 dias</option>
                    <option value="14">14 dias</option>
                    <option value="30" selected>30 dias</option>
                    <option value="60">60 dias</option>
                    <option value="90">90 dias</option>
                </select>
                <button @click="load()" class="px-4 py-2 bg-white/20 hover:bg-white/30 rounded-xl text-sm font-medium transition backdrop-blur">
                    <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3">
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-white" x-text="data.summary?.credits_today || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Creditos Hoje</div>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-white" x-text="data.summary?.credits_week || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Semana</div>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-white" x-text="data.summary?.credits_month || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Periodo</div>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-white" x-text="data.summary?.total_requests || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Requisicoes</div>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-emerald-400" x-text="data.summary?.total_videos || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Videos</div>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-red-400" x-text="data.summary?.errors || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Erros</div>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-purple-400" x-text="data.summary?.avg_daily || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Media/Dia</div>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="text-2xl font-bold text-amber-400" x-text="data.summary?.cost_per_video || 0"></div>
            <div class="text-xs text-gray-400 mt-1">Cred/Video</div>
        </div>
    </div>

    <!-- Per-Service Breakdown -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <template x-for="(info, svc) in (data.by_service || {})" :key="svc">
            <div class="glass-card rounded-xl p-5">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 rounded-xl flex items-center justify-center"
                         :class="svc === 'scrapecreators' ? 'bg-purple-500/20 text-purple-400' : svc === 'creative_center' ? 'bg-emerald-500/20 text-emerald-400' : svc === 'youtube_api' ? 'bg-red-500/20 text-red-400' : 'bg-blue-500/20 text-blue-400'">
                        <i data-lucide="server" class="w-5 h-5"></i>
                    </div>
                    <div>
                        <h3 class="font-semibold text-white text-sm capitalize" x-text="svc.replace('_', ' ')"></h3>
                        <p class="text-xs text-gray-400" x-text="info.requests + ' requisicoes'"></p>
                    </div>
                </div>
                <div class="grid grid-cols-3 gap-2 text-center">
                    <div class="bg-white/5 rounded-lg p-2">
                        <div class="text-lg font-bold text-white" x-text="info.credits"></div>
                        <div class="text-[10px] text-gray-500">Creditos</div>
                    </div>
                    <div class="bg-white/5 rounded-lg p-2">
                        <div class="text-lg font-bold text-emerald-400" x-text="info.videos"></div>
                        <div class="text-[10px] text-gray-500">Videos</div>
                    </div>
                    <div class="bg-white/5 rounded-lg p-2">
                        <div class="text-lg font-bold text-amber-400" x-text="info.videos > 0 ? (info.credits / info.videos).toFixed(1) : '-'"></div>
                        <div class="text-[10px] text-gray-500">Cred/Vid</div>
                    </div>
                </div>
            </div>
        </template>
        <template x-if="Object.keys(data.by_service || {}).length === 0">
            <div class="glass-card rounded-xl p-8 text-center col-span-full">
                <i data-lucide="database" class="w-12 h-12 text-gray-600 mx-auto mb-3"></i>
                <p class="text-gray-400 text-sm">Nenhum dado de uso ainda. Execute scans para ver os dados.</p>
            </div>
        </template>
    </div>

    <!-- Charts Row -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <!-- Daily Credits Chart -->
        <div class="glass-card rounded-xl p-5">
            <h3 class="font-semibold text-white mb-4 flex items-center gap-2">
                <i data-lucide="bar-chart-3" class="w-5 h-5 text-purple-400"></i>
                Creditos por Dia (por API)
            </h3>
            <div class="h-64">
                <canvas id="dailyChart"></canvas>
            </div>
        </div>

        <!-- Service Pie Chart -->
        <div class="glass-card rounded-xl p-5">
            <h3 class="font-semibold text-white mb-4 flex items-center gap-2">
                <i data-lucide="pie-chart" class="w-5 h-5 text-purple-400"></i>
                Distribuicao por API
            </h3>
            <div class="h-64 flex items-center justify-center">
                <canvas id="serviceChart"></canvas>
            </div>
        </div>

        <!-- Hourly Activity Chart -->
        <div class="glass-card rounded-xl p-5">
            <h3 class="font-semibold text-white mb-4 flex items-center gap-2">
                <i data-lucide="clock" class="w-5 h-5 text-purple-400"></i>
                Atividade por Hora (7 dias)
            </h3>
            <div class="h-64">
                <canvas id="hourlyChart"></canvas>
            </div>
        </div>

        <!-- Videos Found vs Credits Chart -->
        <div class="glass-card rounded-xl p-5">
            <h3 class="font-semibold text-white mb-4 flex items-center gap-2">
                <i data-lucide="activity" class="w-5 h-5 text-purple-400"></i>
                Eficiencia: Videos vs Creditos
            </h3>
            <div class="h-64">
                <canvas id="efficiencyChart"></canvas>
            </div>
        </div>
    </div>

    <!-- History Table -->
    <div class="glass-card rounded-xl overflow-hidden">
        <div class="p-5 border-b border-white/5 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <h3 class="font-semibold text-white flex items-center gap-2">
                <i data-lucide="list" class="w-5 h-5 text-purple-400"></i>
                Historico de Scans
                <span class="text-xs text-gray-400 font-normal" x-text="'(' + (data.total_logs || 0) + ' registros)'"></span>
            </h3>
            <div class="flex gap-2">
                <select x-model="filterService" @change="page=1; load()" class="bg-white/5 border border-white/10 text-gray-300 rounded-lg px-3 py-1.5 text-xs">
                    <option value="">Todas APIs</option>
                    <option value="scrapecreators">ScrapeCreators</option>
                    <option value="creative_center">Creative Center</option>
                    <option value="youtube_api">YouTube API</option>
                    <option value="apify">Apify</option>
                </select>
                <select x-model="filterStatus" @change="page=1; load()" class="bg-white/5 border border-white/10 text-gray-300 rounded-lg px-3 py-1.5 text-xs">
                    <option value="">Todos Status</option>
                    <option value="success">Sucesso</option>
                    <option value="error">Erro</option>
                    <option value="skipped">Pulado</option>
                </select>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="text-left text-gray-400 text-xs border-b border-white/5">
                        <th class="px-4 py-3 font-medium">Data/Hora</th>
                        <th class="px-4 py-3 font-medium">API</th>
                        <th class="px-4 py-3 font-medium">Endpoint</th>
                        <th class="px-4 py-3 font-medium">Keyword</th>
                        <th class="px-4 py-3 font-medium text-center">Creditos</th>
                        <th class="px-4 py-3 font-medium text-center">Videos</th>
                        <th class="px-4 py-3 font-medium text-center">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="log in (data.logs || [])" :key="log.id">
                        <tr class="border-b border-white/5 hover:bg-white/5 transition">
                            <td class="px-4 py-3 text-gray-300 text-xs whitespace-nowrap" x-text="formatDate(log.timestamp)"></td>
                            <td class="px-4 py-3">
                                <span class="px-2 py-0.5 rounded-full text-xs font-medium"
                                      :class="log.service === 'scrapecreators' ? 'bg-purple-500/20 text-purple-300' : log.service === 'creative_center' ? 'bg-emerald-500/20 text-emerald-300' : log.service === 'youtube_api' ? 'bg-red-500/20 text-red-300' : 'bg-blue-500/20 text-blue-300'"
                                      x-text="log.service.replace('_', ' ')"></span>
                            </td>
                            <td class="px-4 py-3 text-gray-400 text-xs max-w-[200px] truncate" x-text="log.endpoint"></td>
                            <td class="px-4 py-3 text-gray-300 text-xs max-w-[150px] truncate" x-text="log.keyword || '-'"></td>
                            <td class="px-4 py-3 text-center">
                                <span class="font-semibold" :class="log.credits_used > 0 ? 'text-amber-400' : 'text-gray-500'" x-text="log.credits_used"></span>
                            </td>
                            <td class="px-4 py-3 text-center text-emerald-400 font-semibold" x-text="log.videos_found"></td>
                            <td class="px-4 py-3 text-center">
                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase"
                                      :class="log.status === 'success' ? 'bg-emerald-500/20 text-emerald-400' : log.status === 'error' ? 'bg-red-500/20 text-red-400' : 'bg-gray-500/20 text-gray-400'"
                                      x-text="log.status"></span>
                            </td>
                        </tr>
                    </template>
                    <template x-if="!loading && (!data.logs || data.logs.length === 0)">
                        <tr><td colspan="7" class="px-4 py-12 text-center text-gray-500">Nenhum registro encontrado</td></tr>
                    </template>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div class="p-4 border-t border-white/5 flex items-center justify-between" x-show="(data.total_pages || 0) > 1">
            <span class="text-xs text-gray-400" x-text="'Pagina ' + page + ' de ' + (data.total_pages || 1)"></span>
            <div class="flex gap-2">
                <button @click="page = Math.max(1, page - 1); load()" :disabled="page <= 1"
                        class="px-3 py-1.5 bg-white/5 hover:bg-white/10 rounded-lg text-xs text-gray-300 disabled:opacity-30 transition">Anterior</button>
                <button @click="page = Math.min(data.total_pages || 1, page + 1); load()" :disabled="page >= (data.total_pages || 1)"
                        class="px-3 py-1.5 bg-white/5 hover:bg-white/10 rounded-lg text-xs text-gray-300 disabled:opacity-30 transition">Proximo</button>
            </div>
        </div>
    </div>

    <!-- Loading overlay -->
    <div x-show="loading" class="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50">
        <div class="glass-card rounded-2xl p-8 text-center">
            <div class="animate-spin w-8 h-8 border-2 border-purple-400 border-t-transparent rounded-full mx-auto mb-3"></div>
            <p class="text-gray-300 text-sm">Carregando dados...</p>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script>
const SERVICE_COLORS = {
    scrapecreators: { bg: 'rgba(168, 85, 247, 0.7)', border: '#a855f7' },
    creative_center: { bg: 'rgba(16, 185, 129, 0.7)', border: '#10b981' },
    youtube_api: { bg: 'rgba(239, 68, 68, 0.7)', border: '#ef4444' },
    apify: { bg: 'rgba(59, 130, 246, 0.7)', border: '#3b82f6' },
    tiktok_api: { bg: 'rgba(236, 72, 153, 0.7)', border: '#ec4899' },
};

function getColor(svc) {
    return SERVICE_COLORS[svc] || { bg: 'rgba(156, 163, 175, 0.7)', border: '#9ca3af' };
}

let dailyChartInstance, serviceChartInstance, hourlyChartInstance, efficiencyChartInstance;

function scannerHistory() {
    return {
        data: {},
        loading: false,
        days: 30,
        page: 1,
        filterService: '',
        filterStatus: '',

        async load() {
            this.loading = true;
            try {
                const params = new URLSearchParams({
                    days: this.days, page: this.page, limit: 50,
                    service: this.filterService, status: this.filterStatus,
                });
                const res = await fetch(`/api/scanner/history?${params}`);
                this.data = await res.json();
                this.$nextTick(() => {
                    this.renderCharts();
                    lucide.createIcons();
                });
            } catch (e) {
                console.error('Load error:', e);
            }
            this.loading = false;
        },

        formatDate(iso) {
            if (!iso) return '-';
            const d = new Date(iso);
            return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' }) + ' ' +
                   d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
        },

        renderCharts() {
            this.renderDailyChart();
            this.renderServiceChart();
            this.renderHourlyChart();
            this.renderEfficiencyChart();
        },

        renderDailyChart() {
            const ctx = document.getElementById('dailyChart');
            if (!ctx) return;
            if (dailyChartInstance) dailyChartInstance.destroy();

            const chart = this.data.daily_chart || [];
            const labels = chart.map(d => d.date);
            const allServices = new Set();
            chart.forEach(d => Object.keys(d.services || {}).forEach(s => allServices.add(s)));

            const datasets = [...allServices].map(svc => ({
                label: svc.replace('_', ' '),
                data: chart.map(d => (d.services[svc]?.credits) || 0),
                backgroundColor: getColor(svc).bg,
                borderColor: getColor(svc).border,
                borderWidth: 1,
                borderRadius: 4,
            }));

            dailyChartInstance = new Chart(ctx, {
                type: 'bar',
                data: { labels, datasets },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    plugins: { legend: { labels: { color: '#9ca3af', font: { size: 11 } } } },
                    scales: {
                        x: { stacked: true, ticks: { color: '#6b7280', font: { size: 10 } }, grid: { color: 'rgba(255,255,255,0.03)' } },
                        y: { stacked: true, ticks: { color: '#6b7280', font: { size: 10 } }, grid: { color: 'rgba(255,255,255,0.05)' }, title: { display: true, text: 'Creditos', color: '#6b7280' } },
                    },
                },
            });
        },

        renderServiceChart() {
            const ctx = document.getElementById('serviceChart');
            if (!ctx) return;
            if (serviceChartInstance) serviceChartInstance.destroy();

            const byService = this.data.by_service || {};
            const labels = Object.keys(byService).map(s => s.replace('_', ' '));
            const values = Object.values(byService).map(v => v.credits);
            const colors = Object.keys(byService).map(s => getColor(s).bg);
            const borders = Object.keys(byService).map(s => getColor(s).border);

            if (labels.length === 0) {
                labels.push('Sem dados');
                values.push(1);
                colors.push('rgba(75, 85, 99, 0.5)');
                borders.push('#4b5563');
            }

            serviceChartInstance = new Chart(ctx, {
                type: 'doughnut',
                data: { labels, datasets: [{ data: values, backgroundColor: colors, borderColor: borders, borderWidth: 2 }] },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    cutout: '65%',
                    plugins: {
                        legend: { position: 'bottom', labels: { color: '#9ca3af', font: { size: 11 }, padding: 16 } },
                    },
                },
            });
        },

        renderHourlyChart() {
            const ctx = document.getElementById('hourlyChart');
            if (!ctx) return;
            if (hourlyChartInstance) hourlyChartInstance.destroy();

            const hourly = this.data.hourly || {};
            const labels = Object.keys(hourly).sort();
            const values = labels.map(h => hourly[h]);

            hourlyChartInstance = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels.map(h => h + 'h'),
                    datasets: [{
                        label: 'Requisicoes',
                        data: values,
                        backgroundColor: values.map(v => {
                            const max = Math.max(...values, 1);
                            const intensity = v / max;
                            return `rgba(124, 58, 237, ${0.2 + intensity * 0.6})`;
                        }),
                        borderColor: '#7c3aed',
                        borderWidth: 1,
                        borderRadius: 3,
                    }],
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        x: { ticks: { color: '#6b7280', font: { size: 9 } }, grid: { display: false } },
                        y: { ticks: { color: '#6b7280', font: { size: 10 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
                    },
                },
            });
        },

        renderEfficiencyChart() {
            const ctx = document.getElementById('efficiencyChart');
            if (!ctx) return;
            if (efficiencyChartInstance) efficiencyChartInstance.destroy();

            const chart = this.data.daily_chart || [];
            const labels = chart.map(d => d.date);

            // Sum credits and requests per day across all services
            const credits = chart.map(d => Object.values(d.services || {}).reduce((s, v) => s + (v.credits || 0), 0));
            const requests = chart.map(d => Object.values(d.services || {}).reduce((s, v) => s + (v.requests || 0), 0));

            efficiencyChartInstance = new Chart(ctx, {
                type: 'line',
                data: {
                    labels,
                    datasets: [
                        {
                            label: 'Creditos',
                            data: credits,
                            borderColor: '#a855f7',
                            backgroundColor: 'rgba(168, 85, 247, 0.1)',
                            fill: true, tension: 0.3, pointRadius: 2,
                        },
                        {
                            label: 'Requisicoes',
                            data: requests,
                            borderColor: '#3b82f6',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            fill: true, tension: 0.3, pointRadius: 2,
                        },
                    ],
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    plugins: { legend: { labels: { color: '#9ca3af', font: { size: 11 } } } },
                    scales: {
                        x: { ticks: { color: '#6b7280', font: { size: 10 } }, grid: { color: 'rgba(255,255,255,0.03)' } },
                        y: { ticks: { color: '#6b7280', font: { size: 10 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
                    },
                },
            });
        },
    };
}
</script>
{% endblock %}
