/*
|--------------------------------------------------------------------------
| PDF SERVICE — jsPDF + html2canvas
|--------------------------------------------------------------------------
|
| Gera PDF a partir de HTML renderizado no browser.
| Retorna Blob para download local e upload ao Storage.
|
*/

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

const A4 = { width: 595.28, height: 841.89 }; // pontos (72dpi)
const MARGIN = 40; // pontos

/**
 * Renderiza HTML completo em um Blob PDF.
 *
 * @param {string} html - HTML completo do documento (com <html>, <style>, etc.)
 * @returns {Promise<Blob>} PDF blob
 */
export async function htmlToPdfBlob(html) {
    // Cria container temporario oculto para renderizar o HTML
    const container = document.createElement('div');
    container.style.cssText = `
        position: fixed; left: -9999px; top: 0;
        width: 794px;
        background: white;
        font-family: 'Segoe UI', Arial, sans-serif;
        color: #1a1a1a;
    `;
    // 794px ≈ A4 width a 96dpi

    // Injeta o HTML (extrai o body content se vier documento completo)
    const bodyMatch = html.match(/<body[^>]*>([\s\S]*)<\/body>/i);
    const styleMatch = html.match(/<style[^>]*>([\s\S]*?)<\/style>/i);

    if (styleMatch) {
        const style = document.createElement('style');
        style.textContent = styleMatch[1];
        container.appendChild(style);
    }

    const content = document.createElement('div');
    content.innerHTML = bodyMatch ? bodyMatch[1] : html;
    container.appendChild(content);

    document.body.appendChild(container);

    try {
        const canvas = await html2canvas(container, {
            scale: 1.5, // boa qualidade sem exagerar no tamanho
            useCORS: true,
            backgroundColor: '#ffffff',
            width: 794,
            windowWidth: 794
        });

        const imgData = canvas.toDataURL('image/jpeg', 0.85);
        const pdf = new jsPDF('p', 'pt', 'a4');

        const imgWidth = A4.width - (MARGIN * 2);
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        const pageHeight = A4.height - (MARGIN * 2);
        let position = MARGIN;
        let heightLeft = imgHeight;

        pdf.addImage(imgData, 'JPEG', MARGIN, position, imgWidth, imgHeight, undefined, 'FAST');
        heightLeft -= pageHeight;

        while (heightLeft > 0) {
            position = -(imgHeight - heightLeft) + MARGIN;
            pdf.addPage();
            pdf.addImage(imgData, 'JPEG', MARGIN, position, imgWidth, imgHeight, undefined, 'FAST');
            heightLeft -= pageHeight;
        }

        return pdf.output('blob');
    } finally {
        document.body.removeChild(container);
    }
}

/**
 * Gera PDF e dispara download no browser.
 *
 * @param {string} html - HTML completo
 * @param {string} filename - nome do arquivo
 */
export async function htmlToPdfDownload(html, filename = 'documento.pdf') {
    const blob = await htmlToPdfBlob(html);
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

/**
 * Gera PDF e abre em nova aba para impressao.
 *
 * @param {string} html - HTML completo
 */
export async function htmlToPdfOpen(html) {
    const blob = await htmlToPdfBlob(html);
    const url = URL.createObjectURL(blob);
    window.open(url, '_blank');
}
