/**
 * What the bundle gets for `react/jsx-runtime` (the compiled JSX of the app
 * and its libraries). WordPress only ships a "react-jsx-runtime" script from
 * 6.6, so elements are made with createElement() from WordPress's React,
 * which every version has. See wordpress/react.ts.
 */
import { Fragment, createElement } from './react';

type ElementType = Parameters<typeof createElement>[ 0 ];
type Props = Record<string, unknown> & { children?: unknown };

/**
 * jsx( type, props, key ) / jsxs() for an element whose children are written
 * out in the JSX (a fixed list). Those go to createElement() as separate
 * arguments, as they would without the JSX transform, so React doesn't ask
 * them for keys; a list built at runtime stays one argument and keeps React's
 * key check.
 */
function create( type: ElementType, { children, ...props }: Props, key: string | undefined, fixedChildren: boolean ) {
    if ( undefined !== key ) {
        props.key = key;
    }
    if ( undefined === children ) {
        return createElement( type, props );
    }
    if ( fixedChildren && Array.isArray( children ) ) {
        return createElement( type, props, ...( children as Parameters<typeof createElement>[ 2 ][] ) );
    }
    return createElement( type, props, children as Parameters<typeof createElement>[ 2 ] );
}

const jsx  = ( type: ElementType, props: Props, key?: string ) => create( type, props, key, false );
const jsxs = ( type: ElementType, props: Props, key?: string ) => create( type, props, key, true );

// Development builds (npm run dev) call jsxDEV( type, props, key, isStaticChildren ).
const jsxDEV = ( type: ElementType, props: Props, key?: string, isStaticChildren?: boolean ) => create( type, props, key, !! isStaticChildren );

export { Fragment, jsx, jsxs, jsxDEV };
