{% extends "base.html" %}
{% block title %}Viral Academy - Viral Social Pro{% endblock %}
{% block nav_academy %}active{% endblock %}
{% block page_title %}Viral Academy{% endblock %}
{% block page_subtitle %}Aprenda, pratique e domine a viralizacao{% endblock %}

{% block content %}
<div x-data="viralAcademy()" x-init="init()" x-cloak>

    <!-- XP BAR -->
    <div class="glass-card rounded-2xl p-4 mb-6 animate-fade-up">
        <div class="flex items-center gap-4">
            <div class="w-14 h-14 rounded-xl gradient-brand flex items-center justify-center flex-shrink-0">
                <span class="text-xl font-bold" x-text="stats.level || 1"></span>
            </div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center justify-between mb-1">
                    <span class="text-sm font-bold text-white/80">Nivel <span x-text="stats.level || 1"></span></span>
                    <span class="text-xs text-white/40" x-text="stats.xp + ' / ' + stats.xp_to_next + ' XP'"></span>
                </div>
                <div class="w-full h-2.5 bg-dark-700 rounded-full overflow-hidden">
                    <div class="h-full gradient-brand rounded-full transition-all duration-500" :style="'width:' + (stats.xp_progress || 0) + '%'"></div>
                </div>
                <div class="flex items-center gap-4 mt-2 text-xs text-white/40">
                    <span class="flex items-center gap-1"><i data-lucide="flame" class="w-3.5 h-3.5 text-accent-orange"></i> <span x-text="stats.streak_days || 0"></span> dias de streak</span>
                    <span class="flex items-center gap-1"><i data-lucide="trophy" class="w-3.5 h-3.5 text-yellow-400"></i> <span x-text="stats.achievements_earned || 0"></span>/<span x-text="stats.achievements_total || 0"></span> conquistas</span>
                    <span class="flex items-center gap-1"><i data-lucide="target" class="w-3.5 h-3.5 text-brand-400"></i> <span x-text="stats.total_challenges_done || 0"></span> desafios</span>
                </div>
            </div>
        </div>
    </div>

    <!-- TABS -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1">
        <button class="tab-btn" :class="tab === 'painel' && 'active'" @click="tab = 'painel'">
            <i data-lucide="layout-dashboard" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Painel
        </button>
        <button class="tab-btn" :class="tab === 'curso' && 'active'" @click="tab = 'curso'; loadCourse()">
            <i data-lucide="book-open" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Curso
        </button>
        <button class="tab-btn" :class="tab === 'coach' && 'active'" @click="tab = 'coach'">
            <i data-lucide="sparkles" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Coach IA
        </button>
        <button class="tab-btn" :class="tab === 'conquistas' && 'active'" @click="tab = 'conquistas'; loadAchievements()">
            <i data-lucide="award" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Conquistas
        </button>
        <button class="tab-btn" :class="tab === 'trilhas' && 'active'" @click="tab = 'trilhas'; loadPaths()">
            <i data-lucide="map" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Trilhas
        </button>
    </div>

    <!-- TAB: PAINEL -->
    <div x-show="tab === 'painel'" x-transition>
        <!-- Quick Stats -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="book-open" class="w-6 h-6 text-brand-400 mx-auto mb-2"></i>
                <p class="text-xl font-bold text-white" x-text="courseData?.completed || 0"></p>
                <p class="text-[10px] text-white/40">Modulos completos</p>
                <p class="text-[10px] text-white/30" x-text="'de ' + (courseData?.total || 24)"></p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="target" class="w-6 h-6 text-accent-green mx-auto mb-2"></i>
                <p class="text-xl font-bold text-accent-green" x-text="challenges.daily?.length || 0"></p>
                <p class="text-[10px] text-white/40">Desafios de hoje</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="trophy" class="w-6 h-6 text-yellow-400 mx-auto mb-2"></i>
                <p class="text-xl font-bold text-yellow-400" x-text="stats.achievements_earned || 0"></p>
                <p class="text-[10px] text-white/40">Conquistas</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="map" class="w-6 h-6 text-accent-cyan mx-auto mb-2"></i>
                <p class="text-xl font-bold text-accent-cyan" x-text="stats.active_plans || 0"></p>
                <p class="text-[10px] text-white/40">Planos ativos</p>
            </div>
        </div>

        <!-- Active Challenges -->
        <div class="glass-card rounded-2xl p-5 mb-4">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2"><i data-lucide="target" class="w-4 h-4 text-accent-green"></i> Desafios Ativos</h3>
                <button @click="generateDailyChallenges()" class="text-xs text-brand-300 hover:text-brand-200">Gerar novos</button>
            </div>
            <div x-show="challenges.daily?.length === 0 && challenges.weekly?.length === 0" class="text-center py-6">
                <p class="text-sm text-white/30">Nenhum desafio ativo. Clique em "Gerar novos"!</p>
            </div>
            <div class="space-y-2">
                <template x-for="c in [...(challenges.daily || []), ...(challenges.weekly || [])]" :key="c.id">
                    <div class="glass-light rounded-xl p-3 flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <span class="px-2 py-0.5 rounded text-[9px] font-bold" :class="c.challenge_type === 'weekly' ? 'gradient-brand text-white' : 'bg-accent-green/20 text-accent-green'" x-text="c.challenge_type === 'weekly' ? 'SEMANAL' : 'DIARIO'"></span>
                            <div>
                                <p class="text-sm text-white/80" x-text="c.title"></p>
                                <p class="text-[10px] text-white/40" x-text="c.description"></p>
                            </div>
                        </div>
                        <div class="flex items-center gap-2 flex-shrink-0">
                            <span class="text-xs text-yellow-400 font-bold" x-text="'+' + c.xp_reward + ' XP'"></span>
                            <button @click="completeChallenge(c.id)" class="px-3 py-1 rounded-lg gradient-success text-white text-[10px] font-bold">Concluir</button>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- Course Progress Bar -->
        <div class="glass-card rounded-2xl p-5">
            <h3 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="book-open" class="w-4 h-4 text-brand-400"></i> Progresso do Curso</h3>
            <div class="w-full h-3 bg-dark-700 rounded-full overflow-hidden mb-2">
                <div class="h-full gradient-brand rounded-full transition-all" :style="'width:' + (courseData?.percent || 0) + '%'"></div>
            </div>
            <div class="flex items-center justify-between text-xs text-white/40">
                <span x-text="(courseData?.completed || 0) + ' de ' + (courseData?.total || 24) + ' modulos'"></span>
                <span x-text="(courseData?.percent || 0) + '% completo'"></span>
            </div>
            <div x-show="courseData?.next_module" class="mt-3 glass-light rounded-xl p-3">
                <p class="text-[10px] text-white/40 mb-1">Proximo modulo:</p>
                <p class="text-sm font-bold text-white/80" x-text="courseData?.next_module?.title"></p>
                <p class="text-[10px] text-white/40" x-text="courseData?.next_module?.description"></p>
            </div>
        </div>
    </div>

    <!-- TAB: CURSO -->
    <div x-show="tab === 'curso'" x-transition>
        <div class="space-y-2">
            <template x-for="m in (courseData?.modules || [])" :key="m.id">
                <div class="glass-card rounded-xl p-4 flex items-center gap-4" :class="m.completed && 'border-green-500/20'">
                    <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
                         :class="m.completed ? 'bg-accent-green/20' : 'bg-dark-700'">
                        <i :data-lucide="m.completed ? 'check-circle' : 'circle'" class="w-5 h-5" :class="m.completed ? 'text-accent-green' : 'text-white/20'"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2">
                            <span class="text-[10px] text-white/30" x-text="'#' + m.id"></span>
                            <h4 class="text-sm font-bold" :class="m.completed ? 'text-white/60 line-through' : 'text-white/80'" x-text="m.title"></h4>
                        </div>
                        <p class="text-[10px] text-white/40 mt-0.5" x-text="m.description"></p>
                        <div class="flex items-center gap-3 mt-1 text-[10px] text-white/30">
                            <span x-text="m.category"></span>
                            <span x-text="m.duration + ' min'"></span>
                        </div>
                    </div>
                    <button x-show="!m.completed" @click="completeModule(m.id)" class="px-3 py-1.5 rounded-lg gradient-brand text-white text-xs font-bold flex-shrink-0">Concluir</button>
                    <span x-show="m.completed" class="text-[10px] text-accent-green font-bold flex-shrink-0">Completo</span>
                </div>
            </template>
        </div>
    </div>

    <!-- TAB: COACH IA -->
    <div x-show="tab === 'coach'" x-transition>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <!-- Audit -->
            <div class="glass-card rounded-2xl p-5">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center"><i data-lucide="search" class="w-5 h-5"></i></div>
                    <div>
                        <h3 class="text-sm font-bold text-white/80">Auditoria de Canal</h3>
                        <p class="text-[10px] text-white/40">Analise completa do seu canal com IA</p>
                    </div>
                </div>
                <div class="flex gap-2 mb-3">
                    <select x-model="auditPlatform" class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="tiktok">TikTok</option>
                        <option value="instagram">Instagram</option>
                        <option value="youtube">YouTube</option>
                    </select>
                    <button @click="doAudit()" :disabled="loadingAudit" class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-bold disabled:opacity-50">
                        <span x-text="loadingAudit ? 'Auditando...' : 'Auditar'"></span>
                    </button>
                </div>
                <div x-show="auditResult" x-transition class="glass-light rounded-xl p-3 text-sm text-white/70 whitespace-pre-wrap leading-relaxed max-h-80 overflow-y-auto" x-text="auditResult?.audit || ''"></div>
            </div>

            <!-- Recommendations -->
            <div class="glass-card rounded-2xl p-5">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center"><i data-lucide="lightbulb" class="w-5 h-5"></i></div>
                    <div>
                        <h3 class="text-sm font-bold text-white/80">Recomendacoes IA</h3>
                        <p class="text-[10px] text-white/40">Dicas personalizadas para seu nivel</p>
                    </div>
                </div>
                <button @click="getRecommendations()" :disabled="loadingRecs" class="w-full px-4 py-2 rounded-xl gradient-ocean text-white text-xs font-bold disabled:opacity-50 mb-3">
                    <span x-text="loadingRecs ? 'Gerando...' : 'Gerar Recomendacoes'"></span>
                </button>
                <div x-show="recsResult" x-transition class="glass-light rounded-xl p-3 text-sm text-white/70 whitespace-pre-wrap leading-relaxed max-h-80 overflow-y-auto" x-text="recsResult?.recommendations || ''"></div>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- Growth Plan -->
            <div class="glass-card rounded-2xl p-5">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center"><i data-lucide="map" class="w-5 h-5"></i></div>
                    <div>
                        <h3 class="text-sm font-bold text-white/80">Plano de Crescimento</h3>
                        <p class="text-[10px] text-white/40">Plano de 90 dias personalizado com IA</p>
                    </div>
                </div>
                <div class="space-y-2 mb-3">
                    <input x-model="planGoal" type="text" placeholder="Meta (ex: 10k seguidores)"
                           class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    <div class="flex gap-2">
                        <select x-model="planPlatform" class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                            <option value="tiktok">TikTok</option>
                            <option value="instagram">Instagram</option>
                            <option value="youtube">YouTube</option>
                        </select>
                        <select x-model="planDays" class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                            <option value="30">30 dias</option>
                            <option value="60">60 dias</option>
                            <option value="90" selected>90 dias</option>
                        </select>
                    </div>
                </div>
                <button @click="generatePlan()" :disabled="loadingPlan || !planGoal" class="w-full px-4 py-2 rounded-xl gradient-fire text-white text-xs font-bold disabled:opacity-50">
                    <span x-text="loadingPlan ? 'Criando plano...' : 'Gerar Plano'"></span>
                </button>
                <div x-show="planResult" x-transition class="mt-3 glass-light rounded-xl p-3 text-sm text-white/70 whitespace-pre-wrap leading-relaxed max-h-80 overflow-y-auto" x-text="planResult?.plan_text || ''"></div>
            </div>

            <!-- Weekly Report -->
            <div class="glass-card rounded-2xl p-5">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center"><i data-lucide="bar-chart" class="w-5 h-5"></i></div>
                    <div>
                        <h3 class="text-sm font-bold text-white/80">Relatorio Semanal</h3>
                        <p class="text-[10px] text-white/40">Performance da ultima semana</p>
                    </div>
                </div>
                <button @click="getWeeklyReport()" :disabled="loadingReport" class="w-full px-4 py-2 rounded-xl gradient-success text-white text-xs font-bold disabled:opacity-50 mb-3">
                    <span x-text="loadingReport ? 'Gerando relatorio...' : 'Gerar Relatorio'"></span>
                </button>
                <div x-show="reportResult" x-transition class="glass-light rounded-xl p-3 text-sm text-white/70 whitespace-pre-wrap leading-relaxed max-h-80 overflow-y-auto" x-text="reportResult?.report || ''"></div>
            </div>
        </div>
    </div>

    <!-- TAB: CONQUISTAS -->
    <div x-show="tab === 'conquistas'" x-transition>
        <div class="flex items-center justify-between mb-4">
            <p class="text-sm text-white/50" x-text="achievementData?.earned + ' de ' + achievementData?.total + ' conquistas desbloqueadas'"></p>
            <button @click="seedAchievements()" class="text-xs text-brand-300 hover:text-brand-200">Seed Conquistas</button>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
            <template x-for="a in (achievementData?.achievements || [])" :key="a.code">
                <div class="glass-card rounded-xl p-4 text-center" :class="!a.earned && 'opacity-40'">
                    <div class="w-12 h-12 rounded-xl mx-auto mb-2 flex items-center justify-center"
                         :class="{
                             'bg-yellow-500/20': a.rarity === 'lendario' && a.earned,
                             'bg-purple-500/20': a.rarity === 'epico' && a.earned,
                             'bg-blue-500/20': a.rarity === 'raro' && a.earned,
                             'bg-white/5': a.rarity === 'comum' || !a.earned,
                         }">
                        <i :data-lucide="a.icon || 'award'" class="w-6 h-6"
                           :class="{
                               'text-yellow-400': a.rarity === 'lendario' && a.earned,
                               'text-purple-400': a.rarity === 'epico' && a.earned,
                               'text-blue-400': a.rarity === 'raro' && a.earned,
                               'text-white/50': a.rarity === 'comum' && a.earned,
                               'text-white/15': !a.earned,
                           }"></i>
                    </div>
                    <h4 class="text-xs font-bold text-white/80 mb-0.5" x-text="a.name"></h4>
                    <p class="text-[10px] text-white/40 mb-1" x-text="a.description"></p>
                    <div class="flex items-center justify-center gap-2">
                        <span class="text-[9px] px-1.5 py-0.5 rounded" :class="{
                            'bg-yellow-500/20 text-yellow-400': a.rarity === 'lendario',
                            'bg-purple-500/20 text-purple-400': a.rarity === 'epico',
                            'bg-blue-500/20 text-blue-400': a.rarity === 'raro',
                            'bg-white/10 text-white/40': a.rarity === 'comum',
                        }" x-text="a.rarity"></span>
                        <span class="text-[9px] text-yellow-400" x-text="'+' + a.xp_reward + ' XP'"></span>
                    </div>
                    <p x-show="a.earned" class="text-[9px] text-accent-green mt-1" x-text="'Desbloqueado'"></p>
                </div>
            </template>
        </div>
    </div>

    <!-- TAB: TRILHAS -->
    <div x-show="tab === 'trilhas'" x-transition>
        <div class="grid-cards">
            <template x-for="path in learningPaths" :key="path.id">
                <div class="glass-card rounded-xl p-5">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-12 h-12 rounded-xl flex items-center justify-center"
                             :class="{
                                 'gradient-brand': path.difficulty === 'facil',
                                 'gradient-fire': path.difficulty === 'intermediario',
                                 'gradient-ocean': path.difficulty === 'avancado',
                                 'gradient-success': path.difficulty === 'completo',
                             }">
                            <i :data-lucide="path.icon || 'map'" class="w-6 h-6"></i>
                        </div>
                        <div>
                            <h3 class="text-sm font-bold text-white/80" x-text="path.name"></h3>
                            <p class="text-[10px] text-white/40" x-text="path.description"></p>
                        </div>
                    </div>
                    <div class="flex items-center gap-3 text-[10px] text-white/30 mb-3">
                        <span x-text="path.modules.length + ' modulos'"></span>
                        <span x-text="path.duration"></span>
                        <span class="px-1.5 py-0.5 rounded" :class="{
                            'bg-green-500/20 text-green-400': path.difficulty === 'facil',
                            'bg-orange-500/20 text-orange-400': path.difficulty === 'intermediario',
                            'bg-red-500/20 text-red-400': path.difficulty === 'avancado',
                            'bg-brand-500/20 text-brand-300': path.difficulty === 'completo',
                        }" x-text="path.difficulty"></span>
                    </div>
                    <!-- Progress -->
                    <div class="w-full h-2 bg-dark-700 rounded-full overflow-hidden mb-1">
                        <div class="h-full gradient-brand rounded-full transition-all" :style="'width:' + getPathProgress(path) + '%'"></div>
                    </div>
                    <p class="text-[10px] text-white/30" x-text="getPathProgress(path) + '% completo'"></p>
                </div>
            </template>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function viralAcademy() {
    return {
        tab: 'painel',
        stats: {},
        courseData: null,
        challenges: { daily: [], weekly: [] },
        achievementData: null,
        learningPaths: [],

        // Coach
        auditPlatform: 'tiktok',
        loadingAudit: false,
        auditResult: null,
        loadingRecs: false,
        recsResult: null,
        planGoal: '',
        planPlatform: 'tiktok',
        planDays: 90,
        loadingPlan: false,
        planResult: null,
        loadingReport: false,
        reportResult: null,

        async init() {
            await Promise.all([this.loadStats(), this.loadCourse(), this.loadChallenges()]);
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async loadStats() {
            try {
                const r = await fetch('/api/academy/stats');
                this.stats = await r.json();
            } catch(e) {}
        },

        async loadCourse() {
            try {
                const r = await fetch('/api/academy/course');
                this.courseData = await r.json();
            } catch(e) {}
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async loadChallenges() {
            try {
                const r = await fetch('/api/academy/challenges');
                this.challenges = await r.json();
            } catch(e) {}
        },

        async loadAchievements() {
            try {
                const r = await fetch('/api/academy/achievements');
                this.achievementData = await r.json();
            } catch(e) {}
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async loadPaths() {
            if (this.learningPaths.length > 0) return;
            try {
                const r = await fetch('/api/academy/learning-paths');
                const d = await r.json();
                this.learningPaths = d.paths || [];
            } catch(e) {}
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async generateDailyChallenges() {
            try {
                const r = await fetch('/api/academy/challenges/daily', { method: 'POST', headers: {'Content-Type':'application/json'}, body: '{}' });
                const d = await r.json();
                // Also generate weekly
                await fetch('/api/academy/challenges/weekly', { method: 'POST', headers: {'Content-Type':'application/json'}, body: '{}' });
                await this.loadChallenges();
                showToast('Desafios gerados!', 'success');
            } catch(e) { showToast('Erro', 'error'); }
        },

        async completeChallenge(id) {
            try {
                const r = await fetch(`/api/academy/challenges/${id}/complete`, {
                    method: 'POST', headers: {'Content-Type':'application/json'}, body: '{}'
                });
                const d = await r.json();
                if (d.error) { showToast(d.error, 'error'); return; }
                showToast(`+${d.xp_earned} XP! ${d.leveled_up ? 'LEVEL UP!' : ''}`, 'success');
                if (d.new_achievements?.length) {
                    d.new_achievements.forEach(a => showToast(`Conquista: ${a.name}!`, 'success'));
                }
                await Promise.all([this.loadStats(), this.loadChallenges()]);
            } catch(e) { showToast('Erro', 'error'); }
        },

        async completeModule(id) {
            try {
                const r = await fetch(`/api/academy/course/${id}/complete`, {
                    method: 'POST', headers: {'Content-Type':'application/json'}, body: '{}'
                });
                const d = await r.json();
                if (d.error) { showToast(d.error, 'error'); return; }
                showToast(`+${d.xp_earned} XP! Modulo ${id} concluido!`, 'success');
                if (d.new_achievements?.length) {
                    d.new_achievements.forEach(a => showToast(`Conquista: ${a.name}!`, 'success'));
                }
                await Promise.all([this.loadStats(), this.loadCourse()]);
            } catch(e) { showToast('Erro', 'error'); }
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        // Coach IA
        async doAudit() {
            this.loadingAudit = true;
            showToast('Auditando canal...', 'info');
            try {
                const r = await fetch('/api/academy/audit', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ platform: this.auditPlatform })
                });
                this.auditResult = await r.json();
                showToast('Auditoria concluida! +50 XP', 'success');
                await this.loadStats();
            } catch(e) { showToast('Erro', 'error'); }
            this.loadingAudit = false;
        },

        async getRecommendations() {
            this.loadingRecs = true;
            try {
                const r = await fetch('/api/academy/recommendations');
                this.recsResult = await r.json();
            } catch(e) { showToast('Erro', 'error'); }
            this.loadingRecs = false;
        },

        async generatePlan() {
            if (!this.planGoal) return;
            this.loadingPlan = true;
            showToast('Criando plano de crescimento...', 'info');
            try {
                const r = await fetch('/api/academy/growth-plan', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ goal: this.planGoal, platform: this.planPlatform, days: parseInt(this.planDays) })
                });
                this.planResult = await r.json();
                showToast('Plano criado! +100 XP', 'success');
                await this.loadStats();
            } catch(e) { showToast('Erro', 'error'); }
            this.loadingPlan = false;
        },

        async getWeeklyReport() {
            this.loadingReport = true;
            showToast('Gerando relatorio...', 'info');
            try {
                const r = await fetch('/api/academy/weekly-report');
                this.reportResult = await r.json();
                showToast('Relatorio gerado! +30 XP', 'success');
                await this.loadStats();
            } catch(e) { showToast('Erro', 'error'); }
            this.loadingReport = false;
        },

        async seedAchievements() {
            try {
                const r = await fetch('/api/academy/seed-achievements', { method: 'POST' });
                const d = await r.json();
                showToast(`Conquistas: ${d.total || 0} total`, 'success');
                await this.loadAchievements();
            } catch(e) { showToast('Erro', 'error'); }
        },

        getPathProgress(path) {
            if (!this.courseData?.modules || !path.modules) return 0;
            const completed = this.courseData.modules.filter(m => m.completed && path.modules.includes(m.id));
            return Math.round(completed.length / path.modules.length * 100);
        },
    };
}
</script>
{% endblock %}
