import { getPrefix } from '@blocklet/payment-react';
import { joinURL } from 'ufo';
import { pdfStyles } from './styles';

const fontUrl = joinURL(getPrefix(), '/fonts/noto-sans-sc-chinese-simplified-500-normal.ttf');
export const fontFamily = 'Noto Sans SC';

export async function loadFont(): Promise<boolean> {
  try {
    const font = new FontFace(fontFamily, `url(${fontUrl})`);
    const loadedFont = await font.load();
    document.fonts.add(loadedFont);
    return true;
  } catch (error) {
    console.error('Font loading failed:', error);
    return false;
  }
}

export function loadImage(url: string): Promise<HTMLImageElement | null> {
  if (!url) return Promise.resolve(null);
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = url;
  });
}

export function composeStyles(classNames: string): React.CSSProperties {
  return classNames
    .split(' ')
    .filter(Boolean)
    .reduce(
      (acc, className) => ({
        ...acc,
        ...pdfStyles[className],
      }),
      {}
    );
}
