xlorfx commited on
Commit
a71afe2
·
verified ·
1 Parent(s): 1c481bc

Create script.js

Browse files
Files changed (1) hide show
  1. script.js +195 -0
script.js ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // arquivo: script.js - Para integrar com o frontend existente
2
+
3
+ // Configuração da API
4
+ const API_URL = 'https://seu-backend-goalmaster-ai.hf.space'; // Substitua pelo URL real quando implantar
5
+
6
+ // Selecionar elementos importantes do DOM
7
+ document.addEventListener('DOMContentLoaded', () => {
8
+ const generatePlanBtn = document.getElementById('generate-plan');
9
+ const aiLoadingSection = document.getElementById('ai-loading');
10
+ const aiPlanSection = document.getElementById('ai-plan-section');
11
+
12
+ const goalTitleInput = document.getElementById('goal-title');
13
+ const goalCategorySelect = document.getElementById('goal-category');
14
+ const goalDescriptionInput = document.getElementById('goal-description');
15
+ const goalTimelineSelect = document.getElementById('goal-timeline');
16
+
17
+ // Capturar opções da IA
18
+ const stepByStepOption = document.querySelector('input[type="checkbox"][checked]:nth-of-type(1)');
19
+ const metricsOption = document.querySelector('input[type="checkbox"][checked]:nth-of-type(2)');
20
+ const remindersOption = document.querySelector('input[type="checkbox"][checked]:nth-of-type(3)');
21
+ const benchmarksOption = document.querySelector('input[type="checkbox"]:not([checked])');
22
+
23
+ // Substituir o evento de clique simulado por uma chamada real à API
24
+ if (generatePlanBtn) {
25
+ generatePlanBtn.addEventListener('click', async function() {
26
+ if (!goalTitleInput.value.trim()) {
27
+ alert('Por favor, informe um título para sua meta.');
28
+ return;
29
+ }
30
+
31
+ // Mostrar estado de carregamento
32
+ aiLoadingSection.classList.remove('hidden');
33
+ generatePlanBtn.disabled = true;
34
+
35
+ try {
36
+ // Preparar dados para enviar à API
37
+ const planData = {
38
+ title: goalTitleInput.value,
39
+ category: goalCategorySelect.value,
40
+ description: goalDescriptionInput.value,
41
+ timeframe: goalTimelineSelect.value,
42
+ options: {
43
+ step_by_step: stepByStepOption.checked,
44
+ metrics: metricsOption.checked,
45
+ reminders: remindersOption.checked,
46
+ benchmarks: benchmarksOption.checked
47
+ }
48
+ };
49
+
50
+ // Fazer chamada à API
51
+ const response = await fetch(`${API_URL}/generate-plan`, {
52
+ method: 'POST',
53
+ headers: {
54
+ 'Content-Type': 'application/json',
55
+ },
56
+ body: JSON.stringify(planData)
57
+ });
58
+
59
+ const result = await response.json();
60
+
61
+ if (result.success) {
62
+ // Atualizar a UI com o plano gerado
63
+ updatePlanUI(result.plan, planData.title, planData.category);
64
+ } else {
65
+ throw new Error(result.error || 'Erro ao gerar o plano');
66
+ }
67
+ } catch (error) {
68
+ console.error('Erro:', error);
69
+ // Em caso de erro, exibir um plano genérico
70
+ displayFallbackPlan(goalTitleInput.value, goalCategorySelect.value);
71
+ } finally {
72
+ // Ocultar carregamento e mostrar seção do plano
73
+ aiLoadingSection.classList.add('hidden');
74
+ aiPlanSection.classList.remove('hidden');
75
+ generatePlanBtn.disabled = false;
76
+
77
+ // Rolar até a seção do plano
78
+ aiPlanSection.scrollIntoView({ behavior: 'smooth' });
79
+ }
80
+ });
81
+ }
82
+ });
83
+
84
+ // Função para atualizar a UI com o plano gerado pela IA
85
+ function updatePlanUI(plan, goalTitle, category) {
86
+ // Selecionar elementos que precisam ser atualizados
87
+ const planSummaryContainer = document.querySelector('.bg-gray-50.p-4.rounded-lg.mb-6 ul');
88
+ const planStepsContainer = document.querySelector('.mb-6 .space-y-4');
89
+ const resourcesContainer = document.querySelector('.bg-blue-50.p-4.rounded-lg ul');
90
+ const checkpointsContainer = document.querySelector('.bg-green-50.p-4.rounded-lg ul');
91
+
92
+ // Atualizar resumo
93
+ if (planSummaryContainer) {
94
+ planSummaryContainer.innerHTML = `
95
+ <li>Duração: ${plan.summary.duration}</li>
96
+ <li>Métricas-chave: ${plan.summary.key_metrics.join(', ')}</li>
97
+ <li>Nível estimado ao final: ${plan.summary.final_level}</li>
98
+ <li>Dificuldade: ${plan.summary.difficulty}</li>
99
+ `;
100
+ }
101
+
102
+ // Atualizar etapas
103
+ if (planStepsContainer) {
104
+ planStepsContainer.innerHTML = '';
105
+
106
+ plan.steps.forEach((step, index) => {
107
+ const stepElement = document.createElement('div');
108
+ stepElement.className = 'p-4 border border-gray-200 rounded-lg';
109
+
110
+ const tasks = step.tasks.map(task => `• ${task}`).join('<br>');
111
+
112
+ stepElement.innerHTML = `
113
+ <div class="flex items-start">
114
+ <div class="flex-shrink-0 h-10 w-10 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 mr-3">
115
+ <span class="font-bold">${index + 1}</span>
116
+ </div>
117
+ <div>
118
+ <h4 class="font-medium text-gray-900">${step.period}: ${step.title}</h4>
119
+ <p class="text-gray-600 mt-1">${tasks}</p>
120
+ </div>
121
+ </div>
122
+ `;
123
+
124
+ planStepsContainer.appendChild(stepElement);
125
+ });
126
+ }
127
+
128
+ // Atualizar recursos recomendados
129
+ if (resourcesContainer) {
130
+ resourcesContainer.innerHTML = '';
131
+
132
+ plan.resources.forEach(resource => {
133
+ const li = document.createElement('li');
134
+ li.innerHTML = `<a href="#" class="underline">${resource}</a>`;
135
+ resourcesContainer.appendChild(li);
136
+ });
137
+ }
138
+
139
+ // Atualizar checkpoints
140
+ if (checkpointsContainer) {
141
+ checkpointsContainer.innerHTML = '';
142
+
143
+ plan.checkpoints.forEach(checkpoint => {
144
+ const li = document.createElement('li');
145
+ li.textContent = checkpoint;
146
+ checkpointsContainer.appendChild(li);
147
+ });
148
+ }
149
+
150
+ // Atualizar título e citação da IA
151
+ const planTitle = document.querySelector('#ai-plan-section h2');
152
+ if (planTitle) {
153
+ planTitle.textContent = `Plano para: ${goalTitle}`;
154
+ }
155
+
156
+ const planQuote = document.querySelector('.border-l-4.border-purple-500.pl-4.mb-6 p');
157
+ if (planQuote) {
158
+ 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:"`;
159
+ }
160
+ }
161
+
162
+ // Função para exibir um plano de contingência em caso de falha
163
+ function displayFallbackPlan(goalTitle, category) {
164
+ // Plano genérico baseado no título e categoria
165
+ const fallbackPlan = {
166
+ summary: {
167
+ duration: "3 meses",
168
+ key_metrics: ["Progresso semanal", "Tarefas concluídas"],
169
+ final_level: "Objetivo alcançado com sucesso",
170
+ difficulty: "Moderada"
171
+ },
172
+ steps: [
173
+ {
174
+ period: "Mês 1",
175
+ title: "Preparação e Planejamento",
176
+ tasks: ["Pesquisar sobre o tema", "Definir metas específicas", "Reunir recursos necessários"]
177
+ },
178
+ {
179
+ period: "Mês 2",
180
+ title: "Implementação",
181
+ tasks: ["Executar tarefas planejadas", "Monitorar progresso", "Ajustar estratégias"]
182
+ },
183
+ {
184
+ period: "Mês 3",
185
+ title: "Refinamento e Conclusão",
186
+ tasks: ["Aprimorar habilidades", "Superar obstáculos finais", "Avaliar resultados"]
187
+ }
188
+ ],
189
+ resources: ["Cursos online sobre o tema", "Comunidades especializadas", "Ferramentas digitais de acompanhamento"],
190
+ checkpoints: ["Relatório semanal de progresso", "Avaliação mensal de resultados", "Revisão de estratégias a cada 2 semanas"]
191
+ };
192
+
193
+ // Atualizar UI com o plano de contingência
194
+ updatePlanUI(fallbackPlan, goalTitle, category);
195
+ }