/**
 * External dependencies
 */
import { CART_STORE_KEY as storeKey } from '@kkart/block-data';
import { dispatch } from '@wordpress/data';
import { useStoreCart } from '@kkart/base-hooks';
import { useEffect, RawHTML } from '@wordpress/element';
import LoadingMask from '@kkart/base-components/loading-mask';
import {
	ValidationContextProvider,
	CartProvider,
} from '@kkart/base-context';
import {
	dispatchEvent,
	translateJQueryEventToNative,
} from '@kkart/base-utils';
import withScrollToTop from '@kkart/base-hocs/with-scroll-to-top';

/**
 * Internal dependencies
 */
import FullCart from './full-cart';

const EmptyCart = ( { content } ) => {
	useEffect( () => {
		dispatchEvent( 'kkart-blocks_render_blocks_frontend', {
			element: document.body.querySelector(
				'.wp-block-kkart-cart'
			),
		} );
	}, [] );
	return <RawHTML>{ content }</RawHTML>;
};

const Block = ( { emptyCart, attributes, scrollToTop } ) => {
	const { cartItems, cartIsLoading } = useStoreCart();

	useEffect( () => {
		const invalidateCartData = () => {
			dispatch( storeKey ).invalidateResolutionForStore();
			scrollToTop();
		};

		// Make it so we can read jQuery events triggered by KKART Core elements.
		const removeJQueryAddedToCartEvent = translateJQueryEventToNative(
			'added_to_cart',
			'kkart-blocks_added_to_cart'
		);
		const removeJQueryRemovedFromCartEvent = translateJQueryEventToNative(
			'removed_from_cart',
			'kkart-blocks_removed_from_cart'
		);

		document.body.addEventListener(
			'kkart-blocks_added_to_cart',
			invalidateCartData
		);
		document.body.addEventListener(
			'kkart-blocks_removed_from_cart',
			invalidateCartData
		);

		return () => {
			removeJQueryAddedToCartEvent();
			removeJQueryRemovedFromCartEvent();

			document.body.removeEventListener(
				'kkart-blocks_added_to_cart',
				invalidateCartData
			);
			document.body.removeEventListener(
				'kkart-blocks_removed_from_cart',
				invalidateCartData
			);
		};
	}, [ scrollToTop ] );

	return (
		<>
			{ ! cartIsLoading && cartItems.length === 0 ? (
				<EmptyCart content={ emptyCart } />
			) : (
				<LoadingMask showSpinner={ true } isLoading={ cartIsLoading }>
					<ValidationContextProvider>
						<CartProvider>
							<FullCart attributes={ attributes } />
						</CartProvider>
					</ValidationContextProvider>
				</LoadingMask>
			) }
		</>
	);
};

export default withScrollToTop( Block );
