`).join('');
};
const listenForEntries = () => {
if (!userId) return;
const collectionRef = collection(db, `artifacts/${appId}/users/${userId}/pcos_symptoms`);
const q = query(collectionRef, orderBy('date', 'desc'));
onSnapshot(q, (snapshot) => {
const entries = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
renderHistory(entries);
}, (error) => {
console.error("Error listening to history: ", error);
showMessage('Could not load history.', 'error');
});
};
// --- 5. PDF GENERATION ---
const downloadHistory = () => {
const { jsPDF } = window.jspdf;
const contentToPrint = document.getElementById('printable-content');
html2canvas(contentToPrint, { scale: 2, useCORS: true }).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const ratio = canvasWidth / pdfWidth;
const calculatedHeight = canvasHeight / ratio;
const pdfHeight = pdf.internal.pageSize.getHeight();
let heightLeft = calculatedHeight;
let position = 0;
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, calculatedHeight);
heightLeft -= pdfHeight;
while (heightLeft > 0) {
position -= pdfHeight;
pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, calculatedHeight);
heightLeft -= pdfHeight;
}
pdf.save('PCOS_Symptom_History.pdf');
}).catch(err => {
showMessage('Failed to generate PDF.', 'error');
});
};
// --- 6. EVENT LISTENERS & INITIALIZATION ---
document.querySelectorAll('.symptom-input-group input[type="range"]').forEach(slider => {
const valueSpan = slider.previousElementSibling.querySelector('span');
slider.addEventListener('input', () => {
valueSpan.textContent = slider.value;
});
});
saveBtn.addEventListener('click', saveEntry);
downloadBtn.addEventListener('click', downloadHistory);
// Set default date to today
entryDateInput.valueAsDate = new Date();
// Auth handling
if (auth) {
onAuthStateChanged(auth, (user) => {
if (user) {
userId = user.uid;
listenForEntries();
} else {
userId = null;
historyLog.innerHTML = `
Please sign in to save and view your history.
`; } }); (async () => { try { const initialAuthToken = typeof __initial_auth_token !== 'undefined' ? __initial_auth_token : null; if (initialAuthToken) { await signInWithCustomToken(auth, initialAuthToken); } else { await signInAnonymously(auth); } } catch (error) { console.error("Authentication failed:", error); showMessage('Could not authenticate user. Data will not be saved.', 'error'); } })(); }