(function (window, document) {
    'use strict';

    const MAX_HIGHLIGHT_CHARS = 200000;
    const copiedLabel = String((window.MARKBLOCKS_FRONTEND && window.MARKBLOCKS_FRONTEND.copied) || 'Copied');

    function highlightWithin(root) {
        const scope = root || document;
        if (!window.MarkBlocksSyntax || typeof window.MarkBlocksSyntax.render !== 'function') return;

        scope.querySelectorAll('.markblocks-code-block code:not([data-markblocks-highlighted])').forEach((codeElement) => {
            const wrapper = codeElement.closest('.markblocks-code-block');
            const language = wrapper ? wrapper.getAttribute('data-language') : '';
            const source = codeElement.textContent || '';

            if (source.length > MAX_HIGHLIGHT_CHARS) {
                codeElement.setAttribute('data-markblocks-highlighted', 'skipped');
                return;
            }

            try {
                if (!window.MarkBlocksSyntax.render(codeElement, source, language)) {
                    throw new Error('Safe syntax renderer unavailable.');
                }
                codeElement.setAttribute('data-markblocks-highlighted', 'yes');
            } catch (error) {
                codeElement.textContent = source;
                codeElement.setAttribute('data-markblocks-highlighted', 'failed');
            }
        });
    }

    function legacyCopy(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.setAttribute('readonly', 'readonly');
        textarea.style.position = 'fixed';
        textarea.style.insetInlineStart = '-9999px';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();

        let copied = false;
        try {
            copied = document.execCommand('copy');
        } catch (error) {
            copied = false;
        }
        textarea.remove();
        return copied;
    }

    async function copyCode(button) {
        const wrapper = button.closest('.markblocks-code-block');
        const code = wrapper ? wrapper.querySelector('code') : null;
        if (!code) return;

        const originalText = button.textContent;
        const originalLabel = button.getAttribute('aria-label');
        const text = code.textContent || '';
        let copied = false;

        try {
            if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
                await navigator.clipboard.writeText(text);
                copied = true;
            }
        } catch (error) {
            copied = false;
        }

        if (!copied) copied = legacyCopy(text);
        if (!copied) return;

        button.textContent = copiedLabel;
        button.setAttribute('aria-label', copiedLabel);
        window.setTimeout(() => {
            button.textContent = originalText;
            if (originalLabel) {
                button.setAttribute('aria-label', originalLabel);
            } else {
                button.removeAttribute('aria-label');
            }
        }, 1600);
    }

    document.addEventListener('click', (event) => {
        const target = event.target instanceof Element ? event.target : null;
        const button = target ? target.closest('.markblocks-copy-code') : null;
        if (button) {
            event.preventDefault();
            copyCode(button);
        }
    });

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => highlightWithin(document));
    } else {
        highlightWithin(document);
    }

    function registerElementorHooks() {
        if (!window.elementorFrontend || !window.elementorFrontend.hooks) return;
        window.elementorFrontend.hooks.addAction('frontend/element_ready/emb_markdown_article.default', ($scope) => highlightWithin($scope[0]));
        window.elementorFrontend.hooks.addAction('frontend/element_ready/emb_code_block.default', ($scope) => highlightWithin($scope[0]));
    }

    if (window.elementorFrontend && window.elementorFrontend.hooks) {
        registerElementorHooks();
    } else {
        window.addEventListener('elementor/frontend/init', registerElementorHooks, { once: true });
    }
})(window, document);
