/**
 * Translations: strings live in the components as
 * __( 'Text', 'ai-content-generator-for-woocommerce' ) calls on WordPress's
 * wp.i18n (the domain has to be written out each time so translation tools
 * can extract it). WordPress loads the language pack's strings into wp.i18n
 * before the app (wp_set_script_translations()); this adds the plugin's .mo
 * catalogue and borrowed core strings on top
 * (WTOFE_Settings_App::get_locale_data()).
 *
 * main.tsx imports this module first, so the data is in place before any
 * component renders.
 */
import { Fragment, createElement, type ReactNode } from 'react';
import { setLocaleData } from '@wordpress/i18n';
import boot from './boot';

if ( boot.locale?.plugin ) {
    setLocaleData( boot.locale.plugin, 'ai-content-generator-for-woocommerce' );
}
// Strings borrowed from WordPress itself, such as "Save Changes".
if ( boot.locale?.core ) {
    setLocaleData( boot.locale.core, 'default' );
}

/**
 * Like sprintf(), but the values can be React nodes (links, <strong> …), so
 * a translated sentence can carry markup without HTML in the string.
 *
 * @param template String with %s or %1$s placeholders.
 * @param nodes    Values for the placeholders, in order.
 */
export function interpolate( template: string, ...nodes: ReactNode[] ): ReactNode[] {
    let next = 0;
    return template.split( /(%(?:\d+\$)?s)/ ).map( ( part, index ) => {
        const match = part.match( /^%(?:(\d+)\$)?s$/ );
        if ( ! match ) {
            return part;
        }
        const node = match[ 1 ] ? nodes[ Number( match[ 1 ] ) - 1 ] : nodes[ next++ ];
        return createElement( Fragment, { key: index }, node );
    } );
}
