import { familyById, fontFileUrl, variantFor, type FontVariant } from './fonts';

/**
 * On-demand loading of the bundled webfonts for on-screen (WYSIWYG) rendering
 * of text boxes and the inline native-edit preview. Each (family, variant) is
 * registered once as a `FontFace` under the family's CSS name with matching
 * weight/style descriptors, so the browser picks the right file from the
 * element's font-weight/font-style. Fetches flow through the service worker's
 * runtime cache, so a family stays available offline after first use.
 */

const loaded = new Map<string, Promise<void>>(); // key: `${id}:${variant}`

/** CSS font stack for a family id (core families need no loading). */
export function cssFamilyFor(id: string): string {
  return familyById(id)?.cssStack ?? 'Arial, Helvetica, sans-serif';
}

export function ensureFontLoaded(id: string, variant: FontVariant = 'regular'): Promise<void> {
  const fam = familyById(id);
  if (!fam || fam.core || !fam.cssName || typeof FontFace === 'undefined') return Promise.resolve();
  const url = fontFileUrl(id, variant);
  if (!url) return Promise.resolve();
  const key = `${id}:${variant}`;
  let p = loaded.get(key);
  if (!p) {
    p = (async () => {
      try {
        const weight = variant === 'bold' || variant === 'boldItalic' ? '700' : '400';
        const style = variant === 'italic' || variant === 'boldItalic' ? 'italic' : 'normal';
        const face = new FontFace(fam.cssName as string, `url(${url})`, { weight, style });
        await face.load();
        document.fonts.add(face);
      } catch (e) {
        console.warn('Font load failed', id, variant, e);
      }
    })();
    loaded.set(key, p);
  }
  return p;
}

/** Convenience: load the variant implied by bold/italic flags. */
export function ensureFontFor(id: string, bold?: boolean, italic?: boolean): Promise<void> {
  return ensureFontLoaded(id, variantFor(bold, italic));
}

/** Preload every variant of a family (used when the user selects it). */
export function ensureFamilyLoaded(id: string): Promise<void> {
  const fam = familyById(id);
  if (!fam || fam.core || !fam.files) return Promise.resolve();
  return Promise.all((Object.keys(fam.files) as FontVariant[]).map((v) => ensureFontLoaded(id, v))).then(() => undefined);
}
