goal-master-ai / script.js
xlorfx's picture
Create script.js
a71afe2 verified
// 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);
}