jQuery(window).on('elementor/frontend/init', function () {

    elementorFrontend.hooks.addAction(
        'frontend/element_ready/sifency_code_snippet.default',
        function ($scope) {

            /* -----------------------------------------
             * 1. Prism Highlight + Line Numbers
             * ----------------------------------------- */
            if (typeof Prism !== 'undefined') {
                setTimeout(function () {
                    Prism.highlightAllUnder($scope[0]);
                }, 0);
            }

            /* -----------------------------------------
             * 2. Copy Button Logic
             * ----------------------------------------- */
            const $copyBtn = $scope.find('.copy-btn');

            if (!$copyBtn.length) return;

            $copyBtn.on('click', function () {
                const $btn  = jQuery(this);
                const code  = $scope.find('pre code').text();

                if (!code) return;

                // Modern Clipboard API
                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(code).then(function () {
                        updateButtonState($btn);
                    });
                } 
                // Fallback
                else {
                    const textarea = document.createElement('textarea');
                    textarea.value = code;
                    textarea.style.position = 'fixed';
                    textarea.style.left = '-9999px';
                    document.body.appendChild(textarea);
                    textarea.select();

                    try {
                        document.execCommand('copy');
                        updateButtonState($btn);
                    } catch (e) {
                        console.error('Copy failed', e);
                    }

                    document.body.removeChild(textarea);
                }
            });

            function updateButtonState($btn) {
                const original = $btn.text();
                $btn.text('Copied!').addClass('is-copied');

                setTimeout(function () {
                    $btn.text(original).removeClass('is-copied');
                }, 2000);
            }
        }
    );
});
