( function ( $ ) {
	"use strict";

	if ( 'undefined' === typeof wc_cart_params ) {
		return;
	}

	document.addEventListener(
		'DOMContentLoaded',
		function () {

			if ('undefined' !== typeof splitit_settings) {
				let obj = splitit_settings.splitit_upstream_messaging_position_cart_page;
				if ("object" === typeof obj && null !== obj) {
					generateUm( obj, splitit_settings )
				}

				function generateUm(umSettings, splititSettings) {
					let umSelector = getUmSelector( umSettings );
					let block      = '<div id="on_site_message_block_cart"></div>';
					let isVisa     = 'yes' == splititSettings.enabled_visa;

					let blockStyles  = '';
					let tagName      = '';
					let price        = getPrice();
					let installments = getInstallmentByPrice( price, splititSettings, umSettings );

					if (umSettings.strip && 1 == umSettings.strip.enable_strip) {
						tagName = 'spt-strip';

						if ('custom' !== umSettings.strip.um_text_type) {
							umSettings.strip.strip_text = '';
						}

						let stripUm = makeBlock( isVisa, tagName, umSettings.strip );
						block       = '<div id="on_site_message_block_cart" style="position: relative; width: 100%; height: auto; min-width: 50px; min-height: 50px; margin-bottom: 15px;">';
						block      += stripUm;
						block      += '</div>';

					} else if (umSettings.banner && 1 == umSettings.banner.enable_banner) {
						tagName = 'spt-banner';

						if ('custom' !== umSettings.banner.um_text_type) {
							umSettings.banner.text_main = '';
						}

						block       = makeBlock( isVisa, tagName, umSettings.banner );
						blockStyles = 'position: relative; width: 100%; height: auto; min-width: 50px; min-height: 50px; margin-top: 20px; margin-bottom: 20px';

					} else if (umSettings.logo && 1 == umSettings.logo.enable_logo) {
						tagName = 'spt-floating-logo';

						if ('custom' !== umSettings.logo.um_text_type) {
							umSettings.logo.logo_text = '';
						}

						umSettings.logo.amount       = price;
						umSettings.logo.installments = installments;

						block = makeBlock( isVisa, tagName, umSettings.logo );

						blockStyles = 'position: relative; width: 100%; height: auto; min-width: 50px; min-height: 50px; margin-top: 20px; margin-bottom: 20px';

					} else if (umSettings.one_liner && 1 == umSettings.one_liner.enable_one_liner) {
						tagName = 'spt-one-liner';

						if ('custom' !== umSettings.one_liner.text_option) {
							umSettings.one_liner.text_custom = '';
						}

						umSettings.one_liner.amount       = price;
						umSettings.one_liner.installments = installments;

						block = makeBlock( isVisa, tagName, umSettings.one_liner );

						blockStyles = 'position: relative; width: 100%; height: auto; min-width: 50px; min-height: 50px; margin-top: 20px; margin-bottom: 20px';
					}

					const observer = new MutationObserver(
						function (mutations) {
							const selectorBlock = document.querySelector( umSelector );
							if (selectorBlock) {
								observer.disconnect();
								if ('spt-strip' === tagName) {
									$( umSelector ).prepend( block );
									if ( ! installments) {
										$( 'spt-strip' ).css( 'display', 'none' );
									}
								} else {
									if ( ! document.getElementById( 'on_site_message_block_cart' )) {
										const umContainer         = document.createElement( 'div' );
										umContainer.id            = 'on_site_message_block_cart';
										umContainer.style.cssText = blockStyles;
										if ( ! installments) {
											umContainer.style.display = 'none';
										}

										selectorBlock.parentNode.insertBefore( umContainer, selectorBlock.nextSibling );

										umContainer.innerHTML = block;
									}
								}
							}
						}
					);
					observer.observe( document.body, {childList: true, subtree: true} );
				}

				function getUmSelector(umSettings) {
					let selector = 'body';

					if (umSettings.banner && 1 == umSettings.banner.enable_banner) {
						if (umSettings.banner.regular && '' !== umSettings.banner.regular) {
							selector = umSettings.banner.regular;
						} else {
							selector = '.wp-block-woocommerce-cart-order-summary-block';
						}
					} else if (umSettings.logo && 1 == umSettings.logo.enable_logo) {
						if (umSettings.logo.regular && '' !== umSettings.logo.regular) {
							selector = umSettings.logo.regular;
						} else {
							selector = '.wp-block-woocommerce-cart-order-summary-block';
						}
					} else if (umSettings.one_liner && 1 == umSettings.one_liner.enable_one_liner) {
						if (umSettings.one_liner.regular && '' !== umSettings.one_liner.regular) {
							selector = umSettings.one_liner.regular;
						} else {
							selector = '.wp-block-woocommerce-cart-order-summary-block';
						}
					}
					return selector;
				}

				function makeBlock(isVisa, tagName, pageConfig, hideUpstreamMessage = '') {
					let $block = $( '<' + tagName + ' ' + hideUpstreamMessage + '></' + tagName + '>' );

					$.each(
						pageConfig,
						function (key, config) {
							if ('enable_one_liner' === key || 'regular' === key || '' === config) {
								return;
							}

							if (('text_size' === key || 'text_main_size' === key || 'banner_width' === key || 'banner_height' === key) && $.isNumeric( config )) {
								config = config + 'px';
							} else if (('hide_learn_more' === key || 'hide_icon' === key) && "1" === config) {
								config = true;
							}

							$block.attr( key, config );
						}
					);

					if ('spt-strip' === tagName && 'top' === pageConfig.position) {
						$block.attr( 'is_solid', true );
					}

					if (isVisa) {
						$block.attr( 'vis', true );
					}

					return $( '<div>' ).append( $block ).html();
				}

				if ('undefined' !== typeof wc && wc.wcSettings && wp.data) {
					let installments = null;

					const {select, subscribe} = wp.data;
					const previousTotals      = select( 'wc/store/cart' ).getCartTotals();
					let previousTotal         = previousTotals ? previousTotals.total_price / 100 : null;

					const unsubscribe           = subscribe(
						() => {
                        const currentTotals = select( 'wc/store/cart' ).getCartTotals();
                        const currentTotal  = currentTotals ? currentTotals.total_price / 100 : null;
                        if (currentTotal !== previousTotal) {
                            previousTotal = currentTotal;
                            installments  = getInstallmentByPrice( currentTotal, splitit_settings, umSettings );
                            if ( ! installments) {
                                $( 'spt-floating-logo, spt-one-liner' ).css( 'display', 'none' );
                            } else {
                                $( 'spt-floating-logo, spt-one-liner' )
                                .css( 'display', '' )
                                .attr( 'amount', currentTotal )
                                .attr( 'installments', installments );
                            }

                        }
						}
					);

					window.addEventListener( 'beforeunload', unsubscribe );
				}

				function getPrice() {
					if ('undefined' !== typeof wc && wc.wcSettings && wp.data) {
						const {select} = wp.data;
						const totals   = select( 'wc/store/cart' ).getCartTotals();
						return totals ? totals.total_price / 100 : null;
					}
				}

				function getInstallmentByPrice(price, settings, pageConfig) {
					if ('undefined' !== typeof settings.splitit_upstream_default_installments && '' !== settings.splitit_upstream_default_installments) {
						return parseInt( settings.splitit_upstream_default_installments );
					}

					let customInstallments = checkCustomInstallmentsSettings( pageConfig, settings );
					if (customInstallments !== null) {
						return customInstallments;
					}

					if ('undefined' !== typeof settings.splitit_inst_conf.ic_installment) {
						const key = getInstallmentIcToByPrice( settings.splitit_inst_conf.ic_to, price, settings.splitit_inst_conf.ic_from );
						if (-1 === key) {
							// Range configured, but product price is not in range.
							return null;
						}
						if (key in settings.splitit_inst_conf.ic_installment) {
							const installment = settings.splitit_inst_conf.ic_installment[key];
							const explode     = installment.split( ',' );
							return Math.max( ...explode.map( Number ) );
						}
					}

					return 4;
				}

				function checkCustomInstallmentsSettings(pageConfig, splititSettings) {
					let umType = '';

					if (pageConfig.strip && pageConfig.strip.enable_strip == 1) {
						umType = 'strip';
					} else if (pageConfig.banner && pageConfig.banner.enable_banner == 1) {
						umType = 'banner';
					} else if (pageConfig.logo && pageConfig.logo.enable_logo == 1) {
						umType = 'logo';
					} else if (pageConfig.one_liner && pageConfig.one_liner.enable_one_liner == 1) {
						umType = 'one_liner';
					}

					let customInstallments = pageConfig[umType] && pageConfig[umType].installments &&
					pageConfig[umType].installments.trim() !== ''
						? parseInt( pageConfig[umType].installments, 10 )
						: null;

					let defaultInstallments = splititSettings.default_installments_number &&
					splititSettings.default_installments_number.trim() !== ''
						? parseInt( splititSettings.default_installments_number, 10 )
						: null;

					return customInstallments !== null ? customInstallments : defaultInstallments;
				}

				function getInstallmentIcToByPrice(installments, priceProduct, installmentsFrom) {
					if (installments && priceProduct && installmentsFrom) {
						const origInstallments = [...installments];
						installments.sort( (a, b) => a - b );
						installmentsFrom.sort( (a, b) => a - b );

						for (let key = 0; key < installments.length; key++) {
							const price = installments[key];
							if (priceProduct <= price &&
							undefined !== installmentsFrom[key] &&
							installmentsFrom[key] <= priceProduct) {
								return origInstallments.indexOf( price );
							}
						}
					}
					return -1;
				}
			}
		}
	)
})( jQuery );
