`;
pdfHtml += `
`;
if (dataToExport.results.length >= 2 && dataToExport.results[0] && dataToExport.results[1]) {
pdfHtml += ``;
}
pdfHtml += ``;
const pdfOutputEl = toolContainer.querySelector('#cibt-pdfOutput'); // Query inside handler
if (pdfOutputEl) pdfOutputEl.innerHTML = pdfHtml;
const opt = {
margin: [0.5, 0.5, 0.5, 0.5],
filename: `Credit_Impact_Report_${exportType}_${new Date().toISOString().slice(0,10)}.pdf`,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2, useCORS: true, logging: false },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
if (typeof html2pdf !== 'undefined' && pdfOutputEl) {
html2pdf().from(pdfOutputEl).set(opt).save()
.catch(err => { console.error("PDF generation failed:", err); alert("PDF generation error."); });
} else {
alert("PDF library not loaded or PDF output element not found.");
}
});
} else {
console.error("Download PDF button not found.");
}
// --- Tab Navigation ---
const tabs = Array.from(toolContainer.querySelectorAll('.cibt-tabcontent'));
const tabLinks = Array.from(toolContainer.querySelectorAll('.cibt-tablink'));
let currentTabIndex = 0;
if (!tabs.length || !tabLinks.length) {
console.error("CRITICAL: Tab content or tab links missing. UI will be broken.");
// return; // Optionally halt if tabs are fundamental
}
window.cibt_openTab = function(evt, tabName) {
if (!tabs.length || !tabLinks.length) { return; } // Guard
tabs.forEach(tab => { if(tab) tab.style.display = 'none'; });
tabLinks.forEach(link => { if(link) link.classList.remove('active'); });
const activeTabContent = toolContainer.querySelector('#' + tabName);
if(activeTabContent) {
activeTabContent.style.display = 'block';
} else {
console.error(`Tab content for ${tabName} not found. Defaulting to first tab.`);
if (tabs.length > 0 && tabs[0]) tabs[0].style.display = 'block'; // Fallback
if (tabLinks.length > 0 && tabLinks[0]) tabLinks[0].classList.add('active');
currentTabIndex = 0;
cibt_updateNavButtons();
return;
}
let clickedIndex = -1;
if (evt && evt.currentTarget) {
evt.currentTarget.classList.add('active');
clickedIndex = tabLinks.indexOf(evt.currentTarget);
} else {
clickedIndex = tabLinks.findIndex(link => {
if (!link) return false;
const onclickAttr = link.getAttribute('onclick');
return onclickAttr && onclickAttr.includes(`'${tabName}'`);
});
if (clickedIndex !== -1 && tabLinks[clickedIndex]) {
tabLinks[clickedIndex].classList.add('active');
} else { // Fallback if findIndex fails (e.g. initial call with mismatch)
if (tabLinks.length > 0 && tabLinks[0]) tabLinks[0].classList.add('active');
clickedIndex = 0;
}
}
currentTabIndex = (clickedIndex !== -1 && clickedIndex < tabs.length) ? clickedIndex : 0;
cibt_updateNavButtons();
const exportSelectEl = toolContainer.querySelector('#cibt-exportSelect');
if (exportSelectEl) {
if (tabName === 'cibt-tabMortgage') exportSelectEl.value = 'mortgage';
else if (tabName === 'cibt-tabAutoLoan') exportSelectEl.value = 'autoLoan';
else if (tabName === 'cibt-tabPersonalLoan') exportSelectEl.value = 'personalLoan';
else if (tabName === 'cibt-tabCreditCard') exportSelectEl.value = 'creditCard';
}
}
window.cibt_navigateTab = function(direction) {
if (!tabs.length || !tabLinks.length) { return; } // Guard
let newIndex = currentTabIndex;
if (direction === 'next' && currentTabIndex < tabs.length - 1) newIndex++;
else if (direction === 'prev' && currentTabIndex > 0) newIndex--;
if (tabLinks[newIndex] && newIndex !== currentTabIndex) tabLinks[newIndex].click();
}
function cibt_updateNavButtons() {
const prevBtnEl = toolContainer.querySelector('#cibt-prevButton');
const nextBtnEl = toolContainer.querySelector('#cibt-nextButton');
if(prevBtnEl) prevBtnEl.disabled = currentTabIndex === 0;
if(nextBtnEl && tabs) nextBtnEl.disabled = currentTabIndex >= tabs.length - 1;
}
// --- Initialization ---
function initializeTool() {
const autoTermEl = toolContainer.querySelector('#cibt-autoLoanTermMonths');
if (autoTermEl) autoTermEl.value = "60";
else console.warn("Element #cibt-autoLoanTermMonths not found during init.");
if (tabs.length > 0 && tabLinks.length > 0) { // Only open tab if elements exist
cibt_openTab(null, 'cibt-tabMortgage');
} else {
console.error("Cannot initialize tabs - tab or link elements are missing.");
}
}
let attempts = 0;
function checkLibrariesAndInit_cibt() {
if (typeof html2pdf !== 'undefined') {
initializeTool();
} else if (attempts < 20) {
attempts++;
setTimeout(checkLibrariesAndInit_cibt, 100);
} else {
console.warn("Warning: PDF generation library (html2pdf.js) could not be loaded. PDF export will not work.");
// alert("Warning: PDF generation library could not be loaded. PDF export will not work.");
initializeTool();
}
}
checkLibrariesAndInit_cibt();
})();
Results Comparison:
`; if (dataToExport.inputs.type === 'Credit Card APR') { pdfHtml += `| Scenario | Est. Monthly Interest ($) | ||
|---|---|---|---|
| ${res.scenario} | ${res.monthlyInterest.toFixed(2)} |
| Scenario | Monthly Payment ($) | Total Interest Paid ($) | Total Loan Cost ($) |
|---|---|---|---|
| ${res.scenario} | ${res.monthlyPayment.toFixed(2)} | ${res.totalInterest.toFixed(2)} | ${res.totalCost.toFixed(2)} |
Budget Impact Summary (Scenario A vs. Scenario B):
`; if (dataToExport.inputs.type === 'Credit Card APR') { const diffAB = dataToExport.results[0].monthlyInterest - dataToExport.results[1].monthlyInterest; pdfHtml += `Scenario A has an estimated monthly interest cost $${Math.abs(diffAB).toFixed(2)} ${diffAB < 0 ? 'lower' : 'higher'} than Scenario B.
`; } else { const paymentDiffAB = dataToExport.results[1].monthlyPayment - dataToExport.results[0].monthlyPayment; const interestDiffAB = dataToExport.results[1].totalInterest - dataToExport.results[0].totalInterest; pdfHtml += `Scenario A's monthly payment is $${Math.abs(paymentDiffAB).toFixed(2)} ${paymentDiffAB > 0 ? 'lower' : 'higher'}.
`; pdfHtml += `Choosing Scenario A could ${interestDiffAB > 0 ? 'save' : 'cost an extra'} $${Math.abs(interestDiffAB).toFixed(2)} in total interest.
`; } pdfHtml += `