/**
 * Font Manager Utility
 * Handles loading and registering custom fonts for jsPDF.
 * Specifically manages Noto Sans Symbols 2 for consistent symbol rendering.
 */

// Using the direct TTF file from Supabase storage
const FONT_URL = 'https://nenznrmcinpmomjgnzfp.supabase.co/storage/v1/object/public/fonts/NotoSansSymbols2-Regular.ttf';
const FONT_NAME = 'NotoSymbols';
const FONT_FILE_NAME = 'NotoSansSymbols2-Regular.ttf';

let cachedFontData = null;

/**
 * Fetches the Noto Sans Symbols 2 font and converts it to base64.
 * Uses in-memory caching to prevent redundant network requests.
 * @returns {Promise<string|null>} Base64 encoded font data or null if failed
 */
export const loadNotoSymbolsFont = async () => {
  if (cachedFontData) {
    console.log('FontManager: Using cached NotoSymbols font data');
    return cachedFontData;
  }

  console.log('FontManager: Fetching NotoSymbols font from', FONT_URL);
  try {
    const response = await fetch(FONT_URL);
    if (!response.ok) {
      throw new Error(`Failed to fetch font: ${response.status} ${response.statusText}`);
    }
    const blob = await response.blob();
    
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        // reader.result is like "data:font/ttf;base64,AAEAAA..."
        // We need just the base64 part for jsPDF
        if (typeof reader.result === 'string') {
          const base64data = reader.result.split(',')[1];
          cachedFontData = base64data;
          console.log('FontManager: NotoSymbols font loaded and cached successfully');
          resolve(base64data);
        } else {
          reject(new Error('Failed to convert font blob to base64'));
        }
      };
      reader.onerror = () => reject(new Error('FileReader failed to read font blob'));
      reader.readAsDataURL(blob);
    });
  } catch (error) {
    console.error('FontManager: Error loading Noto Sans Symbols 2 font:', error);
    return null;
  }
};

/**
 * Registers the Noto Sans Symbols 2 font with a jsPDF instance.
 * @param {Object} doc - The jsPDF document instance
 * @returns {boolean} - True if successful, false otherwise
 */
export const registerNotoSymbolsFont = (doc) => {
  if (!doc) {
    console.error('FontManager: No jsPDF instance provided to registerNotoSymbolsFont');
    return false;
  }

  if (!cachedFontData) {
    console.warn('FontManager: Cannot register font: No font data loaded. Call loadNotoSymbolsFont() first.');
    return false;
  }

  try {
    // Check if font is already added to VFS to avoid duplicates (though jsPDF handles overwrites usually)
    if (doc.existsFileInVFS(FONT_FILE_NAME)) {
       console.log('FontManager: Font already exists in VFS, skipping VFS addition.');
    } else {
       // Add font to VFS (Virtual File System)
       doc.addFileToVFS(FONT_FILE_NAME, cachedFontData);
    }
    
    // Register font with jsPDF
    // usage: doc.setFont('NotoSymbols', 'normal');
    doc.addFont(FONT_FILE_NAME, FONT_NAME, 'normal');
    
    console.log('FontManager: NotoSymbols font registered with jsPDF instance');
    return true;
  } catch (error) {
    console.error('FontManager: Error registering font with jsPDF:', error);
    return false;
  }
};

/**
 * Checks if the font is currently cached and ready to be registered.
 * @returns {boolean}
 */
export const isFontAvailable = () => {
  return !!cachedFontData;
};

/**
 * Returns the standardized font family name for Noto Symbols.
 * @returns {string}
 */
export const getNotoSymbolsFontName = () => {
  return FONT_NAME;
};