import { UNICODE_FONT_STACK } from './htmlCanvasConfig';

/**
 * Utility to ensure Unicode-supporting fonts are loaded and available.
 * Critical for rendering symbols like checkmarks (✓) and boxes (☐) in PDFs.
 */

const SYMBOL_TEST_STRING = '✓ ☐ ☑ ☒ ★ ⚠';

/**
 * Preloads fonts and verifies symbol rendering capabilities.
 * @returns {Promise<boolean>}
 */
export const loadUnicodeFonts = async () => {
  try {
    // 1. Check if the FontFace API is available
    if (typeof FontFace === 'undefined') {
      console.warn('FontFace API not supported, skipping explicit font load.');
      return true; 
    }

    // 2. Create a dummy element to force font loading/layout calculation
    const testEl = document.createElement('span');
    testEl.style.position = 'absolute';
    testEl.style.top = '-9999px';
    testEl.style.left = '-9999px';
    testEl.style.fontFamily = UNICODE_FONT_STACK;
    testEl.textContent = SYMBOL_TEST_STRING;
    document.body.appendChild(testEl);

    // 3. Wait for fonts to be ready
    await document.fonts.ready;

    // 4. Force layout check
    const width = testEl.offsetWidth;
    
    // Clean up
    document.body.removeChild(testEl);

    if (width === 0) {
        console.warn('Symbol font test failed (0 width). Proceeding with fallback.');
    } else {
        console.log('Unicode fonts verified.');
    }

    return true;
  } catch (error) {
    console.error('Error loading unicode fonts:', error);
    // Don't block generation on font errors, try to proceed with system defaults
    return false;
  }
};

/**
 * Wraps HTML content in a container with the robust font stack
 */
export const wrapWithUnicodeStyles = (htmlContent) => {
  return `
    <div style="font-family: ${UNICODE_FONT_STACK}; width: 100%; height: 100%;">
      ${htmlContent}
    </div>
  `;
};