<!--
|--------------------------------------------------------------------------
| DevOverviewTab.vue — Visão Geral da área de desenvolvimento
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { logError } from '@/support/supportLogger';

const loading = ref(true);
const stats = ref({
    phases: [],
    roadmapTotal: 0,
    roadmapConcluido: 0,
    roadmapEmAndamento: 0,
    roadmapPendente: 0,
    auditoriaAberto: 0,
    auditoriaResolvido: 0,
    auditoriaTotal: 0,
    competitors: 0,
    competitorFeatures: 0,
    comparisonGaps: 0,
    comparisonTem: 0,
    comparisonParcial: 0,
    lastGenerations: []
});

async function loadStats() {
    loading.value = true;
    try {
        const [phasesRes, itemsRes, auditoriaRes, competitorsRes, featuresRes, matrixRes, logRes] = await Promise.all([
            supabase.from('dev_roadmap_phases').select('*').order('ordem'),
            supabase.from('dev_roadmap_items').select('id, phase_id, status'),
            supabase.from('dev_auditoria_items').select('id, status'),
            supabase.from('dev_competitors').select('id, nome, pais', { count: 'exact' }),
            supabase.from('dev_competitor_features').select('id', { count: 'exact', head: true }),
            supabase.from('dev_comparison_matrix').select('id, nosso_status'),
            supabase.from('dev_generation_log').select('*').order('created_at', { ascending: false }).limit(5)
        ]);

        // Phases with item counts per status
        const items = itemsRes.data || [];
        stats.value.phases = (phasesRes.data || []).map((p) => {
            const phaseItems = items.filter((i) => i.phase_id === p.id);
            return {
                ...p,
                total: phaseItems.length,
                concluido: phaseItems.filter((i) => i.status === 'concluido').length,
                em_andamento: phaseItems.filter((i) => i.status === 'em_andamento').length,
                pendente: phaseItems.filter((i) => i.status === 'pendente').length
            };
        });

        stats.value.roadmapTotal = items.length;
        stats.value.roadmapConcluido = items.filter((i) => i.status === 'concluido').length;
        stats.value.roadmapEmAndamento = items.filter((i) => i.status === 'em_andamento').length;
        stats.value.roadmapPendente = items.filter((i) => i.status === 'pendente').length;

        const aud = auditoriaRes.data || [];
        stats.value.auditoriaTotal = aud.length;
        stats.value.auditoriaAberto = aud.filter((i) => ['aberto', 'em_analise'].includes(i.status)).length;
        stats.value.auditoriaResolvido = aud.filter((i) => i.status === 'resolvido').length;

        stats.value.competitors = competitorsRes.count || (competitorsRes.data || []).length;
        stats.value.competitorFeatures = featuresRes.count || 0;

        const matrix = matrixRes.data || [];
        stats.value.comparisonGaps = matrix.filter((m) => m.nosso_status === 'gap').length;
        stats.value.comparisonTem = matrix.filter((m) => m.nosso_status === 'tem').length;
        stats.value.comparisonParcial = matrix.filter((m) => m.nosso_status === 'parcial').length;

        stats.value.lastGenerations = logRes.data || [];
    } catch (e) {
        logError('DevOverviewTab', 'loadStats', e);
    } finally {
        loading.value = false;
    }
}

function percent(done, total) {
    if (!total) return 0;
    return Math.round((done / total) * 100);
}

function statusColor(status) {
    return {
        planejada: 'var(--text-color-secondary)',
        em_andamento: '#f59e0b',
        concluida: '#10b981',
        arquivada: '#94a3b8'
    }[status] || 'var(--text-color-secondary)';
}

function formatDate(iso) {
    if (!iso) return '—';
    return new Date(iso).toLocaleString('pt-BR');
}

onMounted(loadStats);
</script>

