const { select, dispatch, subscribe } = wp.data;
const {
    __experimentalAddAnnotation: addAnno,
    __experimentalRemoveAnnotationsBySource: clearAnno,
} = dispatch( 'core/annotations' );

/**
 * Adds editor-only highlights using the Annotations API.
 */
function addFreshenUpAnnotations() {
    clearAnno( 'freshenup' );                           // clear old (hot-reload etc.)

    const blocks = select( 'core/block-editor' ).getBlocks();
    ( window.FRESHENUP_HIGHLIGHTS || [] ).forEach( item => {
        const target = blocks.find( b =>
            b.attributes.content &&
            b.attributes.content.indexOf( item.snippet ) !== -1
        );

        if ( target ) {
            addAnno( {
                id:            item.id,
                source:        'freshenup',
                blockClientId: target.clientId,
                selector:      'block',                // highlight whole block
            } );
        }
    } );
}

wp.domReady( () => {
    const parsedBlocks = wp.blocks.parse( window.FRESHENUP_REVISION_HTML || '' );

    // Wait until Gutenberg has loaded its own blocks, then replace them once.
    const unsubscribe = subscribe( () => {
        if ( select( 'core/block-editor' ).getBlocks().length ) {
            unsubscribe();                             // detach first

            // Run in the next tick to avoid Redux recursion
            setTimeout( () => {
                dispatch( 'core/block-editor' ).resetBlocks( parsedBlocks );
                addFreshenUpAnnotations();
            }, 0 );
        }
    } );
} );
