var PasteImageModal = (function () {
    var bsModal, targetEl, previewEl, defaultText;
    var currentInputSelector, currentPreviewSelector;

    function init() {
        var modalEl = document.getElementById('pasteImageModal');
        if (!modalEl || typeof bootstrap === 'undefined') return false;

        targetEl = document.getElementById('pasteImageTarget');
        previewEl = document.getElementById('pasteImageModalPreview');
        defaultText = targetEl.textContent;
        bsModal = new bootstrap.Modal(modalEl);

        modalEl.addEventListener('shown.bs.modal', function () {
            targetEl.textContent = defaultText;
            previewEl.style.display = 'none';
            previewEl.removeAttribute('src');
            targetEl.focus();
        });

        targetEl.addEventListener('paste', function (e) {
            var clipboard = e.clipboardData || window.clipboardData;
            var items = clipboard ? clipboard.items : null;
            if (!items) return;

            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                if (item.kind === 'file' && item.type.indexOf('image/') === 0) {
                    e.preventDefault();

                    var blob = item.getAsFile();
                    if (!blob) continue;

                    var ext = (blob.type.split('/')[1] || 'png').toLowerCase();
                    var pastedFile = new File([blob], 'pasted-image-' + Date.now() + '.' + ext, { type: blob.type });

                    var input = document.querySelector(currentInputSelector);
                    if (input) {
                        var dt = new DataTransfer();
                        dt.items.add(pastedFile);
                        input.files = dt.files;
                        input.dispatchEvent(new Event('change', { bubbles: true }));
                    }

                    var url = URL.createObjectURL(pastedFile);
                    previewEl.src = url;
                    previewEl.style.display = '';
                    targetEl.textContent = 'Image pasted!';

                    if (currentPreviewSelector) {
                        var extPreview = document.querySelector(currentPreviewSelector);
                        if (extPreview) {
                            extPreview.src = url;
                            extPreview.style.display = '';
                        }
                    }

                    setTimeout(function () { bsModal.hide(); }, 400);
                    break;
                }
            }
        });

        return true;
    }

    function open(inputSelector, previewSelector) {
        if (!bsModal && !init()) return;
        currentInputSelector = inputSelector;
        currentPreviewSelector = previewSelector || null;
        bsModal.show();
    }

    return { open: open };
})();
