(function ($) {
	"use strict";

	var closing = "<svg xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' width='15' height='15' viewBox='0 0 24 24' aria-hidden='true'><path d='M12,2C6.47,2,2,6.47,2,12c0,5.53,4.47,10,10,10s10-4.47,10-10C22,6.47,17.53,2,12,2z M16.707,15.293 c0.391,0.391,0.391,1.023,0,1.414C16.512,16.902,16.256,17,16,17s-0.512-0.098-0.707-0.293L12,13.414l-3.293,3.293 C8.512,16.902,8.256,17,8,17s-0.512-0.098-0.707-0.293c-0.391-0.391-0.391-1.023,0-1.414L10.586,12L7.293,8.707 c-0.391-0.391-0.391-1.023,0-1.414s1.023-0.391,1.414,0L12,10.586l3.293-3.293c0.391-0.391,1.023-0.391,1.414,0 s0.391,1.023,0,1.414L13.414,12L16.707,15.293z'></path></svg>";
	var params = window.CNS_params || {};
	var liveRegionClass = "cns-notify-live-region";
	var liveRegionSelector = "." + liveRegionClass;
	var positionClassPrefix = "cns-pos-";
	var trackedAddToCartSelectors = [
		".add_to_cart_button",
		".single_add_to_cart_button",
		".wc-block-components-product-button__button",
		".wc-block-components-product-add-to-cart .wp-block-button__link",
		"[name='add-to-cart']",
		"form.cart button[type='submit']",
		"form.cart input[type='submit']"
	].join(", ");
	var trackedProductContainerSelectors = [
		".product",
		"li.product",
		".wc-block-product",
		".wp-block-woocommerce-product",
		".wc-block-grid__product",
		".wc-block-components-product",
		".wp-block-post"
	].join(", ");
	var interactionWindowMs = 10000;
	var lastAddToCartContext = {
		$trigger: null,
		productData: null,
		capturedAt: 0,
	};

	function escapeHtml(value) {
		return String(value || "")
			.replace(/&/g, "&amp;")
			.replace(/</g, "&lt;")
			.replace(/>/g, "&gt;")
			.replace(/"/g, "&quot;")
			.replace(/'/g, "&#39;");
	}

	function toInt(value, fallback) {
		var parsed = parseInt(value, 10);
		return Number.isNaN(parsed) ? fallback : parsed;
	}

	function getDefaultProductContext() {
		return {
			title: "",
			imageSrc: "",
			quantity: 1,
			variationSummary: "",
		};
	}

	function getDefaultCartSummary() {
		return {
			cartCount: 0,
			cartSubtotal: "",
		};
	}

	function getProductNameFromAriaLabel(value) {
		var label = String(value || "").trim();
		var quoteMatch = label.match(/["']([^"']+)["']/);

		if (quoteMatch && quoteMatch[1]) {
			return quoteMatch[1].trim();
		}

		if (/cart/i.test(label) || /add/i.test(label)) {
			return "";
		}

		return label;
	}

	function sanitizeUrl(value) {
		try {
			var parsed = new URL(String(value || ""), window.location.origin);
			if (parsed.protocol === "http:" || parsed.protocol === "https:") {
				return parsed.href;
			}
		} catch (error) {
			return "";
		}

		return "";
	}

	function applyCssVars(cssVars) {
		if (!cssVars || typeof cssVars !== "object") {
			return;
		}

		var root = document.querySelector(".notiny");
		if (!root) {
			return;
		}

		Object.keys(cssVars).forEach(function (varName) {
			if (varName.indexOf("--CNS-") !== 0) {
				return;
			}
			root.style.setProperty(varName, String(cssVars[varName] || ""));
		});
	}

	function isMobileViewport() {
		return window.matchMedia && window.matchMedia("(max-width: 767px)").matches;
	}

	function userPrefersReducedMotion() {
		return window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
	}

	function getOrCreateLiveRegion() {
		var $liveRegion = $(liveRegionSelector);
		if ($liveRegion.length) {
			return $liveRegion;
		}

		return $("<div/>", {
			class: liveRegionClass + " cns-screen-reader-text",
			role: "status",
			"aria-live": "polite",
			"aria-atomic": "true",
		}).appendTo("body");
	}

	function announceToLiveRegion(text) {
		var safeText = String(text || "").trim();
		if (!safeText) {
			return;
		}

		var $liveRegion = getOrCreateLiveRegion();
		$liveRegion.text("");

		setTimeout(function () {
			$liveRegion.text(safeText);
		}, 25);
	}

	function normalizeAttributeLabel(value) {
		return String(value || "")
			.replace(/^attribute_/, "")
			.replace(/[_-]+/g, " ")
			.trim();
	}

	function parseQuantityFromText(value) {
		var match = String(value || "").match(/\d+/);
		return match ? toInt(match[0], 0) : 0;
	}

	function getVariationSummary($button) {
		var $form = $button.closest("form.cart");
		var entries = [];

		if (!$form.length) {
			return "";
		}

		$form.find(".variations select").each(function () {
			var $select = $(this);
			var rawValue = $select.val();
			if (!rawValue) {
				return;
			}

			var selectedText = $select.find("option:selected").text().trim();
			if (!selectedText) {
				selectedText = String(rawValue);
			}

			var labelText = "";
			var $label = $select.closest("tr").find("label").first();
			if ($label.length) {
				labelText = $label.text().trim();
			}
			if (!labelText) {
				labelText = normalizeAttributeLabel($select.attr("name"));
			}

			entries.push(labelText + ": " + selectedText);
		});

		return entries.join(", ");
	}

	function getAddedQuantity($button) {
		if (!$button || !$button.length) {
			return 1;
		}

		var buttonQuantity = toInt($button.attr("data-quantity") || $button.data("quantity"), 0);
		if (buttonQuantity > 0) {
			return buttonQuantity;
		}

		var $qtyInput = $button.closest("form.cart").find("input.qty").first();
		var inputQuantity = toInt($qtyInput.val(), 0);
		if (inputQuantity > 0) {
			return inputQuantity;
		}

		return 1;
	}

	function getProductContainer($trigger) {
		if (!$trigger || !$trigger.length) {
			return $();
		}

		var $product = $trigger.closest(trackedProductContainerSelectors);
		if ($product.length) {
			return $product.first();
		}

		return $();
	}

	function getProductContext($button) {
		var context = getDefaultProductContext();
		var $product = $();
		var productNameFromAttr = "";

		if (!$button || !$button.length) {
			return context;
		}

		$product = getProductContainer($button);
		context.quantity = getAddedQuantity($button);
		context.variationSummary = getVariationSummary($button);

		if ($product.length) {
			context.title = $product.find(".product_title").first().text().trim();
			if (!context.title) {
				context.title = $product.find(".woocommerce-loop-product__title, .wc-block-grid__product-title").first().text().trim();
			}
			if (!context.title) {
				context.title = $product.find("h1, h2, h3").first().text().trim();
			}
			context.imageSrc = $product.find("img").first().attr("src") || "";
		}

		productNameFromAttr = String($button.attr("data-product_name") || $button.attr("data-product-name") || "").trim();
		if (!context.title && productNameFromAttr) {
			context.title = productNameFromAttr;
		}

		if (!context.title) {
			context.title = getProductNameFromAriaLabel($button.attr("aria-label"));
		}

		return context;
	}

	function mergeProductContext(primary, fallback) {
		var base = getDefaultProductContext();
		var main = primary && typeof primary === "object" ? primary : {};
		var backup = fallback && typeof fallback === "object" ? fallback : {};

		base.title = main.title || backup.title || "";
		base.imageSrc = main.imageSrc || backup.imageSrc || "";
		base.quantity = main.quantity > 0 ? main.quantity : backup.quantity > 0 ? backup.quantity : 1;
		base.variationSummary = main.variationSummary || backup.variationSummary || "";

		return base;
	}

	function normalizeServerNotice(rawNotice) {
		var notice = rawNotice && typeof rawNotice === "object" ? rawNotice : {};
		var quantity = toInt(notice.quantity, 0);
		var cartCount = toInt(notice.cart_count, 0);

		return {
			title: String(notice.title || "").trim(),
			imageSrc: sanitizeUrl(notice.image || notice.imageSrc || ""),
			quantity: quantity > 0 ? quantity : 0,
			variationSummary: String(notice.variation_summary || notice.variationSummary || "").trim(),
			cartCount: cartCount > 0 ? cartCount : 0,
			cartSubtotal: String(notice.cart_subtotal || notice.cartSubtotal || "").trim(),
		};
	}

	function hasServerNoticeData(rawNotice) {
		var quantity = toInt(rawNotice && rawNotice.quantity, 0);

		if (!rawNotice || typeof rawNotice !== "object") {
			return false;
		}

		return Boolean(rawNotice.title || rawNotice.image || rawNotice.imageSrc || quantity > 0 || rawNotice.variation_summary || rawNotice.variationSummary);
	}

	function dispatchDeveloperEvent(eventName, detail) {
		$(document.body).trigger(eventName, [detail]);
		if (typeof window.CustomEvent === "function") {
			document.dispatchEvent(new CustomEvent(eventName, { detail: detail }));
		}
	}

	function rememberTrigger($trigger) {
		var now = Date.now();
		if (!$trigger || !$trigger.length) {
			return;
		}

		lastAddToCartContext = {
			$trigger: $trigger,
			productData: getProductContext($trigger),
			capturedAt: now,
		};
	}

	function getRememberedTrigger() {
		if (!lastAddToCartContext.$trigger || !lastAddToCartContext.$trigger.length) {
			return $();
		}

		if (Date.now() - lastAddToCartContext.capturedAt > interactionWindowMs) {
			return $();
		}

		return lastAddToCartContext.$trigger;
	}

	function getDomCartSummary() {
		var summary = getDefaultCartSummary();
		var cartCountText = $(".wc-block-mini-cart__badge, .site-header-cart .count, .cart-contents .count").first().text().trim();
		var cartSubtotalText = $(".wc-block-mini-cart__footer .wc-block-components-totals-footer-item .wc-block-components-formatted-money-amount, .woocommerce-mini-cart__total .amount, .wc-block-mini-cart__amount").first().text().trim();

		summary.cartCount = parseQuantityFromText(cartCountText);
		summary.cartSubtotal = cartSubtotalText;

		return summary;
	}

	function extractCartSummary(fragments) {
		var cartSummary = getDefaultCartSummary();
		var cartCount = 0;
		var cartSubtotal = "";

		if (!fragments || typeof fragments !== "object") {
			return cartSummary;
		}

		Object.keys(fragments).forEach(function (fragmentKey) {
			var markup = fragments[fragmentKey];
			if (typeof markup !== "string" || !markup) {
				return;
			}

			var $fragment = $("<div/>").html(markup);

			if (!cartSubtotal) {
				cartSubtotal = $fragment.find(".woocommerce-mini-cart__total .amount").last().text().trim();
			}
			if (!cartSubtotal) {
				cartSubtotal = $fragment.find(".cart-subtotal .amount").last().text().trim();
			}

			if (!cartCount) {
				var miniCartItemCount = $fragment.find(".woocommerce-mini-cart-item, .mini_cart_item").length;
				if (miniCartItemCount > 0) {
					var quantityTotal = 0;
					$fragment.find(".woocommerce-mini-cart-item .quantity, .mini_cart_item .quantity").each(function () {
						quantityTotal += parseQuantityFromText($(this).text());
					});
					cartCount = quantityTotal > 0 ? quantityTotal : miniCartItemCount;
				}
			}

			if (!cartCount) {
				var countText = $fragment.find(".count").first().text().trim();
				cartCount = parseQuantityFromText(countText);
			}
		});

		cartSummary.cartCount = cartCount;
		cartSummary.cartSubtotal = cartSubtotal;

		return cartSummary;
	}

	function getActionsMarkup() {
		var actions = [];
		var cartUrl = sanitizeUrl(params.cart_url);
		var checkoutUrl = sanitizeUrl(params.checkout_url);

		if (params.show_view_cart && cartUrl) {
			actions.push(
				"<a class='cns_notify_action cns_notify_link' href='" +
					escapeHtml(cartUrl) +
					"'>" +
					escapeHtml(params.view_cart_label || "View Cart") +
					"</a>"
			);
		}

		if (params.show_checkout && checkoutUrl) {
			actions.push(
				"<a class='cns_notify_action cns_notify_link cns_notify_link_primary' href='" +
					escapeHtml(checkoutUrl) +
					"'>" +
					escapeHtml(params.checkout_label || "Checkout") +
					"</a>"
			);
		}

		if (params.show_continue) {
			actions.push(
				"<button type='button' class='cns_notify_action cns_continue_button'>" +
					escapeHtml(params.continue_label || "Continue Shopping") +
					"</button>"
			);
		}

		if (!actions.length) {
			return "";
		}

		return "<div class='cns_notify_actions'>" + actions.join("") + "</div>";
	}

	function getMetaMarkup(productData, cartSummary) {
		var parts = [];
		var quantityLabel = params.quantity_label || "Qty";
		var variationsLabel = params.variations_label || "Options";
		var itemsLabel = params.items_label || "Items in cart";
		var subtotalLabel = params.subtotal_label || "Subtotal";

		if (productData.quantity > 0) {
			parts.push("<span class='cns_notify_meta_item'>" + escapeHtml(quantityLabel) + ": " + escapeHtml(productData.quantity) + "</span>");
		}

		if (productData.variationSummary) {
			parts.push("<span class='cns_notify_meta_item'>" + escapeHtml(variationsLabel) + ": " + escapeHtml(productData.variationSummary) + "</span>");
		}

		if (cartSummary.cartCount > 0) {
			parts.push("<span class='cns_notify_meta_item'>" + escapeHtml(itemsLabel) + ": " + escapeHtml(cartSummary.cartCount) + "</span>");
		}

		if (cartSummary.cartSubtotal) {
			parts.push("<span class='cns_notify_meta_item'>" + escapeHtml(subtotalLabel) + ": " + escapeHtml(cartSummary.cartSubtotal) + "</span>");
		}

		if (!parts.length) {
			return "";
		}

		return "<div class='cns_notify_meta'>" + parts.join("") + "</div>";
	}

	function getNotificationMarkup(productData, cartSummary) {
		var styleClass = String(params.style_class || "").trim();
		var positionClass = positionClassPrefix + String(params.notifyposition || "right-bottom").replace(/[^a-z-]/g, "");
		var templateClass = "cns-template-" + String(params.template || "default").replace(/[^a-z0-9_-]/gi, "").toLowerCase();
		var titleMarkup = productData.title ? "<h2>" + escapeHtml(productData.title) + "</h2>" : "";
		var message = params.success_message || "The product has been successfully added to the cart.";
		var closeLabel = params.close_label || "Close notification";
		var messageMarkup =
			"<div class='cns_notify_message_row'><span class='cns_notify_message'>" +
			escapeHtml(message) +
			"</span><button type='button' class='cns_close_button' aria-label='" +
			escapeHtml(closeLabel) +
			"'>" +
			closing +
			"</button></div>";
		var metaMarkup = getMetaMarkup(productData, cartSummary);
		var classNames = "cns-notify " + positionClass + " " + templateClass + (styleClass ? " " + styleClass : "");

		return "<div class='" + escapeHtml(classNames) + "' role='status' aria-live='polite' aria-atomic='true'>" + titleMarkup + messageMarkup + metaMarkup + getActionsMarkup() + "</div>";
	}

	function getMostRecentNotice() {
		var $notices = $(".notiny .notiny-base");
		if (!$notices.length) {
			return $();
		}

		return $notices.last();
	}

	function bindNotificationEvents() {
		$(document).on("click", ".cns_close_button", function (event) {
			event.preventDefault();
			event.stopPropagation();
			var $notice = $(this).closest(".notiny-base");
			if ($notice.length) {
				$.notiny.close($notice);
			}
		});

		$(document).on("click", ".cns_notify_link", function (event) {
			event.stopPropagation();
		});

		$(document).on("click", ".cns_continue_button", function (event) {
			event.preventDefault();
			event.stopPropagation();
			var $notice = $(this).closest(".notiny-base");
			if ($notice.length) {
				$.notiny.close($notice);
			}
		});

		$(document).on("keydown", function (event) {
			if (event.key !== "Escape") {
				return;
			}

			var $notice = getMostRecentNotice();
			if ($notice.length) {
				$.notiny.close($notice);
			}
		});
	}

	function bindAddToCartCaptureEvents() {
		$(document).on("click", trackedAddToCartSelectors, function () {
			rememberTrigger($(this));
		});

		$(document).on("submit", "form.cart", function () {
			var $form = $(this);
			var $trigger = $form.find(":submit:focus").first();

			if (!$trigger.length) {
				$trigger = $form.find("[name='add-to-cart'], .single_add_to_cart_button, button[type='submit'], input[type='submit']").first();
			}

			if ($trigger.length) {
				rememberTrigger($trigger);
			}
		});
	}

	function buildNotificationDetail(productData, cartSummary) {
		return {
			title: productData.title || "",
			image: productData.imageSrc || "",
			quantity: productData.quantity || 0,
			variations: productData.variationSummary || "",
			cart_count: cartSummary.cartCount || 0,
			cart_subtotal: cartSummary.cartSubtotal || "",
			position: params.notifyposition || "right-bottom",
		};
	}

	function showNotificationFromEvent(fragments, $trigger, serverNotice) {
		var rememberedTrigger = getRememberedTrigger();
		var effectiveTrigger = $trigger && $trigger.length ? $trigger : rememberedTrigger;
		var normalizedServerNotice = normalizeServerNotice(serverNotice);
		var productData = mergeProductContext(getProductContext(effectiveTrigger), lastAddToCartContext.productData);
		var duration = parseInt(params.duration, 10);
		var cartSummary = extractCartSummary(fragments);
		var domSummary = null;
		var notificationText = "";
		var useReducedMotion = userPrefersReducedMotion();
		var detail = {};
		var serverProductData = getDefaultProductContext();

		if (effectiveTrigger && effectiveTrigger.hasClass("product_type_external")) {
			return;
		}

		if (effectiveTrigger && effectiveTrigger.length) {
			rememberTrigger(effectiveTrigger);
		}

		serverProductData.title = normalizedServerNotice.title;
		serverProductData.imageSrc = normalizedServerNotice.imageSrc;
		serverProductData.quantity = normalizedServerNotice.quantity > 0 ? normalizedServerNotice.quantity : 1;
		serverProductData.variationSummary = normalizedServerNotice.variationSummary;
		productData = mergeProductContext(productData, serverProductData);
		if (normalizedServerNotice.quantity > 0) {
			productData.quantity = normalizedServerNotice.quantity;
		}

		if (Number.isNaN(duration) || duration < 1000) {
			duration = 3000;
		}

		if (!cartSummary.cartCount || !cartSummary.cartSubtotal) {
			domSummary = getDomCartSummary();
			if (!cartSummary.cartCount) {
				cartSummary.cartCount = domSummary.cartCount;
			}
			if (!cartSummary.cartSubtotal) {
				cartSummary.cartSubtotal = domSummary.cartSubtotal;
			}
		}

		if (!cartSummary.cartCount && normalizedServerNotice.cartCount > 0) {
			cartSummary.cartCount = normalizedServerNotice.cartCount;
		}

		if (!cartSummary.cartSubtotal && normalizedServerNotice.cartSubtotal) {
			cartSummary.cartSubtotal = normalizedServerNotice.cartSubtotal;
		}

		notificationText = getNotificationMarkup(productData, cartSummary);
		detail = buildNotificationDetail(productData, cartSummary);
		dispatchDeveloperEvent("cart_notify_before_render", detail);

		$.notiny({
			theme: "CNS_dark",
			width: "400",
			image: params.show_image ? (productData.imageSrc || void 0) : void 0,
			text: notificationText,
			position: params.notifyposition || "right-bottom",
			delay: duration,
			clickhide: false,
			animate: !useReducedMotion,
		});

		applyCssVars(params.css_vars);
		announceToLiveRegion((productData.title ? productData.title + ". " : "") + (params.success_message || ""));
		dispatchDeveloperEvent("cart_notify_after_render", detail);
		dispatchDeveloperEvent("cart_notify_notification_shown", detail);
	}

	jQuery(document).ready(function () {
		if (!params.enabled) {
			return;
		}

		if (!params.show_on_mobile && isMobileViewport()) {
			return;
		}

		getOrCreateLiveRegion();
		bindNotificationEvents();
		bindAddToCartCaptureEvents();

		$.notiny.addTheme("CNS_dark", {
			notification_class: "notify-theme-CNS-dark notiny-default-vars",
		});

		if (hasServerNoticeData(params.server_notice)) {
			showNotificationFromEvent(null, $(), params.server_notice);
		}

		$(document.body).on("added_to_cart", function (event, fragments, cart_hash, $button) {
			if ($button && $button.length) {
				rememberTrigger($button);
			}

			showNotificationFromEvent(fragments, $button, null);
		});

		if (document.body && typeof document.body.addEventListener === "function") {
			document.body.addEventListener("wc-blocks_added_to_cart", function () {
				showNotificationFromEvent(null, getRememberedTrigger(), null);
			});
		}
	});
})(jQuery);
