jQuery(document).ready(function($) {
    'use strict';

    // Handle info icon click to expand/collapse
    $(document).on('click', '.canvon-fb-preview-info-icon, .canvon-fb-widget-with-text', function() {
        var $previewIcons = $(this).closest('.canvon-fb-preview-icons');
        var $infoIcon = $previewIcons.find('.canvon-fb-preview-info-icon');
        var isCollapsed = $infoIcon.attr('data-collapsed') === 'true';

        if (isCollapsed) {
            // Expand - mark as expanded
            $infoIcon.attr('data-collapsed', 'false');
            $previewIcons.addClass('expanded');
        }
    });

    // Handle close button click to collapse
    $(document).on('click', '.canvon-fb-preview-close', function() {
        var $previewIcons = $(this).closest('.canvon-fb-preview-icons');
        $previewIcons.removeClass('expanded');
        $previewIcons.find('.canvon-fb-preview-info-icon').attr('data-collapsed', 'true');
    });

    $(document).on('click', '[data-canvon-fb-wechat-modal]', function() {
        var modalId = $(this).data('canvon-fb-wechat-modal');
        $('#' + modalId).addClass('open').attr('aria-hidden', 'false');
    });

    $(document).on('click', '[data-canvon-fb-wechat-close]', function() {
        $(this).closest('.canvon-fb-wechat-contact-modal').removeClass('open').attr('aria-hidden', 'true');
    });

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            $('.canvon-fb-wechat-contact-modal.open').removeClass('open').attr('aria-hidden', 'true');
        }
    });

    $(document).on('click', '[data-canvon-fb-copy-wechat]', function() {
        var $button = $(this);
        var value = String($button.data('canvon-fb-copy-wechat') || '');

        if (!value) {
            return;
        }

        var setCopied = function() {
            var original = $button.data('original-text') || $button.text();
            $button.data('original-text', original).text('Copied');
            setTimeout(function() {
                $button.text(original);
            }, 1400);
        };

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(value).then(setCopied);
        } else {
            var input = $('<input type="text" readonly>');
            input.val(value).css({ position: 'fixed', left: '-9999px' }).appendTo('body');
            input[0].select();
            document.execCommand('copy');
            input.remove();
            setCopied();
        }
    });
});
