import { useAsukaStore } from '../store/asukaStore';
import { loadRegisteredFont } from './fonts';
import type { AsukaRegisteredFont } from '../types/options';

/** Ensure that a registered family is ready before a renderer measures or paints text. */
export async function ensureFontFamilyLoaded(family: string | null | undefined): Promise<boolean> {
  const normalizedFamily = String(family ?? '').trim();
  if (!normalizedFamily) return false;

  const state: any = useAsukaStore.getState();
  const candidates = ((state.fontsCatalog ?? []) as AsukaRegisteredFont[])
    .filter((font) => String(font?.family ?? '').trim().toLowerCase() === normalizedFamily.toLowerCase());
  const font = candidates.find((entry) => entry.source !== 'system') ?? candidates[0];
  if (!font) return false;
  if (font.source === 'system' || font.loaded) return true;

  state.markFontState?.(font.id, { loading: true, error: undefined });
  let loaded = false;
  try {
    loaded = await loadRegisteredFont(font);
  } catch {
    loaded = false;
  }
  useAsukaStore.getState().markFontState?.(font.id, {
    loading: false,
    loaded,
    error: loaded ? undefined : 'Failed to load font',
  });
  return loaded;
}
