Foreign Direct Investment (FDI) Trend Tracker
Visualize and analyze global Foreign Direct Investment (FDI) trends over time.
Analysis Setup
FDI Type
Select Countries/Regions (min. 1)
Time Horizon (Years)
FDI Trend Analysis
FDI Trends Over Time
AI-Powered Insights
Generating AI insights...
`; // Prepare a summary of the data for the AI prompt let dataSummary = `FDI ${fdiType} data for ${startYear}-${endYear}:\n`; selectedCountries.forEach(countryName => { const countryData = data[countryName]; const values = countryData.map(d => d[fdiType]); const avg = values.reduce((sum, val) => sum + val, 0) / values.length; const min = Math.min(...values); const max = Math.max(...values); dataSummary += `- ${countryName}: Avg ${avg.toFixed(2)}, Min ${min.toFixed(2)}, Max ${max.toFixed(2)}\n`; }); const prompt = ` You are an economic analyst specializing in Foreign Direct Investment (FDI). A user requested an analysis of FDI trends for the following countries/regions: ${selectedCountries.join(', ')} over the period ${startYear} to ${endYear}, showing ${fdiType} data. Here is a summary of the simulated data: ${dataSummary} Provide a brief analysis of the observed FDI trends, considering general economic principles. Cover: 1. Key Observations (e.g., strong growth, volatility, stagnation for specific regions/countries). 2. Potential Factors (e.g., global economic climate, regional policies, stability, market size - these are hypothetical as data is simulated). 3. Implications (e.g., for economic development, investment attractiveness). Format the response in simple HTML using only for titles and - for lists.
`;
try {
const payload = { contents: [{ role: "user", parts: [{ text: prompt }] }] };
const apiKey = ""; // API key is handled by the Canvas environment at runtime
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
const result = await response.json();
let text = "
Could not generate AI analysis. Please try again.
";
if (result.candidates && result.candidates[0] && result.candidates[0].content && result.candidates[0].content.parts[0]) {
text = result.candidates[0].content.parts[0].text;
}
aiContainer.innerHTML = text;
} catch (error) {
console.error("Error fetching AI insights:", error);
aiContainer.innerHTML = `Error generating AI insights.
`;
}
};
/**
* Exports the visible analysis summary (chart and AI insights) to a PDF document.
*/
window.downloadPDF = async () => {
const btn = document.getElementById('pdf-button-container')?.querySelector('button');
if (!btn) return;
btn.disabled = true;
btn.textContent = 'Generating PDF...';
const content = document.getElementById('summary-for-pdf');
if (!content) {
showMessageBox("PDF Error", "Content for PDF not found.");
btn.disabled = false;
btn.textContent = 'Download Analysis as PDF';
return;
}
try {
// Temporarily adjust chart size for better PDF rendering
const chartCanvas = document.getElementById('fdi-trend-chart');
const originalChartWidth = chartCanvas.style.width;
const originalChartHeight = chartCanvas.style.height;
chartCanvas.style.width = '1000px'; // Larger size for better quality capture
chartCanvas.style.height = '500px';
fdiChartInstance.resize(); // Trigger Chart.js to redraw with new dimensions
const canvas = await html2canvas(content, {
scale: 2, // Increase scale for better resolution
useCORS: true,
logging: false,
// Ensure the background is white for PDF
backgroundColor: '#ffffff'
});
// Restore original chart size
chartCanvas.style.width = originalChartWidth;
chartCanvas.style.height = originalChartHeight;
fdiChartInstance.resize();
const imgData = canvas.toDataURL('image/png');
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const imgWidth = pdfWidth - 20; // 10mm margin on each side
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let finalImgWidth = imgWidth;
let finalImgHeight = imgHeight;
if (finalImgHeight > pdfHeight - 20) { // If image is taller than page height
finalImgHeight = pdfHeight - 20;
finalImgWidth = (canvas.width * finalImgHeight) / canvas.height;
}
const x = (pdfWidth - finalImgWidth) / 2;
const y = (pdfHeight - finalImgHeight) / 2;
pdf.addImage(imgData, 'PNG', x, y, finalImgWidth, finalImgHeight);
pdf.save(`FDI_Trend_Analysis_${new Date().toISOString().slice(0, 10)}.pdf`);
showMessageBox("PDF Generated", "Your FDI trend analysis PDF has been successfully downloaded.");
} catch(e) {
console.error("PDF Generation Error: ", e);
showMessageBox("PDF Error", "An error occurred while generating the PDF. Please ensure all content is visible and try again.");
} finally {
btn.disabled = false;
btn.textContent = 'Download Analysis as PDF';
}
};
// --- INITIALIZATION ---
initCountrySelection(); // Populate the country checkboxes on load
});
Could not generate AI analysis. Please try again.
"; if (result.candidates && result.candidates[0] && result.candidates[0].content && result.candidates[0].content.parts[0]) { text = result.candidates[0].content.parts[0].text; } aiContainer.innerHTML = text; } catch (error) { console.error("Error fetching AI insights:", error); aiContainer.innerHTML = `Error generating AI insights.
`; } }; /** * Exports the visible analysis summary (chart and AI insights) to a PDF document. */ window.downloadPDF = async () => { const btn = document.getElementById('pdf-button-container')?.querySelector('button'); if (!btn) return; btn.disabled = true; btn.textContent = 'Generating PDF...'; const content = document.getElementById('summary-for-pdf'); if (!content) { showMessageBox("PDF Error", "Content for PDF not found."); btn.disabled = false; btn.textContent = 'Download Analysis as PDF'; return; } try { // Temporarily adjust chart size for better PDF rendering const chartCanvas = document.getElementById('fdi-trend-chart'); const originalChartWidth = chartCanvas.style.width; const originalChartHeight = chartCanvas.style.height; chartCanvas.style.width = '1000px'; // Larger size for better quality capture chartCanvas.style.height = '500px'; fdiChartInstance.resize(); // Trigger Chart.js to redraw with new dimensions const canvas = await html2canvas(content, { scale: 2, // Increase scale for better resolution useCORS: true, logging: false, // Ensure the background is white for PDF backgroundColor: '#ffffff' }); // Restore original chart size chartCanvas.style.width = originalChartWidth; chartCanvas.style.height = originalChartHeight; fdiChartInstance.resize(); const imgData = canvas.toDataURL('image/png'); const { jsPDF } = window.jspdf; const pdf = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' }); const pdfWidth = pdf.internal.pageSize.getWidth(); const pdfHeight = pdf.internal.pageSize.getHeight(); const imgWidth = pdfWidth - 20; // 10mm margin on each side const imgHeight = (canvas.height * imgWidth) / canvas.width; let finalImgWidth = imgWidth; let finalImgHeight = imgHeight; if (finalImgHeight > pdfHeight - 20) { // If image is taller than page height finalImgHeight = pdfHeight - 20; finalImgWidth = (canvas.width * finalImgHeight) / canvas.height; } const x = (pdfWidth - finalImgWidth) / 2; const y = (pdfHeight - finalImgHeight) / 2; pdf.addImage(imgData, 'PNG', x, y, finalImgWidth, finalImgHeight); pdf.save(`FDI_Trend_Analysis_${new Date().toISOString().slice(0, 10)}.pdf`); showMessageBox("PDF Generated", "Your FDI trend analysis PDF has been successfully downloaded."); } catch(e) { console.error("PDF Generation Error: ", e); showMessageBox("PDF Error", "An error occurred while generating the PDF. Please ensure all content is visible and try again."); } finally { btn.disabled = false; btn.textContent = 'Download Analysis as PDF'; } }; // --- INITIALIZATION --- initCountrySelection(); // Populate the country checkboxes on load });