`;
html += categoryHtml;
}
container.innerHTML = html;
}
// --- Plan Compilation ---
function compilePlan() {
const container = document.getElementById('plan-summary');
const selectedStressors = Array.from(document.querySelectorAll('#stressors-checklist input:checked')).map(el => el.dataset.stressor);
const selectedStrategies = Array.from(document.querySelectorAll('#strategies-checklist input:checked')).map(el => ({ title: el.dataset.strategyTitle, desc: el.dataset.strategyDesc }));
if (selectedStressors.length === 0 && selectedStrategies.length === 0) {
container.innerHTML = '
Go to the previous tabs to select your stressors and strategies to generate your plan.
';
downloadPdfBtn.disabled = true;
return;
}
downloadPdfBtn.disabled = false;
let stressorsHtml = `
Identified Stressors
${selectedStressors.length > 0 ? selectedStressors.map(s => `- ${s}
`).join('') : '- No specific stressors identified.
'}
`;
let strategiesHtml = `
Your Coping Toolkit
${selectedStrategies.length > 0 ? selectedStrategies.map(s => `
${s.title}: ${s.desc}
`).join('') : '
No strategies selected.
'}
`;
container.innerHTML = stressorsHtml + '
' + strategiesHtml + '
';
}
// --- PDF Generation ---
async function generatePDF() {
const { jsPDF } = window.jspdf;
const originalButtonText = downloadPdfBtn.textContent;
downloadPdfBtn.textContent = 'Generating...';
downloadPdfBtn.disabled = true;
const pdfWrapper = document.createElement('div');
pdfWrapper.style.position = 'absolute';
pdfWrapper.style.left = '-9999px';
pdfWrapper.style.top = '0';
pdfWrapper.style.width = '800px';
pdfWrapper.style.backgroundColor = 'white';
pdfWrapper.className = 'p-8';
pdfWrapper.innerHTML = `
Emotional Resilience Plan
${new Date().toLocaleDateString()}
`;
const planSummaryClone = document.getElementById('plan-summary').cloneNode(true);
pdfWrapper.appendChild(planSummaryClone);
document.body.appendChild(pdfWrapper);
try {
const canvas = await html2canvas(pdfWrapper, { scale: 2, useCORS: true, logging: false });
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({ orientation: 'portrait', unit: 'px', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const imgWidth = canvas.width;
const imgHeight = canvas.height;
const ratio = imgWidth / imgHeight;
let finalImgWidth = pdfWidth;
let finalImgHeight = pdfWidth / ratio;
if (finalImgHeight > pdfHeight) {
finalImgHeight = pdfHeight;
finalImgWidth = pdfHeight * ratio;
}
pdf.addImage(imgData, 'PNG', 0, 0, finalImgWidth, finalImgHeight);
pdf.save('Resilience-Plan.pdf');
} catch (error) {
console.error("PDF Generation Error:", error);
} finally {
document.body.removeChild(pdfWrapper);
downloadPdfBtn.textContent = 'Download PDF Plan';
downloadPdfBtn.disabled = false;
}
}
// --- Event Listeners ---
downloadPdfBtn.addEventListener('click', generatePDF);
// --- Initial Call ---
initializeStressors();
initializeStrategies();
showTab(0);
});