No logs available or found for the selected date range. Please add logs in Tab 1.
';
const dashboardDisplayEl = document.getElementById('shpi-dashboard-display');
const insightsListEl = document.getElementById('shpi-insights-list');
const avgSummaryEl = document.getElementById('shpi-average-summary-list');
// Clear previous charts safely
Object.values(shpiChartInstances).forEach(chart => { if (chart) chart.destroy(); });
shpiChartInstances = {}; // Reset instances
if (shpiSessionLogs.length === 0 && shpiCurrentTabIndex === 1) {
if(dashboardDisplayEl) dashboardDisplayEl.innerHTML = noDataMsg;
if(insightsListEl) insightsListEl.innerHTML = '
No data to analyze.';
if(avgSummaryEl) avgSummaryEl.innerHTML = '
No data for averages.';
return;
}
const startDateStr = document.getElementById('shpi-analysis-start-date').value;
const endDateStr = document.getElementById('shpi-analysis-end-date').value;
if(!startDateStr || !endDateStr) return;
const startDate = new Date(startDateStr + "T00:00:00");
const endDate = new Date(endDateStr + "T23:59:59");
const filteredLogs = shpiSessionLogs.filter(log => log.date >= startDate && log.date <= endDate);
if (filteredLogs.length === 0 && shpiCurrentTabIndex === 1) {
if(dashboardDisplayEl) dashboardDisplayEl.innerHTML = noDataMsg;
if(insightsListEl) insightsListEl.innerHTML = '
No data in selected range for insights.';
if(avgSummaryEl) avgSummaryEl.innerHTML = '
No data in range for averages.';
return;
}
// Calculate Averages
if(avgSummaryEl){
if(filteredLogs.length > 0){
const calcAvg = (key) => filteredLogs.reduce((s,l)=>s+l[key],0)/filteredLogs.length;
avgSummaryEl.innerHTML = `
Avg. Sleep: ${calcAvg('sleepHours').toFixed(1)}h (Quality: ${calcAvg('sleepQuality').toFixed(1)}/5)
Avg. Mood: ${calcAvg('mood').toFixed(1)}/5 | Avg. Stress: ${calcAvg('stressLevel').toFixed(1)}/5 | Avg. Energy: ${calcAvg('energyLevel').toFixed(1)}/5
Avg. Tasks Completed: ${calcAvg('tasksCompleted').toFixed(1)}
Avg. Productivity: ${calcAvg('productivity').toFixed(1)}/5 | Avg. Focus: ${calcAvg('focus').toFixed(1)}/5
Avg. Physical Activity: ${calcAvg('physicalActivity').toFixed(1)} min
`;
} else { avgSummaryEl.innerHTML = '
No data in range for averages.'; }
}
const chartData = (key) => filteredLogs.map(log => ({x: log.date, y: log[key]}));
if(dashboardDisplayEl) dashboardDisplayEl.innerHTML = `
Sleep Duration & Quality
Mood Over Time
Stress Level Over Time
Energy Level Over Time
Productivity Rating Over Time
Focus Level Over Time
Physical Activity (min)
`;
shpiRenderLineChart('shpi-mood-chart', chartData('mood'), 'Mood (1-5)', 'var(--success-color)', 5);
shpiRenderLineChart('shpi-stress-chart', chartData('stressLevel'), 'Stress (1-5)', 'var(--danger-color)', 5);
shpiRenderLineChart('shpi-energy-chart', chartData('energyLevel'), 'Energy (1-5)', 'var(--accent-color)', 5);
shpiRenderLineChart('shpi-productivity-chart', chartData('productivity'), 'Productivity (1-5)', 'var(--primary-color)', 5);
shpiRenderLineChart('shpi-focus-chart', chartData('focus'), 'Focus (1-5)', 'var(--dark-color)', 5);
shpiRenderLineChart('shpi-activity-chart', chartData('physicalActivity'), 'Physical Activity (min)', 'var(--secondary-color)');
const sleepQualityData = filteredLogs.map(log => ({x: log.date, y: log.sleepQuality}));
const sleepHoursData = filteredLogs.map(log => ({x: log.date, y: log.sleepHours}));
const sleepCtx = document.getElementById('shpi-sleep-chart');
if (sleepCtx) {
if (shpiChartInstances['shpi-sleep-chart']) shpiChartInstances['shpi-sleep-chart'].destroy();
shpiChartInstances['shpi-sleep-chart'] = new Chart(sleepCtx.getContext('2d'), {
type: 'line', data: {
datasets: [
{ label: 'Sleep Quality (1-5)', data: sleepQualityData, borderColor: 'var(--primary-color)', yAxisID: 'yQuality', tension: 0.1, borderWidth:2 },
{ label: 'Sleep Hours', data: sleepHoursData, borderColor: 'var(--accent-color)', yAxisID: 'yHours', tension: 0.1, borderWidth:2 }
]},
options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
scales: {
x: { type: 'time', time: { unit: 'day', tooltipFormat: 'MMM dd, yy' } },
yQuality: { type: 'linear', position: 'left', min:0, suggestedMax:5, title:{display:true, text:'Quality (1-5)'} },
yHours: { type: 'linear', position: 'right', min:0, suggestedMax:12, title:{display:true, text:'Hours'}, grid: { drawOnChartArea: false } }
}
}
});
}
if(insightsListEl){
insightsListEl.innerHTML = ''; let insightsGeneratedCount = 0;
if (filteredLogs.length >= 3) {
const avgSleep = filteredLogs.reduce((s,l)=>s+l.sleepHours,0)/filteredLogs.length;
const avgProd = filteredLogs.reduce((s,l)=>s+l.productivity,0)/filteredLogs.length;
const avgFocus = filteredLogs.reduce((s,l)=>s+l.focus,0)/filteredLogs.length;
if(avgSleep < 6.5) { insightsListEl.innerHTML += `
Your average sleep duration of ${avgSleep.toFixed(1)}h is below the recommended 7-9 hours. This could be impacting your daytime energy and focus.`; insightsGeneratedCount++;}
let lowSleepDays = filteredLogs.filter(l => l.sleepHours < 6.5);
let highSleepDays = filteredLogs.filter(l => l.sleepHours >= 7.5);
if(lowSleepDays.length > 2 && highSleepDays.length > 2){
const avgFocusOnLowSleep = lowSleepDays.reduce((s,l)=>s+l.focus,0)/lowSleepDays.length;
const avgFocusOnHighSleep = highSleepDays.reduce((s,l)=>s+l.focus,0)/highSleepDays.length;
if(avgFocusOnHighSleep > avgFocusOnLowSleep * 1.15){ // 15% improvement
insightsListEl.innerHTML += `
Your focus tends to be higher (avg ${avgFocusOnHighSleep.toFixed(1)}/5) on days after more sleep, compared to days with less sleep (avg ${avgFocusOnLowSleep.toFixed(1)}/5).`; insightsGeneratedCount++;
}
}
const activeDays = filteredLogs.filter(l => l.physicalActivity >= 30);
if(activeDays.length > filteredLogs.length / 3){
const avgMoodOnActiveDays = activeDays.reduce((s,l)=>s+l.mood,0)/activeDays.length;
if(avgMoodOnActiveDays > 3.5) {insightsListEl.innerHTML += `
Physical activity appears to correlate with positive mood levels for you (avg mood ${avgMoodOnActiveDays.toFixed(1)}/5 on active days). Keep it up!`; insightsGeneratedCount++;}
}
}
if(insightsGeneratedCount === 0 && filteredLogs.length > 0) insightsListEl.innerHTML += `
Keep logging consistently to uncover more personalized insights between your habits, well-being, and productivity!`;
else if (filteredLogs.length === 0) insightsListEl.innerHTML += `
No data in selected range to provide insights.`;
}
}
function shpiRenderLineChart(canvasId, dataPoints, label, color, suggestedMaxVal = undefined) {
const ctx = document.getElementById(canvasId);
if (!ctx) return;
if (shpiChartInstances[canvasId]) shpiChartInstances[canvasId].destroy();
shpiChartInstances[canvasId] = new Chart(ctx.getContext('2d'), {
type: 'line',
data: { datasets: [{ label: label, data: dataPoints, borderColor: color, tension: 0.1, fill: false, borderWidth: 2 }] },
options: {
responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
scales: { x: { type: 'time', time: { unit: 'day', tooltipFormat: 'MMM dd, yy', displayFormats: {'day': 'MMM dd'} } },
y: { beginAtZero: (suggestedMaxVal ? false : true), min: (suggestedMaxVal ? 1 : undefined) , suggestedMax: suggestedMaxVal, title: {display:true, text:label.split('(')[0].trim()}} }
}
});
}
// PDF Download
function shpiDownloadPDF() {
const dashboardDisplayEl = document.getElementById('shpi-dashboard-display');
if (!dashboardDisplayEl || dashboardDisplayEl.innerHTML.includes("Log daily data") || shpiSessionLogs.length === 0) {
alert("Please log some data and view the dashboard first."); return;
}
const analysisStartDate = document.getElementById('shpi-analysis-start-date').value;
const analysisEndDate = document.getElementById('shpi-analysis-end-date').value;
let pdfHTML = `
Smart Healthy Productivity Insights Report
`;
pdfHTML += `
Analysis Period: ${analysisStartDate} to ${analysisEndDate}
`;
const avgSummaryContent = document.getElementById('shpi-average-summary-list').outerHTML;
if(avgSummaryContent) pdfHTML += `
Overall Averages (Selected Period)
${avgSummaryContent}`;
const chartsToInclude = [
{instance: shpiChartInstances['shpi-sleep-chart'], title: "Sleep Duration & Quality"},
{instance: shpiChartInstances['shpi-mood-chart'], title: "Mood Over Time"},
{instance: shpiChartInstances['shpi-stress-chart'], title: "Stress Level Over Time"},
{instance: shpiChartInstances['shpi-energy-chart'], title: "Energy Level Over Time"},
{instance: shpiChartInstances['shpi-productivity-chart'], title: "Productivity Rating Over Time"},
{instance: shpiChartInstances['shpi-focus-chart'], title: "Focus Level Over Time"},
{instance: shpiChartInstances['shpi-activity-chart'], title: "Physical Activity (min)"}
];
chartsToInclude.forEach(chartInfo => {
if(chartInfo.instance){
try {
pdfHTML += `
${chartInfo.title}
`;
} catch (e) { console.error("Error converting chart to image for PDF: ", chartInfo.title, e); }
}
});
const insightsContent = document.getElementById('shpi-insights-list').outerHTML;
if(insightsContent) pdfHTML += `
"Smart" Insights & Recommendations
${insightsContent}`;
const filteredLogsForPDF = shpiSessionLogs.filter(log => {
const logDateOnly = log.date.toISOString().split('T')[0];
return logDateOnly >= analysisStartDate && logDateOnly <= analysisEndDate;
});
if (filteredLogsForPDF.length > 0 && confirm("Include detailed daily logs in PDF? This can make the PDF long.")) {
pdfHTML += `
Detailed Logs (${analysisStartDate} to ${analysisEndDate})
`;
pdfHTML += `
| Date | Sleep(H) | Slp(Q) | Stress | Mood | Energy | Activity(m) | Tasks | Prod. | Focus | Notes |
`;
filteredLogsForPDF.forEach(log => {
pdfHTML += `
| ${log.date.toLocaleDateString()} | ${log.sleepHours.toFixed(1)} | ${log.sleepQuality} |
${log.stressLevel} | ${log.mood} | ${log.energyLevel} | ${log.physicalActivity} |
${log.tasksCompleted} | ${log.productivity} | ${log.focus} |
${log.notes.substring(0,30)}${log.notes.length > 30 ? '...' : ''} |
`;
});
pdfHTML += `
`;
}
const pdfContainer = document.getElementById('shpi-report-content-for-pdf');
pdfContainer.innerHTML = pdfHTML;
const opt = {
margin: [0.5, 0.3, 0.5, 0.3], filename: `Healthy_Productivity_Insights_${analysisStartDate}_to_${analysisEndDate}.pdf`,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2, useCORS: true, logging: false, scrollX:0, scrollY: -window.scrollY, windowWidth: pdfContainer.scrollWidth + 100 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' },
pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
};
html2pdf().from(pdfContainer).set(opt).save().then(() => {
pdfContainer.innerHTML = '';
}).catch(err => {
console.error("Error generating PDF:", err);
pdfContainer.innerHTML = '';
alert("An error occurred while generating the PDF. Check console for details.");
});
}