export const loadImage = ( src: string ) =>
    new Promise<HTMLImageElement>( ( resolve, reject ) => {
        const img = new Image();
        img.crossOrigin = "anonymous";
        img.onload = () => resolve( img );
        img.onerror = reject;
        img.src = src;
    } );

export const getPrimaryFamily = ( v: string ) => v.split( "," )[ 0 ];

export const ensureFontLoaded = async ( family: string, size: number ) => {
    const fam = family.replace( /^["']|["']$/g, "" );
    const famQuoted = /[\s,]/.test( fam ) ? `'${ fam }'` : fam;
    const fontsApi = document?.fonts as FontFaceSet | undefined;
    if ( !fontsApi?.load ) return;

    try {
        await fontsApi.load( `bold ${ size }px ${ famQuoted }` );
    } catch {
        //
    }
};

export const angleDeg = ( dx: number, dy: number ) =>
    ( ( ( Math.atan2( dy, dx ) * 180 ) / Math.PI ) + 360 ) % 360;