File size: 8,460 Bytes
a71afe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// arquivo: script.js - Para integrar com o frontend existente

// Configuração da API
const API_URL = 'https://seu-backend-goalmaster-ai.hf.space'; // Substitua pelo URL real quando implantar

// Selecionar elementos importantes do DOM
document.addEventListener('DOMContentLoaded', () => {
    const generatePlanBtn = document.getElementById('generate-plan');
    const aiLoadingSection = document.getElementById('ai-loading');
    const aiPlanSection = document.getElementById('ai-plan-section');
    
    const goalTitleInput = document.getElementById('goal-title');
    const goalCategorySelect = document.getElementById('goal-category');
    const goalDescriptionInput = document.getElementById('goal-description');
    const goalTimelineSelect = document.getElementById('goal-timeline');
    
    // Capturar opções da IA
    const stepByStepOption = document.querySelector('input[type="checkbox"][checked]:nth-of-type(1)');
    const metricsOption = document.querySelector('input[type="checkbox"][checked]:nth-of-type(2)');
    const remindersOption = document.querySelector('input[type="checkbox"][checked]:nth-of-type(3)');
    const benchmarksOption = document.querySelector('input[type="checkbox"]:not([checked])');
    
    // Substituir o evento de clique simulado por uma chamada real à API
    if (generatePlanBtn) {
        generatePlanBtn.addEventListener('click', async function() {
            if (!goalTitleInput.value.trim()) {
                alert('Por favor, informe um título para sua meta.');
                return;
            }
            
            // Mostrar estado de carregamento
            aiLoadingSection.classList.remove('hidden');
            generatePlanBtn.disabled = true;
            
            try {
                // Preparar dados para enviar à API
                const planData = {
                    title: goalTitleInput.value,
                    category: goalCategorySelect.value,
                    description: goalDescriptionInput.value,
                    timeframe: goalTimelineSelect.value,
                    options: {
                        step_by_step: stepByStepOption.checked,
                        metrics: metricsOption.checked,
                        reminders: remindersOption.checked,
                        benchmarks: benchmarksOption.checked
                    }
                };
                
                // Fazer chamada à API
                const response = await fetch(`${API_URL}/generate-plan`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(planData)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Atualizar a UI com o plano gerado
                    updatePlanUI(result.plan, planData.title, planData.category);
                } else {
                    throw new Error(result.error || 'Erro ao gerar o plano');
                }
            } catch (error) {
                console.error('Erro:', error);
                // Em caso de erro, exibir um plano genérico
                displayFallbackPlan(goalTitleInput.value, goalCategorySelect.value);
            } finally {
                // Ocultar carregamento e mostrar seção do plano
                aiLoadingSection.classList.add('hidden');
                aiPlanSection.classList.remove('hidden');
                generatePlanBtn.disabled = false;
                
                // Rolar até a seção do plano
                aiPlanSection.scrollIntoView({ behavior: 'smooth' });
            }
        });
    }
});

// Função para atualizar a UI com o plano gerado pela IA
function updatePlanUI(plan, goalTitle, category) {
    // Selecionar elementos que precisam ser atualizados
    const planSummaryContainer = document.querySelector('.bg-gray-50.p-4.rounded-lg.mb-6 ul');
    const planStepsContainer = document.querySelector('.mb-6 .space-y-4');
    const resourcesContainer = document.querySelector('.bg-blue-50.p-4.rounded-lg ul');
    const checkpointsContainer = document.querySelector('.bg-green-50.p-4.rounded-lg ul');
    
    // Atualizar resumo
    if (planSummaryContainer) {
        planSummaryContainer.innerHTML = `
            <li>Duração: ${plan.summary.duration}</li>
            <li>Métricas-chave: ${plan.summary.key_metrics.join(', ')}</li>
            <li>Nível estimado ao final: ${plan.summary.final_level}</li>
            <li>Dificuldade: ${plan.summary.difficulty}</li>
        `;
    }
    
    // Atualizar etapas
    if (planStepsContainer) {
        planStepsContainer.innerHTML = '';
        
        plan.steps.forEach((step, index) => {
            const stepElement = document.createElement('div');
            stepElement.className = 'p-4 border border-gray-200 rounded-lg';
            
            const tasks = step.tasks.map(task => `• ${task}`).join('<br>');
            
            stepElement.innerHTML = `
                <div class="flex items-start">
                    <div class="flex-shrink-0 h-10 w-10 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 mr-3">
                        <span class="font-bold">${index + 1}</span>
                    </div>
                    <div>
                        <h4 class="font-medium text-gray-900">${step.period}: ${step.title}</h4>
                        <p class="text-gray-600 mt-1">${tasks}</p>
                    </div>
                </div>
            `;
            
            planStepsContainer.appendChild(stepElement);
        });
    }
    
    // Atualizar recursos recomendados
    if (resourcesContainer) {
        resourcesContainer.innerHTML = '';
        
        plan.resources.forEach(resource => {
            const li = document.createElement('li');
            li.innerHTML = `<a href="#" class="underline">${resource}</a>`;
            resourcesContainer.appendChild(li);
        });
    }
    
    // Atualizar checkpoints
    if (checkpointsContainer) {
        checkpointsContainer.innerHTML = '';
        
        plan.checkpoints.forEach(checkpoint => {
            const li = document.createElement('li');
            li.textContent = checkpoint;
            checkpointsContainer.appendChild(li);
        });
    }
    
    // Atualizar título e citação da IA
    const planTitle = document.querySelector('#ai-plan-section h2');
    if (planTitle) {
        planTitle.textContent = `Plano para: ${goalTitle}`;
    }
    
    const planQuote = document.querySelector('.border-l-4.border-purple-500.pl-4.mb-6 p');
    if (planQuote) {
        planQuote.textContent = `"Com base no seu objetivo de ${goalTitle} na categoria ${category}, criei um plano personalizado para você alcançar seu objetivo com sucesso. Aqui está o que recomendo:"`;
    }
}

// Função para exibir um plano de contingência em caso de falha
function displayFallbackPlan(goalTitle, category) {
    // Plano genérico baseado no título e categoria
    const fallbackPlan = {
        summary: {
            duration: "3 meses",
            key_metrics: ["Progresso semanal", "Tarefas concluídas"],
            final_level: "Objetivo alcançado com sucesso",
            difficulty: "Moderada"
        },
        steps: [
            {
                period: "Mês 1",
                title: "Preparação e Planejamento",
                tasks: ["Pesquisar sobre o tema", "Definir metas específicas", "Reunir recursos necessários"]
            },
            {
                period: "Mês 2",
                title: "Implementação",
                tasks: ["Executar tarefas planejadas", "Monitorar progresso", "Ajustar estratégias"]
            },
            {
                period: "Mês 3",
                title: "Refinamento e Conclusão",
                tasks: ["Aprimorar habilidades", "Superar obstáculos finais", "Avaliar resultados"]
            }
        ],
        resources: ["Cursos online sobre o tema", "Comunidades especializadas", "Ferramentas digitais de acompanhamento"],
        checkpoints: ["Relatório semanal de progresso", "Avaliação mensal de resultados", "Revisão de estratégias a cada 2 semanas"]
    };
    
    // Atualizar UI com o plano de contingência
    updatePlanUI(fallbackPlan, goalTitle, category);
}