import {useSelect} from '@wordpress/data';
import {useEffect} from '@wordpress/element';
import {registerPlugin} from '@wordpress/plugins';

const render = () => {
    const cartData = useSelect((select) => select('wc/store/cart').getCartData());
    const freeShippingBannerData = cartData.extensions?.yith_dynamic_wc_block_manager?.ywdpd_free_shipping_notices;
    useEffect(() => {
        if (typeof freeShippingBannerData !== 'undefined') {
            const boydClass = document.body.classList;
            if (Array.from(boydClass).includes('woocommerce-cart')) {
                const hide = freeShippingBannerData === '';
                const banner = document.querySelector('.ywdpd-cart-notices-wrapper');
                if (banner) {
                    if (hide) {
                        banner.classList.add('ywdpd_banner_hide');
                    } else {
                        banner.classList.remove('ywdpd_banner_hide');
                        banner.innerHTML = freeShippingBannerData;

                    }
                } else {
                    if (!hide) {
                        window.location.reload();
                    }
                }
            }
        }
    }, [freeShippingBannerData]);
}

registerPlugin('ywdpd-free-shipping-banner', {
    render,
    scope: 'woocommerce-checkout',
});
