// src/utils/pdfFonts.js
// Use a WeakMap to track fonts loaded per document instance
const fontsLoadedMap = new WeakMap();
const location = window.location.origin;

// Improved toBase64 function that handles large buffers without stack overflow
const toBase64 = (arrayBuffer) => {
    const bytes = new Uint8Array(arrayBuffer);
    let binary = "";
    const chunkSize = 1024; // Process in smaller chunks to avoid stack overflow

    for (let i = 0; i < bytes.length; i += chunkSize) {
        const chunk = bytes.slice(i, Math.min(i + chunkSize, bytes.length));
        binary += String.fromCharCode.apply(null, chunk);
    }

    return btoa(binary);
};

// Helper function to handle Bengali text rendering
export function renderBengaliText(doc, text, x, y, options = {}) {
    if (!text) {
        console.warn("Attempted to render empty text");
        return;
    }
    
    // Save current font settings
    let currentFont;
    try {
        currentFont = doc.getFont();
    } catch (error) {
        console.error("Error getting current font:", error);
        // Use default font as fallback
        currentFont = { fontName: "Helvetica", fontStyle: "normal" };
    }
    
    try {
        // Check if Bengali font is loaded for this document
        if (fontsLoadedMap.get(doc)) {
            // Switch to Bengali font
            doc.setFont("NotoSansBengali", "normal");
            // Render the text
            doc.text(text, x, y, options);
        } else {
            // Try to load fonts if not already loaded
            console.warn("Bengali fonts not loaded, attempting to load now");
            // For immediate rendering, fallback to default font
            doc.setFont(currentFont.fontName, currentFont.fontStyle);
            doc.text(text, x, y, options);
            
            // Attempt to load fonts for future use
            loadBengaliFont(doc).catch(err => 
                console.error("Failed to load Bengali fonts:", err)
            );
        }
    } catch (error) {
        console.error("Error rendering Bengali text:", error);
        // Fallback to previous font
        try {
            doc.setFont(currentFont.fontName, currentFont.fontStyle);
            doc.text(text, x, y, options);
        } catch (fallbackError) {
            console.error("Error rendering with fallback font:", fallbackError);
        }
    } finally {
        // Restore original font
        try {
            doc.setFont(currentFont.fontName, currentFont.fontStyle);
        } catch (restoreError) {
            console.error("Error restoring original font:", restoreError);
        }
    }
}

// Helper to check if text contains Bengali characters
export function containsBengali(text) {
    try {
        // Make sure text is a string
        if (typeof text !== "string") {
            return false;
        }
        
        // Check for Bengali Unicode range (\u0980-\u09FF)
        return text.match(/[\u0980-\u09FF]/) !== null;
    } catch (error) {
        console.error("Error checking for Bengali text:", error);
        return false;
    }
}

// Simple function to load Bengali font
export async function loadBengaliFont(doc) {
    // Check if fonts are already loaded for this specific document instance
    if (fontsLoadedMap.get(doc) === true) {
        return true;
    }

    try {
        // Regular font path
        const regularUrl = location + "/fonts/Bangla/Noto_Sans_Bengali/static/NotoSansBengali-Regular.ttf";
        // Bold font path
        const boldUrl = location + "/fonts/Bangla/Noto_Sans_Bengali/static/NotoSansBengali-Bold.ttf";
        
        
        // Load Regular font
        const regRes = await fetch(regularUrl);
        if (!regRes.ok) throw new Error(`Failed to load regular font: ${regRes.status} ${regRes.statusText}`);
        
        const regAb = await regRes.arrayBuffer();
        const regB64 = toBase64(regAb);
        
        // Load Bold font
        const boldRes = await fetch(boldUrl);
        if (!boldRes.ok) throw new Error(`Failed to load bold font: ${boldRes.status} ${boldRes.statusText}`);
        
        const boldAb = await boldRes.arrayBuffer();
        const boldB64 = toBase64(boldAb);

        // Add fonts to the virtual file system
        doc.addFileToVFS("NotoSansBengali-Regular.ttf", regB64);
        doc.addFileToVFS("NotoSansBengali-Bold.ttf", boldB64);

        // Register the fonts with specific names
        doc.addFont("NotoSansBengali-Regular.ttf", "NotoSansBengali", "normal");
        doc.addFont("NotoSansBengali-Bold.ttf", "NotoSansBengali", "bold");

        // Mark fonts as loaded for this specific document
        fontsLoadedMap.set(doc, true);
        return true;
    } catch (error) {
        console.error("Error loading Bengali fonts:", error);
        // Mark fonts as not loaded for this document
        fontsLoadedMap.set(doc, false);
        return false;
    }
}
