Files
od8n_homepage/public/widget/widget.js
2025-07-28 07:22:36 -03:00

142 lines
4.5 KiB
JavaScript

document.addEventListener('DOMContentLoaded', async () => {
try {
let id = window.location.hostname || "localhost";
console.log("Detected domain ID:", id);
const configUrl = `http://localhost:8000/widget/custom/${id}.json`;
console.log(configUrl)
const response = await fetch(configUrl);
if (!response.ok) throw new Error(`Config not found at ${configUrl}`);
const config = await response.json();
const { widgetHTML, preamble, api } = config;
if (!widgetHTML || !api) {
console.error('Invalid config format. Expected widgetHTML and api.');
return;
}
// Step 3: Inject HTML into page
document.body.insertAdjacentHTML('beforeend', widgetHTML);
// Step 4: Select DOM elements
const chatToggle = document.getElementById('cw-chatToggle');
const chatWidget = document.getElementById('cw-chatWidget');
const chatForm = document.getElementById('cw-chatForm');
const chatInput = document.getElementById('cw-chatInput');
const chatMessages = document.getElementById('cw-chatMessages');
const statusDiv = document.getElementById('cw-status');
const sessionId = crypto.randomUUID();
let chatOpened = false;
// Step 5: Utility to append message
function appendMessage(text, sender) {
const msg = document.createElement('div');
msg.classList.add('cw-message', sender === 'user' ? 'user' : 'bot');
msg.innerHTML = text;
chatMessages.appendChild(msg);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Step 6: Toggle chat visibility
chatToggle.addEventListener('click', () => {
const isVisible = chatWidget.style.display === 'block';
chatWidget.style.display = isVisible ? 'none' : 'block';
if (!isVisible && !chatOpened) {
appendMessage(preamble, 'bot');
chatOpened = true;
}
});
// Step 7: Handle form submission
chatForm.addEventListener('submit', async (e) => {
e.preventDefault();
const input = chatInput.value.trim();
if (!input) return;
appendMessage(input, 'user');
chatInput.value = '';
chatInput.focus();
try {
const res = await fetch(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'sendMessage',
sessionId,
chatInput: input
})
});
console.log(res)
const data = await res.json();
if (data.status) {
statusDiv.innerHTML = data.status;
requestAnimationFrame(() => {
statusDiv.style.padding = '10px';
statusDiv.style.maxHeight = statusDiv.scrollHeight + 'px';
});
} else {
statusDiv.style.maxHeight = '0';
statusDiv.style.padding = '0 10px';
}
appendMessage(data.output, 'bot');
} catch (error) {
appendMessage('Fehler beim Verbinden mit dem Server. Bitte versuchen Sie es später erneut.', 'bot');
console.error(error);
}
});
// Step 8: Attach pricing buttons if they exist
function handleBuyClick(buttonId, message) {
const btn = document.getElementById(buttonId);
if (!btn) return;
btn.addEventListener('click', (e) => {
e.preventDefault();
if (chatWidget.style.display !== 'block') {
chatWidget.style.display = 'block';
if (!chatOpened) {
appendMessage(preamble, 'bot');
chatOpened = true;
}
}
appendMessage(message, 'user');
fetch(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'sendMessage',
sessionId,
chatInput: message
})
})
.then(res => res.json())
.then(data => {
appendMessage(data.output, 'bot');
})
.catch(err => {
appendMessage('Fehler beim Verbinden mit dem Server. Bitte versuchen Sie es später erneut.', 'bot');
console.error(err);
});
});
}
handleBuyClick('buy-3h', 'I want to buy the 3 Hours pack for $450.');
handleBuyClick('buy-5h', 'I want to buy the 5 Hours pack for $675.');
handleBuyClick('buy-10h', 'I want to buy the 10 Hours pack for $1200.');
handleBuyClick('buy-bundle', 'I want to buy the ODOO and N8N bundle for $395 per year.');
} catch (err) {
console.error('Failed to initialize chat widget:', err);
}
});