import { __ } from '@wordpress/i18n';
import domReady from "@wordpress/dom-ready";

const copyToClipboard = () => {
    document.querySelectorAll( '.wp-block-code' ).forEach( pre => {
        const code            = pre.getElementsByTagName( 'code' )[0];
        let textArea          = document.createElement( 'textarea' );
        let button            = document.createElement( 'button' );
        let tooltip           = document.createElement( 'div' );
        let tooltipText       = document.createElement( 'span' );
        textArea.value        = code.innerText;
        button.className      = 'copy-code-button';
        button.type           = 'button';
        button.innerText      = __( 'Copy', 'blockify' );
        tooltip.className     = 'tooltip';
        tooltipText.className = 'tooltip-text';
        tooltipText.innerText = __( 'Copy to clipboard', 'blockify' );

        tooltip.appendChild( tooltipText );

        pre.insertBefore( button, pre.firstChild );
        pre.insertBefore( tooltip, button );

        button.addEventListener( 'click', () => {
            textArea.select();
            textArea.setSelectionRange( 0, 99999 );
            navigator?.clipboard?.writeText( textArea.value );
            alert( __( 'Copied ', 'blockify' ) + textArea.value );
        } );
    } );
};

domReady( copyToClipboard );