<template>
    <div v-if="loading" class="loading">
        <i class="pi pi-spin pi-spinner text-2xl text-indigo-500" />
        <p class="text-sm text-[var(--text-color-secondary)] mt-2">Carregando estatísticas...</p>
    </div>

    <div v-else class="overview">
        <!-- Cards de stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background: color-mix(in srgb, #6366f1 12%, transparent); color: #6366f1">
                    <i class="pi pi-flag" />
                </div>
                <div class="stat-body">
                    <div class="stat-value">{{ stats.roadmapTotal }}</div>
                    <div class="stat-label">features no roadmap</div>
                    <div class="stat-sub">
                        <span class="done">{{ stats.roadmapConcluido }} concluídas</span> ·
                        <span class="doing">{{ stats.roadmapEmAndamento }} em andamento</span> ·
                        <span class="pending">{{ stats.roadmapPendente }} pendentes</span>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: color-mix(in srgb, #ef4444 12%, transparent); color: #ef4444">
                    <i class="pi pi-verified" />
                </div>
                <div class="stat-body">
                    <div class="stat-value">{{ stats.auditoriaAberto }}</div>
                    <div class="stat-label">bugs/débitos abertos</div>
                    <div class="stat-sub">
                        <span>{{ stats.auditoriaResolvido }} resolvidos</span> ·
                        <span>{{ stats.auditoriaTotal }} total</span>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: color-mix(in srgb, #0ea5e9 12%, transparent); color: #0ea5e9">
                    <i class="pi pi-globe" />
                </div>
                <div class="stat-body">
                    <div class="stat-value">{{ stats.competitors }}</div>
                    <div class="stat-label">concorrentes analisados</div>
                    <div class="stat-sub">{{ stats.competitorFeatures }} features catalogadas</div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: color-mix(in srgb, #f59e0b 12%, transparent); color: #f59e0b">
                    <i class="pi pi-exclamation-triangle" />
                </div>
                <div class="stat-body">
                    <div class="stat-value">{{ stats.comparisonGaps }}</div>
                    <div class="stat-label">gaps vs mercado</div>
                    <div class="stat-sub">
                        {{ stats.comparisonTem }} temos · {{ stats.comparisonParcial }} parciais
                    </div>
                </div>
            </div>
        </div>

        <!-- Progresso das fases -->
        <div class="section">
            <h2 class="section-title">Progresso das Fases</h2>
            <div class="phases-grid">
                <article v-for="phase in stats.phases" :key="phase.id" class="phase-card">
                    <header class="phase-head">
                        <div class="flex items-center gap-2">
                            <span class="phase-num">{{ phase.numero }}</span>
                            <h3 class="phase-name">{{ phase.nome }}</h3>
                        </div>
                        <span class="phase-status" :style="{ color: statusColor(phase.status) }">
                            {{ phase.status.replace('_', ' ') }}
                        </span>
                    </header>
                    <p class="phase-obj">{{ phase.objetivo }}</p>
                    <div class="phase-progress">
                        <div class="phase-bar">
                            <div class="phase-fill" :style="{ width: percent(phase.concluido, phase.total) + '%' }" />
                        </div>
                        <span class="phase-perc">{{ percent(phase.concluido, phase.total) }}%</span>
                    </div>
                    <div class="phase-counts">
                        <span class="pc-done">{{ phase.concluido }} concluídos</span>
                        <span class="pc-doing">{{ phase.em_andamento }} em andamento</span>
                        <span class="pc-pending">{{ phase.pendente }} pendentes</span>
                        <span class="pc-total">{{ phase.total }} total</span>
                    </div>
                    <div class="phase-timeline">
                        <i class="pi pi-clock text-xs" />
                        <span>{{ phase.timeline_sugerida || '—' }}</span>
                    </div>
                </article>
            </div>
        </div>

        <!-- Últimas gerações -->
        <div class="section">
            <h2 class="section-title">Últimas gerações (backup, dashboard, seed)</h2>
            <div v-if="stats.lastGenerations.length === 0" class="empty">Nenhuma geração registrada ainda.</div>
            <ul v-else class="gen-list">
                <li v-for="g in stats.lastGenerations" :key="g.id" class="gen-item">
                    <i
                        :class="['pi', g.sucesso ? 'pi-check-circle' : 'pi-times-circle']"
                        :style="{ color: g.sucesso ? '#10b981' : '#ef4444' }"
                    />
                    <span class="gen-tipo">{{ g.tipo }}</span>
                    <span class="gen-cmd">{{ g.comando || '—' }}</span>
                    <span class="gen-date">{{ formatDate(g.created_at) }}</span>
                </li>
            </ul>
        </div>
    </div>
</template>

<style scoped>
.loading {
    text-align: center;
    padding: 60px;
}

.overview {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 12px;
}

.stat-card {
    display: flex;
    align-items: center;
    gap: 12px;
    background: var(--surface-card, #fff);
    border: 1px solid var(--surface-border, #e2e8f0);
    border-radius: 10px;
    padding: 14px;
}

.stat-icon {
    display: grid;
    place-items: center;
    width: 42px;
    height: 42px;
    border-radius: 8px;
    font-size: 18px;
    flex-shrink: 0;
}

.stat-body {
    flex: 1;
    min-width: 0;
}

.stat-value {
    font-size: 22px;
    font-weight: 700;
    letter-spacing: -0.5px;
    color: var(--text-color);
    line-height: 1;
}

.stat-label {
    font-size: 12px;
    color: var(--text-color-secondary);
    margin-top: 2px;
}

.stat-sub {
    font-size: 11px;
    color: var(--text-color-secondary);
    margin-top: 6px;
}

.stat-sub .done { color: #10b981; }
.stat-sub .doing { color: #f59e0b; }
.stat-sub .pending { color: var(--text-color-secondary); }

.section {
    background: var(--surface-card, #fff);
    border: 1px solid var(--surface-border, #e2e8f0);
    border-radius: 10px;
    padding: 16px;
}

.section-title {
    font-size: 14px;
    font-weight: 700;
    margin-bottom: 12px;
    color: var(--text-color);
}

.phases-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 12px;
}

.phase-card {
    background: var(--surface-ground, #f8fafc);
    border: 1px solid var(--surface-border, #e2e8f0);
    border-radius: 8px;
    padding: 14px;
}

.phase-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.phase-num {
    display: grid;
    place-items: center;
    width: 26px;
    height: 26px;
    border-radius: 6px;
    background: var(--primary-color);
    color: white;
    font-weight: 700;
    font-size: 12px;
}

.phase-name {
    font-size: 14px;
    font-weight: 600;
    color: var(--text-color);
}

.phase-status {
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 600;
}

.phase-obj {
    font-size: 11px;
    color: var(--text-color-secondary);
    line-height: 1.5;
    margin-bottom: 12px;
}

.phase-progress {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
}

.phase-bar {
    flex: 1;
    height: 6px;
    background: var(--surface-border, #e2e8f0);
    border-radius: 3px;
    overflow: hidden;
}

.phase-fill {
    height: 100%;
    background: linear-gradient(90deg, #10b981, #6366f1);
    transition: width 0.3s;
}

.phase-perc {
    font-size: 11px;
    font-weight: 600;
    color: var(--text-color);
    min-width: 32px;
    text-align: right;
}

.phase-counts {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    font-size: 10px;
    margin-bottom: 8px;
}

.pc-done { color: #10b981; }
.pc-doing { color: #f59e0b; }
.pc-pending { color: var(--text-color-secondary); }
.pc-total { color: var(--text-color-secondary); margin-left: auto; }

.phase-timeline {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    color: var(--text-color-secondary);
    border-top: 1px solid var(--surface-border);
    padding-top: 8px;
    margin-top: 6px;
}

.gen-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.gen-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 0;
    font-size: 12px;
    border-bottom: 1px solid var(--surface-border);
}

.gen-item:last-child {
    border-bottom: none;
}

.gen-tipo {
    font-weight: 600;
    font-family: 'IBM Plex Mono', monospace;
    font-size: 11px;
    text-transform: uppercase;
    padding: 2px 8px;
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
    border-radius: 4px;
}

.gen-cmd {
    font-family: 'IBM Plex Mono', monospace;
    color: var(--text-color-secondary);
    font-size: 11px;
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.gen-date {
    font-size: 11px;
    color: var(--text-color-secondary);
}

.empty {
    text-align: center;
    padding: 30px;
    color: var(--text-color-secondary);
    font-size: 13px;
}
</style>
