/**
 * Google Fonts loader — shared by the admin builder AND the public frontend so a
 * family chosen in the builder (css.fontFamily) actually loads wherever a design
 * renders. The list of OFFERED families is framework data served from PHP
 * (CliqUI::dataRepo()->get('font_family')); this module just loads what's used.
 */

const loaded = new Set();

/**
 * Inject the stylesheet for a font family (once). `group` (DATA from the PHP
 * catalog) picks the endpoint: `system` families are web-safe and never fetched,
 * `earlyaccess` uses Google's early-access endpoint, everything else uses css2.
 * When `group` is unknown (frontend, where only the family name is stored) we
 * fall through to css2 — a non-Google name just fails the request harmlessly.
 */
export const loadGoogleFont = ( family, group ) => {
	if ( ! family || group === 'system' ) {
		return;
	}
	if ( typeof document === 'undefined' || loaded.has( family ) ) {
		return;
	}
	loaded.add( family );
	const link = document.createElement( 'link' );
	link.rel = 'stylesheet';
	link.href =
		group === 'earlyaccess'
			? `https://fonts.googleapis.com/earlyaccess/${ family.toLowerCase().replace( /\s+/g, '' ) }.css`
			: `https://fonts.googleapis.com/css2?family=${ family.trim().replace( /\s+/g, '+' ) }:wght@400;500;600;700&display=swap`;
	link.dataset.cliqFont = family;
	document.head.appendChild( link );
};

/** Collect every font family referenced in a builder model (rows/cols/items). */
export const collectFonts = ( model ) => {
	const out = new Set();
	const add = ( css ) => {
		if ( css && css.fontFamily ) {
			out.add( css.fontFamily );
		}
	};
	add( model?.container?.css );
	if ( model?.settings?.labelFontFamily ) {
		out.add( model.settings.labelFontFamily );
	}
	( model?.rows || [] ).forEach( ( row ) => {
		add( row.settings?.css );
		( row.columns || [] ).forEach( ( col ) => {
			add( col.settings?.css );
			( col.items || [] ).forEach( ( item ) => add( item.css ) );
		} );
	} );
	return Array.from( out );
};

/** Ensure all fonts used by a model are loaded (group unknown → css2 endpoint). */
export const ensureFonts = ( model, excludedFamilies = [] ) => {
	const excluded = new Set( excludedFamilies.map( ( family ) => String( family ).trim().toLowerCase() ) );
	collectFonts( model ).forEach( ( family ) => {
		if ( ! excluded.has( String( family ).trim().toLowerCase() ) ) {
			loadGoogleFont( family );
		}
	} );
};
