No webinar data to display.
`;
}
renderAttendanceChart();
renderEngagementChart();
};
const renderAttendanceChart = () => {
const ctx = elements.attendanceChartCanvas?.getContext('2d');
if (!ctx) return;
const sortedData = [...webinarData].sort((a, b) => new Date(a.date) - new Date(b.date));
const labels = sortedData.map(w => new Date(w.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
if (attendanceChart) attendanceChart.destroy();
attendanceChart = new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [
{ label: 'Registrants', data: sortedData.map(w => w.registrants), backgroundColor: '#a5b4fc' },
{ label: 'Attendees', data: sortedData.map(w => w.attendees), backgroundColor: '#4f46e5' }
]
},
options: { responsive: true, maintainAspectRatio: true, scales: { x: { stacked: false }, y: { stacked: false } } }
});
};
const renderEngagementChart = () => {
const ctx = elements.engagementChartCanvas?.getContext('2d');
if (!ctx) return;
const sortedData = [...webinarData].sort((a, b) => b.engagement - a.engagement);
const labels = sortedData.map(w => w.title);
const data = sortedData.map(w => w.engagement);
if (engagementChart) engagementChart.destroy();
engagementChart = new Chart(ctx, {
type: 'bar',
data: { labels, datasets: [{ label: 'Engagement Score', data, backgroundColor: '#8b5cf6' }] },
options: { responsive: true, maintainAspectRatio: true, indexAxis: 'y', plugins: { legend: { display: false } }, scales: { x: { min: 0, max: 10 } } }
});
};
const renderConfigPanel = () => {
const container = elements.editableList;
if (!container) return;
container.innerHTML = '';
webinarData.forEach(w => {
const card = document.createElement('div');
card.className = 'grid grid-cols-1 md:grid-cols-4 gap-4 items-center bg-white p-3 rounded-lg border';
card.innerHTML = `
`;
container.appendChild(card);
});
};
const handleAddLog = (e) => {
e.preventDefault();
try {
const getNumericValue = (id) => parseFloat(document.getElementById(id).value) || 0;
const newLog = {
id: webinarData.length > 0 ? Math.max(...webinarData.map(w => w.id)) + 1 : 1,
title: document.getElementById('webinarTitle').value,
date: document.getElementById('webinarDate').value,
registrants: getNumericValue('registrants'),
attendees: getNumericValue('attendees'),
engagement: getNumericValue('engagementScore'),
questions: getNumericValue('questionsAsked'),
};
webinarData.push(newLog);
elements.addForm.reset();
renderAll();
showToast('Webinar record added!');
} catch (error) {
console.error("Error adding record:", error);
showToast("Error: Could not add record.");
}
};
const handleConfigListClick = (e) => {
const target = e.target.closest('button');
if (!target) return;
const action = target.dataset.action;
const id = parseInt(target.dataset.id, 10);
if (action === 'update') {
const index = webinarData.findIndex(w => w.id === id);
if (index === -1) return;
const inputs = target.closest('.grid').querySelectorAll('input');
inputs.forEach(input => {
const field = input.dataset.field;
let value = input.value;
if (input.type === 'number') value = parseFloat(value) || 0;
webinarData[index][field] = value;
});
} else if (action === 'delete') {
webinarData = webinarData.filter(w => w.id !== id);
}
renderAll();
showToast(`Record ${action}d successfully!`);
};
const handleGeneratePDF = () => {
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const metrics = calculateMetrics();
doc.setFontSize(20);
doc.text("Webinar Performance Report", 105, 20, null, null, 'center');
doc.setFontSize(10);
doc.text(`Generated on: ${new Date().toLocaleDateString()}`, 105, 26, null, null, 'center');
doc.autoTable({ startY: 35, head: [['Metric', 'Value']], body: [ ['Total Registrants', metrics.registrants.toLocaleString()], ['Avg. Attendance Rate', `${metrics.avgAttendance.toFixed(1)}%`], ['Avg. Engagement', `${metrics.avgEngagement.toFixed(1)}/10`], ['Total Questions', metrics.totalQuestions.toLocaleString()] ], theme: 'grid' });
let finalY = doc.lastAutoTable.finalY || 60;
doc.setFontSize(14);
doc.text("Registration vs. Attendance", 14, finalY + 15);
doc.addImage(elements.attendanceChartCanvas.toDataURL('image/png', 1.0), 'PNG', 14, finalY + 20, 180, 80);
finalY += 95;
doc.setFontSize(14);
doc.text("Webinar Log", 14, finalY);
const sortedData = [...webinarData].sort((a, b) => new Date(b.date) - new Date(a.date));
const tableBody = sortedData.slice(0, 20).map(w => {
const rate = w.registrants > 0 ? ((w.attendees / w.registrants) * 100).toFixed(1) : '0.0';
return [w.title, new Date(w.date).toLocaleDateString(), `${rate}%`, w.engagement.toFixed(1)];
});
doc.autoTable({ head: [['Title', 'Date', 'Attendance Rate', 'Engagement']], body: tableBody, startY: finalY + 5, theme: 'striped', headStyles: { fillColor: [4, 120, 87] } });
doc.save('Webinar-Performance-Report.pdf');
} catch (error) {
console.error("Failed to generate PDF:", error);
showToast("Error: Could not generate PDF.");
}
};
const switchTab = (tabName) => {
currentTab = tabName;
Object.values(elements.tabs).forEach(tab => tab.classList.add('hidden'));
Object.values(elements.tabButtons).forEach(btn => btn.classList.remove('active'));
elements.tabs[tabName].classList.remove('hidden');
elements.tabButtons[tabName].classList.add('active');
updateNavButtons();
};
const navigateTabs = (direction) => {
const currentIndex = tabOrder.indexOf(currentTab);
const newIndex = direction === 'next' ? Math.min(currentIndex + 1, tabOrder.length - 1) : Math.max(currentIndex - 1, 0);
if (newIndex !== currentIndex) switchTab(tabOrder[newIndex]);
};
const updateNavButtons = () => {
const currentIndex = tabOrder.indexOf(currentTab);
elements.navButtons.prev.disabled = currentIndex === 0;
elements.navButtons.next.disabled = currentIndex === tabOrder.length - 1;
};
const showToast = (message) => {
if (!elements.toast) return;
elements.toast.textContent = message;
elements.toast.classList.add('show');
setTimeout(() => { elements.toast.classList.remove('show'); }, 3000);
}
elements.addForm.addEventListener('submit', handleAddLog);
elements.editableList.addEventListener('click', handleConfigListClick);
elements.pdfButton.addEventListener('click', handleGeneratePDF);
elements.tabButtons.dashboard.addEventListener('click', () => switchTab('dashboard'));
elements.tabButtons.config.addEventListener('click', () => switchTab('config'));
elements.navButtons.prev.addEventListener('click', () => navigateTabs('prev'));
elements.navButtons.next.addEventListener('click', () => navigateTabs('next'));
renderAll();
updateNavButtons();
});