/**
 * CloudScale Replace Post with Clipboard
 *
 * Injects a "Paste Clipboard" button into the Gutenberg editor header toolbar.
 * Reads the clipboard and replaces all post blocks with the pasted content.
 * The post title is unaffected (it lives outside the block list).
 *
 * Mobile fallback: when navigator.clipboard.readText() is unavailable or
 * permission is denied, a textarea modal is shown so the user can paste
 * manually.
 */
( function() {
    'use strict';

    if ( ! window.wp || ! window.wp.data || ! window.wp.blocks || ! window.wp.domReady ) {
        return;
    }

    var wpData   = window.wp.data;
    var wpBlocks = window.wp.blocks;
    var domReady = window.wp.domReady;

    var BTN_ID     = 'cs-replace-post-btn';
    var CONFIRM_ID = 'cs-replace-post-confirm';
    var MODAL_ID   = 'cs-replace-post-modal';

    // Selectors to try when locating the editor toolbar (covers WP 6.0–6.8+).
    var TOOLBAR_SELECTORS = [
        '.editor-header__toolbar',
        '.edit-post-header__toolbar',
        '.editor-header .editor-header__toolbar',
    ];

    // =========================================================================
    //  SVG clipboard icon
    // =========================================================================

    var ICON_SVG =
        '<svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor" ' +
            'aria-hidden="true" style="flex-shrink:0;vertical-align:-2px">' +
            '<path d="M5 0h4a1 1 0 0 1 1 1h1a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V3A2 2 0 0 1 3 1h1a1 1 0 0 1 1-1zm0 2a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1H10a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zm1 0V1h2v1H6z"/>' +
        '</svg>';

    // =========================================================================
    //  Convert plain text / markdown to an array of blocks
    // =========================================================================

    function textToBlocks( text ) {
        var blocks = [];

        if ( typeof wpBlocks.pasteHandler === 'function' ) {
            try {
                blocks = wpBlocks.pasteHandler( {
                    plainText: text,
                    HTML: '',
                    mode: 'BLOCKS',
                } );
            } catch ( e ) {
                blocks = [];
            }
        }

        if ( ! blocks || ! blocks.length ) {
            if ( typeof wpBlocks.rawHandler === 'function' ) {
                var html = text.split( /\n\n+/ ).map( function( para ) {
                    return '<p>' + para.replace( /\n/g, '<br>' ) + '</p>';
                } ).join( '' );
                try {
                    blocks = wpBlocks.rawHandler( { HTML: html } );
                } catch ( e ) {
                    blocks = [];
                }
            }
        }

        if ( ! blocks || ! blocks.length ) {
            blocks = [ wpBlocks.createBlock( 'core/paragraph', { content: text } ) ];
        }

        return blocks;
    }

    // =========================================================================
    //  Convert HTML (from clipboard) to blocks — preserves heading structure
    // =========================================================================

    function htmlToBlocks( html ) {
        var blocks = [];
        if ( typeof wpBlocks.pasteHandler === 'function' ) {
            try {
                blocks = wpBlocks.pasteHandler( {
                    HTML: html,
                    plainText: '',
                    mode: 'BLOCKS',
                } );
            } catch ( e ) {
                blocks = [];
            }
        }
        if ( ! blocks || ! blocks.length ) {
            if ( typeof wpBlocks.rawHandler === 'function' ) {
                try {
                    blocks = wpBlocks.rawHandler( { HTML: html } );
                } catch ( e ) {
                    blocks = [];
                }
            }
        }
        if ( ! blocks || ! blocks.length ) {
            blocks = [ wpBlocks.createBlock( 'core/paragraph', { content: html } ) ];
        }
        return blocks;
    }

    function doReplace( blocks ) {
        wpData.dispatch( 'core/block-editor' ).resetBlocks( blocks );
        var btn = document.getElementById( BTN_ID );
        if ( btn ) {
            btn.innerHTML      = ICON_SVG + ' Pasted!';
            btn.style.background = '#16a34a';
            setTimeout( function() {
                btn.innerHTML      = ICON_SVG + ' Paste Clipboard';
                btn.style.background = '';
            }, 1500 );
        }
    }

    // =========================================================================
    //  Read clipboard — prefer HTML (preserves headings); fall back to text
    // =========================================================================

    function readClipboardAndReplace() {
        // clipboard.read() gives us the HTML version which preserves <h1>–<h6>.
        // clipboard.readText() only gives plain text, losing heading structure.
        if ( navigator.clipboard && typeof navigator.clipboard.read === 'function' ) {
            navigator.clipboard.read().then( function( items ) {
                var i, item, types;
                for ( i = 0; i < items.length; i++ ) {
                    item  = items[ i ];
                    types = item.types;

                    // Prefer HTML — keeps heading blocks intact
                    if ( types.indexOf( 'text/html' ) !== -1 ) {
                        item.getType( 'text/html' ).then( function( blob ) {
                            return blob.text();
                        } ).then( function( html ) {
                            if ( html && html.trim() ) {
                                doReplace( htmlToBlocks( html ) );
                            } else {
                                flashError( 'Clipboard empty.' );
                            }
                        } );
                        return;
                    }

                    // Plain text fallback (e.g. markdown from a text editor)
                    if ( types.indexOf( 'text/plain' ) !== -1 ) {
                        item.getType( 'text/plain' ).then( function( blob ) {
                            return blob.text();
                        } ).then( function( text ) {
                            if ( text && text.trim() ) {
                                doReplace( textToBlocks( text ) );
                            } else {
                                flashError( 'Clipboard empty.' );
                            }
                        } );
                        return;
                    }
                }
                flashError( 'Clipboard empty.' );
            } ).catch( function() {
                // clipboard.read() denied — try plain-text read
                readTextFallback();
            } );
        } else {
            readTextFallback();
        }
    }

    function readTextFallback() {
        if ( navigator.clipboard && typeof navigator.clipboard.readText === 'function' ) {
            navigator.clipboard.readText().then( function( text ) {
                if ( ! text || ! text.trim() ) {
                    flashError( 'Clipboard empty.' );
                    return;
                }
                doReplace( textToBlocks( text ) );
            } ).catch( function() {
                showPasteModal();
            } );
        } else {
            showPasteModal();
        }
    }

    // =========================================================================
    //  Confirm banner — positioned below the toolbar
    // =========================================================================

    function showConfirm() {
        removeConfirm();

        var div  = document.createElement( 'div' );
        div.id   = CONFIRM_ID;

        // Position relative to the button
        var btn  = document.getElementById( BTN_ID );
        var rect = btn ? btn.getBoundingClientRect() : null;
        if ( rect ) {
            div.style.top  = ( rect.bottom + 6 ) + 'px';
            div.style.left = rect.left + 'px';
        }

        div.innerHTML =
            '<span>Replace all post content?</span>' +
            '<button id="cs-rp-yes">Replace</button>' +
            '<button id="cs-rp-no">Cancel</button>';
        document.body.appendChild( div );

        document.getElementById( 'cs-rp-yes' ).addEventListener( 'click', function() {
            removeConfirm();
            readClipboardAndReplace();
        } );
        document.getElementById( 'cs-rp-no' ).addEventListener( 'click', removeConfirm );
    }

    function removeConfirm() {
        var el = document.getElementById( CONFIRM_ID );
        if ( el ) {
            el.parentNode.removeChild( el );
        }
    }

    // =========================================================================
    //  Paste modal (fallback when Clipboard API is unavailable / denied)
    // =========================================================================

    function showPasteModal() {
        removeModal();

        var overlay = document.createElement( 'div' );
        overlay.id  = MODAL_ID;
        overlay.innerHTML =
            '<div id="cs-rp-modal-inner">' +
                '<p id="cs-rp-modal-title">Paste your content</p>' +
                '<textarea id="cs-rp-modal-ta" rows="12" ' +
                    'placeholder="Paste here (Ctrl+V or long-press → Paste)…"></textarea>' +
                '<div id="cs-rp-modal-btns">' +
                    '<button id="cs-rp-modal-apply">Apply</button>' +
                    '<button id="cs-rp-modal-cancel">Cancel</button>' +
                '</div>' +
            '</div>';
        document.body.appendChild( overlay );

        setTimeout( function() {
            var ta = document.getElementById( 'cs-rp-modal-ta' );
            if ( ta ) {
                ta.focus();
            }
        }, 80 );

        document.getElementById( 'cs-rp-modal-apply' ).addEventListener( 'click', function() {
            var ta   = document.getElementById( 'cs-rp-modal-ta' );
            var text = ta ? ta.value : '';
            removeModal();
            if ( text.trim() ) {
                doReplace( textToBlocks( text ) );
            }
        } );
        document.getElementById( 'cs-rp-modal-cancel' ).addEventListener( 'click', removeModal );

        overlay.addEventListener( 'click', function( e ) {
            if ( e.target === overlay ) {
                removeModal();
            }
        } );
    }

    function removeModal() {
        var el = document.getElementById( MODAL_ID );
        if ( el ) {
            el.parentNode.removeChild( el );
        }
    }

    // =========================================================================
    //  Error flash on the main button
    // =========================================================================

    function flashError( msg ) {
        var btn = document.getElementById( BTN_ID );
        if ( ! btn ) {
            return;
        }
        btn.textContent        = msg;
        btn.style.background   = '#dc2626';
        setTimeout( function() {
            btn.innerHTML        = ICON_SVG + ' Paste Clipboard';
            btn.style.background = '';
        }, 2000 );
    }

    // =========================================================================
    //  Find the Gutenberg editor header toolbar element
    // =========================================================================

    function findToolbar() {
        var i, el;
        for ( i = 0; i < TOOLBAR_SELECTORS.length; i++ ) {
            el = document.querySelector( TOOLBAR_SELECTORS[ i ] );
            if ( el ) {
                return el;
            }
        }
        return null;
    }

    // =========================================================================
    //  Inject the button into the editor toolbar (with retry)
    // =========================================================================

    domReady( function() {
        if ( document.getElementById( BTN_ID ) ) {
            return;
        }

        var btn  = document.createElement( 'button' );
        btn.id   = BTN_ID;
        btn.type = 'button';
        btn.innerHTML = ICON_SVG + ' Paste Clipboard';

        btn.addEventListener( 'click', function() {
            if ( document.getElementById( CONFIRM_ID ) ) {
                removeConfirm();
            } else {
                showConfirm();
            }
        } );

        var attempts = 0;

        function tryInject() {
            var toolbar = findToolbar();
            if ( toolbar ) {
                toolbar.appendChild( btn );
                btn.classList.add( 'cs-in-toolbar' );
            } else if ( attempts < 25 ) {
                attempts++;
                setTimeout( tryInject, 200 );
            } else {
                // Fallback: fixed position on the body
                document.body.appendChild( btn );
            }
        }

        tryInject();
    } );

} )();
