const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=`;
const apiKey = ""; // A chave deve ser preenchida aqui se a comunicação falhar.
let chatHistory = [];
let isChatLoaded = false;
const loadTailwind = () => {
if (document.querySelector('script[src*="tailwindcss"]')) return;
const script = document.createElement('script');
script.src = "https://cdn.tailwindcss.com";
document.head.appendChild(script);
};
loadTailwind();
const addStyles = () => {
const style = document.createElement('style');
style.innerHTML = `
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');
#chat-widget-fs {
display: none;
}
body { font-family: 'Inter', sans-serif; }
.chat-container-fs {
max-height: calc(75vh - 140px);
overflow-y: auto;
display: flex;
flex-direction: column;
}
.message-bubble-fs {
max-width: 85%;
padding: 10px 14px;
border-radius: 1rem;
margin-bottom: 8px;
line-height: 1.4;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.agent-fs {
background-color: #e0f2fe;
color: #0c4a6e;
border-bottom-left-radius: 0.3rem;
align-self: flex-start;
}
.user-fs {
background-color: #fb923c;
color: white;
border-bottom-right-radius: 0.3rem;
align-self: flex-end;
}
.z-max-fs { z-index: 999999999; }
`;
document.head.appendChild(style);
};
addStyles();
const widgetHTML = `
`;
window.onload = function() {
if (!document.body) {
console.error("FS Chat: FALHA CRÍTICA! document.body não está disponível.");
return;
}
document.body.insertAdjacentHTML('beforeend', widgetHTML);
console.log("FS Chat: HTML injetado no Body com sucesso.");
const chatWidget = document.getElementById('chat-widget-fs');
const chatLauncher = document.getElementById('chat-launcher-fs');
const closeButton = document.getElementById('close-button-fs');
const chatForm = document.getElementById('chat-form-fs');
const userInput = document.getElementById('user-input-fs');
const chatMessages = document.getElementById('chat-messages-fs');
const typingIndicator = document.getElementById('typing-indicator-fs');
const sendButton = document.getElementById('send-button-fs');
if (!chatLauncher || !chatWidget) {
console.error("FS Chat: Elementos essenciais de UI não encontrados após injeção.");
return;
}
console.log("FS Chat: Elementos UI encontrados. Inicializando chat.");
// --- Variáveis de Contexto ---
const systemInstruction = {
parts: [{ text: `
Você é o 'Consultor Digital FranSeguros', um agente de seguros altamente profissional e experiente. Seu objetivo é qualificar as intenções do usuário, responder dúvidas sobre produtos de seguros (Auto, Residencial, Vida, Saúde, Empresarial, Consórcios, etc.) e, gentilmente, guiar o usuário para solicitar uma cotação formal.
INSTRUÇÕES:
1. Mantenha um tom de voz formal, confiável e educado, reforçando a credibilidade da FranSeguros.
2. Não gere cotações diretas. Se o usuário pedir um preço, diga que o preço exato depende de uma análise completa e peça para ele preencher o formulário no site ou fornecer o tipo de seguro que ele precisa para que você possa preparar a cotação.
3. Mantenha as respostas concisas e focadas no benefício.
`}]
};
let chatHistory = [];
let isChatLoaded = false;
// --- Funções do Chat ---
const scrollToBottom = () => {
if (chatMessages) {
chatMessages.scrollTop = chatMessages.scrollHeight;
}
};
const displayMessage = (text, sender) => {
const messageDiv = document.createElement('div');
messageDiv.classList.add('flex', 'flex-col');
const bubble = document.createElement('p');
bubble.classList.add('message-bubble-fs', 'shadow-md');
bubble.textContent = text;
if (sender === 'user') {
messageDiv.classList.add('items-end');
bubble.classList.add('user-fs');
} else {
messageDiv.classList.add('items-start');
bubble.classList.add('agent-fs');
}
messageDiv.appendChild(bubble);
chatMessages.appendChild(messageDiv);
scrollToBottom();
};
const initialAgentGreeting = () => {
isChatLoaded = true;
toggleInputState(true);
const specificGreeting = "Olá, sou seu Consultor Digital FranSeguros. É um prazer auxiliá-lo e garantir sua tranquilidade. Para que eu possa direcionar o atendimento com a precisão necessária, qual é o seu principal objetivo hoje: Tirar dúvidas sobre seguros (Auto, Residencial, Vida, Saúde, Consórcios) ou outros assuntos?";
console.log("FS Chat: Saudação Inicial disparada.");
setTimeout(() => {
displayMessage(specificGreeting, 'agent');
chatHistory.push({ role: "model", parts: [{ text: specificGreeting }] });
toggleInputState(false);
}, 500);
};
const toggleChat = () => {
const isCurrentlyHidden = chatWidget.style.display === 'none' || chatWidget.style.display === '';
if (isCurrentlyHidden) {
// ABRE
chatWidget.style.display = 'flex';
if (!isChatLoaded) {
initialAgentGreeting();
}
} else {
// FECHA
chatWidget.style.display = 'none';
}
scrollToBottom();
};
const toggleInputState = (isDisabled) => {
if (!userInput || !sendButton || !typingIndicator) return;
userInput.disabled = isDisabled;
sendButton.disabled = isDisabled;
sendButton.innerHTML = isDisabled ?
`
` :
`
`;
if (isDisabled) {
typingIndicator.classList.remove('hidden');
} else {
typingIndicator.classList.add('hidden');
}
};
const sendMessage = async (event) => {
event.preventDefault();
const userText = userInput.value.trim();
if (!userText) return;
displayMessage(userText, 'user');
chatHistory.push({ role: "user", parts: [{ text: userText }] });
userInput.value = '';
toggleInputState(true);
const payload = {
contents: chatHistory,
systemInstruction: systemInstruction,
tools: [{ "google_search": {} }],
};
for (let attempt = 0; attempt < 5; attempt++) {
try {
const response = await fetch(API_URL + apiKey, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`HTTP error! status: ${response.status}. Corpo: ${errorBody.substring(0, 100)}...`);
}
const result = await response.json();
const agentResponse = result.candidates?.[0]?.content?.parts?.[0]?.text;
if (agentResponse) {
displayMessage(agentResponse, 'agent');
chatHistory.push({ role: "model", parts: [{ text: agentResponse }] });
break;
} else {
throw new Error("Resposta da IA vazia ou inválida.");
}
} catch (error) {
console.error(`FS Chat: Falha na API na tentativa ${attempt + 1}.`, error);
if (attempt < 4) {
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
} else {
displayMessage("Desculpe, não consegui me conectar ao Consultor Digital. O serviço de inteligência artificial está indisponível. (Verifique sua API Key)", 'agent');
break;
}
}
}
toggleInputState(false);
};
chatLauncher.addEventListener('click', toggleChat);
closeButton.addEventListener('click', toggleChat);
if (chatForm) {
chatForm.addEventListener('submit', sendMessage);
}
// Garante que o widget esteja escondido na inicialização
chatWidget.style.display = 'none';
console.log("FS Chat: Inicialização concluída com sucesso. Botão pronto para clique.");