(function () {

    if (window.__plantshopFilterRegistered) return;

    const getRegistry = () =>
        (window.wc && (window.wc.blocksCheckout || window.wc.wcBlocksCheckout)) || null;

    const register = () => {
        const api = getRegistry();
        if (!api || !api.registerCheckoutFilters) return false;

        api.registerCheckoutFilters('plantshop-wc', {
            itemName: (defaultValue, extensions, {cartItem, context}) => {
                const ext = cartItem?.extensions?.plantshop;
                return ext?.displayTitle?.html || defaultValue;
            },
        });

        window.__plantshopFilterRegistered = true;
        return true;
    };

    if(register()) return;

    const retry = () => { register(); };

    document.addEventListener('wc-blocks_added_to_cart', retry, { once: true });
    document.addEventListener('wc-blocks_cart_update', retry, { once: true });

    let tries = 0;
    const id = setInterval(() => {
        if (register() || ++tries > 20) clearInterval(id);
    }, 150);

})();
