/**
 * What the bundle gets for `import … from 'react'` (see the aliases in
 * vite.config.ts): the React WordPress ships (window.React, from the "react"
 * script), so the app and every library in it share WordPress's copy and none
 * is bundled.
 *
 * WordPress 6.0 and 6.1 ship React 17, 6.2 and later React 18. The React 18
 * APIs the libraries need (TanStack Router, Radix, zustand) get small
 * stand-ins on React 17; on React 18 WordPress's own versions are used.
 * React 19-only APIs (`use`, `useEffectEvent`) are passed through as they are,
 * so libraries that look them up fall back as they do on React 18.
 */
import type * as ReactTypes from 'react';

type ReactModule = typeof ReactTypes & Record<string, unknown>;

declare global {
    interface Window {
        React: typeof ReactTypes;
    }
}

const WP: ReactModule = window.React as ReactModule;

// ── React 18 stand-ins for React 17 ────────────────────────────────────────

let lastId = 0;

/** useId(): an id fixed for the component's lifetime. */
function useIdFallback(): string {
    const [ id ] = WP.useState( () => `wtofe-id-${ ++lastId }` );
    return id;
}

interface StoreInstance<T> {
    value: T;
    getSnapshot: () => T;
}

function hasChanged<T>( inst: StoreInstance<T> ): boolean {
    try {
        return ! Object.is( inst.value, inst.getSnapshot() );
    } catch {
        return true;
    }
}

const queued = new Set<() => void>();

/**
 * Re-renders for store changes, applied together at the end of the current
 * task. React 18 batches updates like this on its own; React 17 renders on
 * every single one, so a router that updates several stores in a row would
 * render between them with only some of its state in place.
 */
function queueStoreUpdate( update: () => void ): void {
    queued.add( update );
    if ( 1 === queued.size ) {
        queueMicrotask( () => {
            const updates = [ ...queued ];
            queued.clear();
            window.ReactDOM.unstable_batchedUpdates( () => updates.forEach( ( run ) => run() ) );
        } );
    }
}

/**
 * useSyncExternalStore(), as React's own use-sync-external-store shim does
 * it (read the snapshot while rendering, re-render when it changes), with
 * React 18's batching of the re-renders.
 */
function useSyncExternalStoreFallback<T>( subscribe: ( onChange: () => void ) => () => void, getSnapshot: () => T ): T {
    const value = getSnapshot();
    const [ { inst }, forceUpdate ] = WP.useState( { inst: { value, getSnapshot } as StoreInstance<T> } );

    WP.useLayoutEffect( () => {
        inst.value = value;
        inst.getSnapshot = getSnapshot;
        if ( hasChanged( inst ) ) {
            forceUpdate( { inst } );
        }
    }, [ subscribe, value, getSnapshot ] );

    WP.useEffect( () => {
        if ( hasChanged( inst ) ) {
            forceUpdate( { inst } );
        }
        return subscribe( () => {
            if ( hasChanged( inst ) ) {
                queueStoreUpdate( () => forceUpdate( { inst } ) );
            }
        } );
    }, [ subscribe ] );

    return value;
}

function startTransitionFallback( callback: () => void ): void {
    callback();
}

// ── The module ─────────────────────────────────────────────────────────────

export const {
    Children,
    Component,
    Fragment,
    Profiler,
    PureComponent,
    StrictMode,
    Suspense,
    cloneElement,
    createContext,
    createElement,
    createRef,
    forwardRef,
    isValidElement,
    lazy,
    memo,
    useCallback,
    useContext,
    useDebugValue,
    useEffect,
    useImperativeHandle,
    useLayoutEffect,
    useMemo,
    useReducer,
    useRef,
    useState,
    version,
} = WP;

export const useId = WP.useId ?? useIdFallback;
export const useSyncExternalStore = WP.useSyncExternalStore ?? useSyncExternalStoreFallback;
export const useInsertionEffect = WP.useInsertionEffect ?? WP.useLayoutEffect;
export const startTransition = WP.startTransition ?? startTransitionFallback;
export const useTransition = WP.useTransition ?? ( () => [ false, startTransition ] );
export const useDeferredValue = WP.useDeferredValue ?? ( <T>( value: T ) => value );

// React 19 only: undefined on WordPress's React 17/18, which libraries check for.
export const use = WP.use;
export const useEffectEvent = WP.useEffectEvent;

// `import React from 'react'` (zustand, sonner): the same set, stand-ins included.
export default {
    ...WP,
    useId,
    useSyncExternalStore,
    useInsertionEffect,
    startTransition,
    useTransition,
    useDeferredValue,
};
