(function ($) {
    "use strict";

    const initCopyButton = ($scope) => {
        const btn = $scope.find('.sifency-copy-btn')[0];
        if (!btn) return;

        let timeout;

        btn.addEventListener('click', async () => {
            const text = btn.getAttribute('data-clipboard');

            if (!text) return;

            try {
                await navigator.clipboard.writeText(text);

                btn.classList.add('is-success');

                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    btn.classList.remove('is-success');
                }, 2000);

            } catch (err) {
                console.error('Copy failed:', err);

                // fallback (old browsers)
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                textarea.remove();

                btn.classList.add('is-success');
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    btn.classList.remove('is-success');
                }, 2000);
            }
        });
    };

    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-copy-button.default',
            initCopyButton
        );
    });

})(jQuery);