`;
const resultsOutput = document.getElementById('results-output');
if (resultsOutput) {
resultsOutput.innerHTML = tableHtml;
}
// Switch to results tab
openTab('results-tab');
};
// Table Sorting
window.sortTable = function (n) {
const table = document.querySelector('.results-table');
if (!table) return;
const tbody = table.querySelector('tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const isNumeric = [false, true, true, true, true, true]; // Only Investment name is string
let ascending = table.querySelectorAll('th')[n].dataset.order === 'asc';
table.querySelectorAll('th').forEach(th => delete th.dataset.order);
table.querySelectorAll('th')[n].dataset.order = ascending ? 'desc' : 'asc';
rows.sort((a, b) => {
let aText = a.cells[n].textContent.trim();
let bText = b.cells[n].textContent.trim();
if (isNumeric[n]) {
aText = parseFloat(aText.replace('$', '')) || 0;
bText = parseFloat(bText.replace('$', '')) || 0;
return ascending ? aText - bText : bText - aText;
}
return ascending ? aText.localeCompare(bText) : bText.localeCompare(aText);
});
tbody.innerHTML = '';
rows.forEach(row => tbody.appendChild(row));
};
// Tab Navigation
window.openTab = function (tabId) {
const tabs = document.querySelectorAll('.tab-content');
const tabLinks = document.querySelectorAll('.tab-link');
tabs.forEach(tab => tab.classList.remove('active'));
tabLinks.forEach(link => link.classList.remove('active'));
const activeTab = document.getElementById(tabId);
if (activeTab) {
activeTab.classList.add('active');
const activeLink = document.querySelector(`.tab-link[onclick="openTab('${tabId}')"]`);
if (activeLink) activeLink.classList.add('active');
}
};
// Download PDF
window.downloadPDF = function () {
const resultsOutput = document.getElementById('results-output');
const pdfContent = resultsOutput.querySelector('.pdf-content');
if (!resultsOutput || !pdfContent || !pdfContent.querySelector('.results-table')) {
alert('No results available to download. Please simulate strategy first.');
return;
}
// Extract table data
const rows = [];
const headers = ['Investment', 'Dividend Income (USD)', 'Total Return (USD)', 'Annualized Return (%)', 'ESG Score', 'Strategy Score'];
rows.push(headers.map(header => ({ text: header, style: 'tableHeader' })));
const tableRows = pdfContent.querySelectorAll('.results-table tbody tr');
tableRows.forEach(row => {
const cells = row.querySelectorAll('td');
const rowData = Array.from(cells).map(cell => ({ text: cell.textContent }));
rows.push(rowData);
});
// Extract summary and recommendations
const totalDividendIncome = pdfContent.querySelector('.strategy-summary p:nth-child(1)')?.textContent || '';
const totalPortfolioReturn = pdfContent.querySelector('.strategy-summary p:nth-child(2)')?.textContent || '';
const avgStrategyScore = pdfContent.querySelector('.strategy-summary p:nth-child(3)')?.textContent || '';
const recommendations = pdfContent.querySelector('.strategy-summary p:nth-child(5)')?.textContent || '';
// Define PDF document structure
const docDefinition = {
content: [
{ text: 'Green Dividend Yield Strategy Simulator Report', style: 'header' },
{ text: '\n' },
{
table: {
headerRows: 1,
widths: ['*', 'auto', 'auto', 'auto', 'auto', 'auto'],
body: rows
},
layout: {
fillColor: function (rowIndex) {
return (rowIndex % 2 === 0 && rowIndex > 0) ? '#f2f2f2' : null;
},
hLineColor: '#ddd',
vLineColor: '#ddd'
}
},
{ text: '\n' },
{ text: 'Portfolio Summary', style: 'subheader' },
{ text: totalDividendIncome, style: 'body' },
{ text: totalPortfolioReturn, style: 'body' },
{ text: avgStrategyScore, style: 'body' },
{ text: '\n' },
{ text: 'Recommendations', style: 'subheader' },
{ text: recommendations, style: 'body' }
],
styles: {
header: {
fontSize: 18,
bold: true,
alignment: 'center',
color: '#333'
},
subheader: {
fontSize: 14,
bold: true,
color: '#333'
},
tableHeader: {
bold: true,
fontSize: 12,
color: 'white',
fillColor: '#4CAF50'
},
body: {
fontSize: 10,
color: '#333'
}
},
defaultStyle: {
fontSize: 10,
color: '#333'
},
pageMargins: [40, 60, 40, 60]
};
try {
// Generate and download PDF
pdfMake.createPdf(docDefinition).download('Green_Dividend_Strategy_Report.pdf');
} catch (err) {
console.error('PDF generation failed:', err);
alert('Failed to generate PDF. Please try again.');
}
};
});