// assets/js/pdf-worker.js - Fast PDF Generator
importScripts('https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js');

// Cache for loaded images
const imageCache = new Map();

self.onmessage = async function(e) {
    if (e.data.type === 'generate') {
        try {
            const { jsPDF } = self.jspdf;
            
            // Create PDF in landscape with proper margins
            const pdf = new jsPDF({
                orientation: 'landscape',
                unit: 'mm',
                format: 'a4'
            });
            
            const pageWidth = pdf.internal.pageSize.getWidth();  // 297mm for A4 landscape
            const pageHeight = pdf.internal.pageSize.getHeight(); // 210mm for A4 landscape
            
            const margin = 15;
            const headerHeight = 30;
            const footerHeight = 15;
            const contentHeight = pageHeight - headerHeight - footerHeight - (2 * margin);
            
            let currentPage = 1;
            
            // Add header to first page
            addHeader(pdf, pageWidth, margin, e.data.projectName);
            
            // Process images in grid (3 per page)
            const images = e.data.images;
            const imagesPerPage = 3;
            let currentImageIndex = 0;
            
            for (let page = 0; page < Math.ceil(images.length / imagesPerPage); page++) {
                if (page > 0) {
                    pdf.addPage();
                    currentPage++;
                    addHeader(pdf, pageWidth, margin, e.data.projectName);
                }
                
                // Calculate grid positions for this page
                const gridWidth = (pageWidth - (2 * margin)) / 3;
                const gridHeight = contentHeight;
                const padding = 5;
                
                // Get images for this page
                const pageImages = images.slice(page * imagesPerPage, (page + 1) * imagesPerPage);
                
                // Process images in parallel
                await Promise.all(pageImages.map(async (imgData, index) => {
                    const col = index % 3;
                    const x = margin + (col * gridWidth);
                    const y = margin + headerHeight;
                    
                    // Draw image container
                    pdf.setDrawColor(220, 220, 220);
                    pdf.setFillColor(245, 245, 245);
                    pdf.roundedRect(x, y, gridWidth, gridHeight, 2, 2, 'FD');
                    
                    try {
                        // Load image (use cache if available)
                        let imageData;
                        if (imageCache.has(imgData.src)) {
                            imageData = imageCache.get(imgData.src);
                        } else {
                            const response = await fetch(imgData.src);
                            const blob = await response.blob();
                            imageData = await blobToDataURL(blob);
                            imageCache.set(imgData.src, imageData);
                        }
                        
                        // Calculate image dimensions
                        const img = await loadImage(imageData);
                        const maxImgWidth = gridWidth - (2 * padding);
                        const maxImgHeight = 120; // Fixed height for images
                        
                        let imgWidth = img.width;
                        let imgHeight = img.height;
                        const aspectRatio = imgWidth / imgHeight;
                        
                        if (imgHeight > maxImgHeight) {
                            imgHeight = maxImgHeight;
                            imgWidth = imgHeight * aspectRatio;
                        }
                        if (imgWidth > maxImgWidth) {
                            imgWidth = maxImgWidth;
                            imgHeight = imgWidth / aspectRatio;
                        }
                        
                        // Center image in grid cell
                        const imgX = x + (gridWidth - imgWidth) / 2;
                        const imgY = y + 25; // Space for model info
                        
                        // Add image
                        pdf.addImage(imageData, 'JPEG', imgX, imgY, imgWidth, imgHeight);
                        
                        // Add model info above image
                        pdf.setFontSize(12);
                        pdf.setFont(undefined, 'bold');
                        pdf.setTextColor(0, 0, 0);
                        
                        // Truncate long model names
                        const modelName = truncateText(imgData.modelName, 20);
                        const textWidth = pdf.getTextWidth(modelName);
                        const textX = x + (gridWidth - textWidth) / 2;
                        
                        pdf.text(modelName, textX, y + 15);
                        
                        // Add Instagram if available
                        if (imgData.instagram) {
                            pdf.setFontSize(9);
                            pdf.setFont(undefined, 'normal');
                            pdf.setTextColor(59, 89, 152); // Instagram blue
                            const instaText = `@${imgData.instagram}`;
                            const instaWidth = pdf.getTextWidth(instaText);
                            const instaX = x + (gridWidth - instaWidth) / 2;
                            pdf.text(instaText, instaX, y + 22);
                        }
                        
                        // Add model details below image
                        if (imgData.details) {
                            const detailsY = imgY + imgHeight + 10;
                            const maxDetailsHeight = gridHeight - (detailsY - y) - 10;
                            
                            pdf.setFontSize(8);
                            pdf.setFont(undefined, 'normal');
                            pdf.setTextColor(100, 100, 100);
                            
                            const detailsLines = wrapText(pdf, imgData.details, gridWidth - 20);
                            const lineHeight = 4;
                            const maxLines = Math.floor(maxDetailsHeight / lineHeight);
                            
                            for (let i = 0; i < Math.min(detailsLines.length, maxLines); i++) {
                                const lineWidth = pdf.getTextWidth(detailsLines[i]);
                                const lineX = x + (gridWidth - lineWidth) / 2;
                                pdf.text(detailsLines[i], lineX, detailsY + (i * lineHeight));
                            }
                            
                            if (detailsLines.length > maxLines) {
                                pdf.text('...', x + gridWidth - 10, detailsY + (maxLines * lineHeight));
                            }
                        }
                        
                    } catch (imgError) {
                        console.error('Image error:', imgError);
                        pdf.setFontSize(10);
                        pdf.setTextColor(255, 0, 0);
                        pdf.text('Image failed to load', x + 10, y + 60);
                    }
                }));
                
                // Report progress
                const progress = Math.round(((page + 1) / Math.ceil(images.length / imagesPerPage)) * 100);
                self.postMessage({ type: 'progress', progress: progress });
            }
            
            // Add footer to all pages
            const totalPages = pdf.internal.getNumberOfPages();
            for (let i = 1; i <= totalPages; i++) {
                pdf.setPage(i);
                addFooter(pdf, pageWidth, pageHeight, i, totalPages);
            }
            
            // Generate PDF
            const pdfOutput = pdf.output('arraybuffer');
            
            self.postMessage({
                type: 'complete',
                pdf: pdfOutput
            });
            
        } catch (error) {
            console.error('PDF generation error:', error);
            self.postMessage({
                type: 'error',
                error: error.message
            });
        }
    }
};

