import html2canvas from 'html2canvas-pro';
import jsPDF from 'jspdf';

/**
 * Render a DOM element to a paginated A4 PDF and trigger a download.
 * Mirrors the project's existing contract-export pattern (html2canvas-pro →
 * jsPDF.addImage). The element should be on-screen or positioned off-canvas
 * (not display:none) so it is laid out before capture.
 */
export async function exportElementToPdf(element: HTMLElement, filename: string): Promise<void> {
    const canvas = await html2canvas(element, { scale: 2, backgroundColor: '#ffffff' });
    const imgData = canvas.toDataURL('image/png');

    const pdf = new jsPDF('p', 'mm', 'a4');
    const pageWidth = pdf.internal.pageSize.getWidth();
    const pageHeight = pdf.internal.pageSize.getHeight();

    const imgWidth = pageWidth;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;

    let heightLeft = imgHeight;
    let position = 0;

    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft > 0) {
        position -= pageHeight;
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
    }

    pdf.save(filename);
}
