No article data to display.
`;
}
};
const renderViewsChart = (viewsByDate) => {
const ctx = elements.viewsChartCanvas?.getContext('2d');
if (!ctx) return;
const sortedDates = Object.keys(viewsByDate).sort((a, b) => new Date(a) - new Date(b));
const chartData = sortedDates.map(date => viewsByDate[date]);
if (viewsChart) viewsChart.destroy();
viewsChart = new Chart(ctx, {
type: 'line',
data: { labels: sortedDates, datasets: [{ label: 'Page Views', data: chartData, borderColor: '#4f46e5', backgroundColor: 'rgba(79, 70, 229, 0.1)', fill: true, tension: 0.3 }] },
options: { responsive: true, maintainAspectRatio: true }
});
};
const renderSourceChart = (trafficBySource) => {
const ctx = elements.sourceChartCanvas?.getContext('2d');
if (!ctx) return;
const labels = Object.keys(trafficBySource);
const data = Object.values(trafficBySource);
if (sourceChart) sourceChart.destroy();
sourceChart = new Chart(ctx, {
type: 'pie',
data: { labels, datasets: [{ label: 'Traffic by Source', data, backgroundColor: ['#3b82f6', '#10b981', '#ef4444', '#f59e0b'], hoverOffset: 4 }] },
options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { position: 'top' } } }
});
};
const renderConfigPanel = () => {
const container = elements.editableList;
if (!container) return;
container.innerHTML = '';
trafficData.forEach(d => {
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: trafficData.length > 0 ? Math.max(...trafficData.map(d => d.id)) + 1 : 1,
date: document.getElementById('recordDate').value,
views: getNumericValue('pageViews'),
uniques: getNumericValue('uniqueVisitors'),
avgTime: getNumericValue('avgTime'),
bounce: getNumericValue('bounceRate'),
sources: { Organic: 60, Social: 25, Direct: 10, Referral: 5 } // Using default distribution for simplicity
};
trafficData.push(newLog);
elements.addForm.reset();
renderAll();
showToast('Traffic 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 = trafficData.findIndex(d => d.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;
trafficData[index][field] = value;
});
} else if (action === 'delete') {
trafficData = trafficData.filter(d => d.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("Website Traffic 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 Page Views', metrics.totalViews.toLocaleString()], ['Unique Visitors', metrics.uniqueVisitors.toLocaleString()], ['Avg. Time on Page', `${metrics.avgTime.toFixed(0)}s`], ['Bounce Rate', `${metrics.bounceRate.toFixed(1)}%`] ], theme: 'grid' });
let finalY = doc.lastAutoTable.finalY || 60;
doc.setFontSize(14);
doc.text("Page Views Over Time", 14, finalY + 15);
doc.addImage(elements.viewsChartCanvas.toDataURL('image/png', 1.0), 'PNG', 14, finalY + 20, 180, 80);
finalY += 95;
doc.setFontSize(14);
doc.text("Top Articles", 14, finalY);
const tableBody = topArticles.map(a => [a.title, a.views.toLocaleString()]);
doc.autoTable({ head: [['Article Title', 'Page Views']], body: tableBody, startY: finalY + 5, theme: 'striped', headStyles: { fillColor: [79, 70, 229] } });
doc.save('Website-Traffic-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();
});