// Helper functions
function addHeader(pdf, pageWidth, margin, projectName) {
    pdf.setFillColor(0, 0, 0);
    pdf.rect(0, 0, pageWidth, 25, 'F');
    
    pdf.setTextColor(255, 255, 255);
    pdf.setFontSize(18);
    pdf.setFont(undefined, 'bold');
    pdf.text('GO PRODUCTIONS', margin, 17);
    
    pdf.setFontSize(12);
    pdf.text(projectName || 'Model Portfolio', pageWidth - margin - pdf.getTextWidth(projectName || 'Model Portfolio'), 17);
    
    pdf.setDrawColor(255, 255, 255);
    pdf.setLineWidth(0.5);
    pdf.line(margin, 20, pageWidth - margin, 20);
}

function addFooter(pdf, pageWidth, pageHeight, currentPage, totalPages) {
    pdf.setFontSize(9);
    pdf.setTextColor(100, 100, 100);
    pdf.setFont(undefined, 'normal');
    
    const date = new Date().toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
    
    pdf.text(`Generated: ${date}`, 15, pageHeight - 10);
    pdf.text(`Page ${currentPage} of ${totalPages}`, pageWidth - 30, pageHeight - 10);
    
    pdf.setFontSize(8);
    pdf.text('© GO Productions', pageWidth / 2 - pdf.getTextWidth('© GO Productions') / 2, pageHeight - 10);
}

function blobToDataURL(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
    });
}

function loadImage(src) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = src;
    });
}

function truncateText(text, maxLength) {
    return text.length > maxLength ? text.substring(0, maxLength - 3) + '...' : text;
}

function wrapText(pdf, text, maxWidth) {
    const words = text.split(' ');
    const lines = [];
    let currentLine = '';
    
    for (const word of words) {
        const testLine = currentLine ? `${currentLine} ${word}` : word;
        const testWidth = pdf.getTextWidth(testLine);
        
        if (testWidth > maxWidth && currentLine) {
            lines.push(currentLine);
            currentLine = word;
        } else {
            currentLine = testLine;
        }
    }
    
    if (currentLine) {
        lines.push(currentLine);
    }
    
    return lines;
}