(function() {
    function fallbackCopyTextToClipboard(text, pasteTo = false) {
        var textArea = document.createElement("textarea");
        textArea.value = text;

        // Avoid scrolling to bottom
        textArea.style.top = "0";
        textArea.style.left = "0";
        textArea.style.position = "fixed";

        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Fallback: Copying text command was ' + msg);
            toastr.success('Copied!');
            pasteToElement(pasteTo, text);
        } catch (err) {
            console.error('Fallback: Oops, unable to copy', err);
        }

        document.body.removeChild(textArea);
    }
    function copyTextToClipboard(text, pasteTo = false) {
        if (!navigator.clipboard) {
            fallbackCopyTextToClipboard(text);
            return;
        }
        navigator.clipboard.writeText(text).then(function() {
            console.log('Async: Copying to clipboard was successful!');
            toastr.success('Copied!');
            pasteToElement(pasteTo, text);
        }, function(err) {
            console.error('Async: Could not copy text: ', err);
        });
    }
    function pasteToElement(_elem, _text) {
        if(_elem && _elem.length) {
            // if rte
            if(_elem.is('.ql-container') && _elem[0].__quill) {
                let qlRoot = _elem[0].__quill.root;
                if($.trim($(qlRoot.innerHTML).text()) === '') {
                    _elem[0].__quill.clipboard.dangerouslyPasteHTML(0, _text);
                    _elem[0].__quill.root.focus();
                }
            }
            else _elem.val(_text);
        }
    }

    function init() {
        $(document)
            .off('click.click-to-copy', '.click-to-copy')
            .on('click.click-to-copy', '.click-to-copy', function(event) {
                let self = $(this);
                copyTextToClipboard(self.text(),
                    self.is('[auto-paste]') ? self.closest('form').find(self.attr('auto-paste')) : false);
            });
        window.copyTextToClipboard = copyTextToClipboard;
    }

    addMCInitializer('click-to-copy', init);

}).call(window);
