(function($) {
    $(document).ready(function() {
    	// Script for sample compatibility with cart/checkout block
        if (window.wc && window.wc.blocksCheckout) {
            const { registerCheckoutFilters } = window.wc.blocksCheckout;
            const modifyItemName = ( defaultValue, extensions, args ) => {
                const isCartContext = args?.context === 'cart';
                const dsfps_product_type = args?.cartItem?.extensions?.dsfps_free_product_sample?.dsfps_product_type;

                if ( 'sample' === dsfps_product_type ) {
                    return args?.cartItem?.extensions?.dsfps_free_product_sample?.name;
                }
                if ( ! isCartContext ) {
                    return defaultValue;
                }
                return `${ defaultValue }`;
            };

            registerCheckoutFilters( 'dsfps-sample-extension', {
                itemName: modifyItemName,
            } );
        }

        // Script for submit sample add to cart form (works when the button is outside form.cart via shortcode)
        $(document).on('click', '.dsfps-free-sample-submit-btn', function() {
            var id = $(this).val();
            var $btn = $(this);
            var $form = $btn.closest('form.cart');
            if (!$form.length) {
                $form = $('form.cart').first();
            }
            if (!$form.length) {
                return;
            }
            var $sc = $btn.closest('.dsfps-sample-button-shortcode');
            if ($sc.length && !$sc.closest('form.cart').length) {
                var nonceVal = $sc.find('input[name="_wpnonce"]').first().val();
                if (nonceVal) {
                    $form.find('input.dsfps-sample-nonce-append').remove();
                    $('<input>', { type: 'hidden', 'class': 'dsfps-sample-nonce-append', name: '_wpnonce', value: nonceVal }).appendTo($form);
                }
            }
            $form.find('.dsfps-add-to-cart-id').val(id);
            $form.find('.dsfps-add-to-cart-id').attr('name', 'dsfps-simple-add-to-cart');
            $form.trigger('submit');
        });
	});
})(jQuery);