`;
elements.resultsArea.classList.remove('hidden');
drawTriangle(a, b);
}
function drawTriangle(a, b) {
const w = elements.canvas.width;
const h = elements.canvas.height;
const padding = 30;
// Scale factor to fit the triangle in the canvas
const maxSide = Math.max(a, b);
const scale = (Math.min(w, h) - 2 * padding) / maxSide;
const scaledA = a * scale;
const scaledB = b * scale;
const x0 = padding;
const y0 = h - padding;
const x1 = padding + scaledB;
const y1 = h - padding;
const x2 = padding;
const y2 = h - padding - scaledA;
ctx.clearRect(0, 0, w, h);
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.closePath();
ctx.strokeStyle = '#4f46e5';
ctx.lineWidth = 2;
ctx.stroke();
// Labels
ctx.fillStyle = '#374151';
ctx.font = '14px Inter';
ctx.fillText('a', x0 - 15, y0 - scaledA / 2);
ctx.fillText('b', x0 + scaledB / 2, y0 + 15);
ctx.fillText('c', x0 + scaledB / 2, y0 - scaledA / 2);
ctx.fillText('A', x2 + 5, y2 + 15);
ctx.fillText('B', x1 - 15, y1 - 5);
ctx.fillText('C', x0 - 5, y0 - 5);
}
function clearAll() {
Object.values(elements.inputs).forEach(input => input.value = '');
elements.resultsArea.classList.add('hidden');
ctx.clearRect(0, 0, elements.canvas.width, elements.canvas.height);
lastSolution = null;
clearError();
}
function downloadPdf() {
if (!lastSolution) {
showError("Please solve a triangle first.");
return;
}
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const canvasImage = elements.canvas.toDataURL('image/png');
doc.setFont('helvetica', 'bold');
doc.setFontSize(18);
doc.text('Triangle Solver Report', doc.internal.pageSize.getWidth() / 2, 20, { align: 'center' });
const tableBody = [
['Side a', lastSolution.a.toFixed(4)], ['Side b', lastSolution.b.toFixed(4)], ['Side c (Hypotenuse)', lastSolution.c.toFixed(4)],
['Angle A', lastSolution.A.toFixed(4) + '°'], ['Angle B', lastSolution.B.toFixed(4) + '°'], ['Angle C', '90°'],
['Area', lastSolution.area.toFixed(4)], ['Perimeter', lastSolution.perimeter.toFixed(4)],
];
doc.autoTable({
startY: 30,
head: [['Property', 'Value']],
body: tableBody,
theme: 'grid', headStyles: { fillColor: [79, 70, 229] }
});
doc.addImage(canvasImage, 'PNG', 15, doc.autoTable.previous.finalY + 15, 80, 80);
doc.save('triangle-solver-report.pdf');
}
// --- Event Listeners ---
elements.tabButtons.forEach(btn => btn.addEventListener('click', () => switchTab(btn.dataset.tab)));
elements.btnSolve.addEventListener('click', solveTriangle);
elements.btnClear.addEventListener('click', clearAll);
elements.btnDownloadPdf.addEventListener('click', downloadPdf);
});