@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.ParagraphViewModel>
@using Dynamicweb.Ecommerce.ProductCatalog
@using Dynamicweb.Core

@{
	int productsCount = 0;
	int maxProductsCounter = 0;

	ProductListViewModel? productList = null;
	if (Dynamicweb.Context.Current is not null && Dynamicweb.Context.Current.Items.Contains("ProductList"))
	{
		productList = (ProductListViewModel?)Dynamicweb.Context.Current.Items["ProductList"];
	}
}

@if (productList is not null)
{
	<div class="h-100 product-list" data-dw-colorscheme="@Model.ColorScheme?.Id">
		@{
			bool isVisualEditor = !string.IsNullOrEmpty(Dynamicweb.Context.Current?.Request.QueryString.Get("VisualEdit")) ? Convert.ToBoolean(Dynamicweb.Context.Current.Request.QueryString.Get("VisualEdit")) : false;

			string groupId = productList?.Group?.Id != null ? productList.Group.Id : "";

			if (productList?.TotalProductsCount > 0)
			{
				int pageSizeSetting = Converter.ToInt32(Dynamicweb.Context.Current?.Request.QueryString.Get("OriginalPageSize")) > 0 ? Converter.ToInt32(Dynamicweb.Context.Current.Request.QueryString.Get("OriginalPageSize")) : productList.PageSize;
				int pageNumber = Converter.ToInt32(Dynamicweb.Context.Current?.Request.QueryString.Get("PageNum")) > 0 ? Converter.ToInt32(Dynamicweb.Context.Current.Request.QueryString.Get("PageNum")) : productList.CurrentPage;
				int pageSize = Converter.ToInt32(Dynamicweb.Context.Current?.Request.QueryString.Get("PageSize")) > 0 ? Converter.ToInt32(Dynamicweb.Context.Current.Request.QueryString.Get("PageSize")) : productList.PageSize;
				pageNumber = pageSize != pageSizeSetting ? (pageSize / pageSizeSetting) : pageNumber;
				int loadedProducts = productList.PageSize > productList.TotalProductsCount ? productList.TotalProductsCount : pageSizeSetting * pageNumber;
				loadedProducts = loadedProducts > productList.TotalProductsCount ? productList.TotalProductsCount : loadedProducts;

				pageNumber += 1;

				string? searchQuery = Dynamicweb.Context.Current?.Request["q"];

				string? searchLayout = Dynamicweb.Context.Current?.Request.QueryString.Get("SearchLayout");

				int itemSourcePageId = Convert.ToInt32(Model.Item?.GetRawValueString("ListComponentSource", "0"));
				itemSourcePageId = Dynamicweb.Content.Services.Pages.GetPageOrLanguage(itemSourcePageId, Pageview.AreaID)?.ID ?? itemSourcePageId;

				var page = Dynamicweb.Content.Services.Pages.GetPage(itemSourcePageId);

				if (page != null)
				{
					var pageViewModel = Dynamicweb.Frontend.ContentViewModelFactory.CreatePageInfoViewModel(page);

					string? gridColumnSize = Model.Item?.GetRawValueString("GridLayoutDesktop", "3-columns");
					gridColumnSize = gridColumnSize == "2-columns" ? "g-col-lg-6" : gridColumnSize;
					gridColumnSize = gridColumnSize == "3-columns" ? "g-col-lg-4" : gridColumnSize;
					gridColumnSize = gridColumnSize == "4-columns" ? "g-col-lg-3" : gridColumnSize;
					gridColumnSize = gridColumnSize == "6-columns" ? "g-col-lg-2" : gridColumnSize;
					gridColumnSize = gridColumnSize == "list" ? "g-col-lg-12" : gridColumnSize;

					string? gridColumnMobileSize = Model.Item?.GetRawValueString("GridLayoutMobile", "2-columns");
					gridColumnMobileSize = gridColumnMobileSize == "list" ? "g-col-12" : gridColumnMobileSize;
					gridColumnMobileSize = gridColumnMobileSize == "2-columns" ? "g-col-6" : gridColumnMobileSize;

					<div class="grid pb-3">
						<script>
							window.dataLayer = window.dataLayer || [];
							window.dataLayer.push({
								event: "view_item_list",
								ecommerce: {
									item_list_id: "product_list_item_repeater",
									item_list_name: "Product list (Item Repeater)",
									items: [
										@foreach (ProductViewModel product in productList.Products)
										{
											<text>{
												item_id: "@product.Number",
												item_name: "@Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(product.Name)",
												currency: "@product.Price.CurrencyCode",
												price: @product.Price.ToStringInvariant(),
												discount: @product.Discount.ToStringInvariant()
											},</text>
										}
									]
								}
							});
						</script>

						@foreach (ProductViewModel product in productList.Products)
						{
							if (maxProductsCounter == 0 || (productsCount < maxProductsCounter))
							{
								string link = product.GetProductLink(GetPageIdByNavigationTag("Shop"), false);

								if (Dynamicweb.Context.Current?.Items.Contains("ProductDetails") != null)
								{
									Dynamicweb.Context.Current.Items["ProductDetails"] = product;
								}
								else
								{
									Dynamicweb.Context.Current?.Items.Add("ProductDetails", product);
								}

								if (Model.Item?.GetString("ListComponentSource") != null)
								{
									<article class="@gridColumnMobileSize @gridColumnSize d-flex flex-column position-relative product js-product" data-product-id="@product.Id" data-variant-id="@product.VariantId" itemscope itemtype="https://schema.org/Product">
										@{
											string clickProductLink = "onclick=\"return clickProductLink('" + @product.Id + "', '" + @Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(product.Name) + "', '" + @Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(product.VariantName) + "', '" + @product.Price.CurrencyCode + "', '" + @product.Price.ToStringInvariant() + "', '" + @product.Discount.ToStringInvariant() + "')\"";
										}
										<a href="@link" class="stretched-link" onmouseenter="swift.Image.swapImage(event)" onmouseout="swift.Image.swapImage(event)" @clickProductLink>
											<span class="visually-hidden">@product.Name</span>
										</a>
										
										<script>
											function clickProductLink(productId, productName, productVariant, productCurrency, productPrice, productDiscount) {
												window.dataLayer = window.dataLayer || [];
												window.dataLayer.push({
													event: "select_item",
													ecommerce: {
														item_list_id: "product_list_item_repeater",
														item_list_name: "Product list (Item Repeater)",
														items: [
															{
																item_id: productId,
																item_name: productName,
																currency: productCurrency,
																item_list_id: "product_list_item_repeater",
																item_list_name: "Product list (Item Repeater)",
																item_variant: productVariant,
																price: productPrice,
																discount: productDiscount
															}
														]
													}
												});
											}
										</script>

										@RenderGrid(itemSourcePageId)
									</article>
								}

								productsCount++;
							}
						}
					</div>

					<div class="my-3" id="ProductListLoadMore">
						<div class="text-center">
							<div class="opacity-85 mb-3">@loadedProducts @Translate("out of") @productList.TotalProductsCount @Translate("products")</div>
							@if (productList.PageCount != 1 && maxProductsCounter == 0 && loadedProducts < productList.TotalProductsCount)
							{
								string? sortBySelection = Dynamicweb.Context.Current?.Request.Form["SortBy"] ?? "";
								sortBySelection = Dynamicweb.Context.Current?.Request.QueryString.Get("SortBy") ?? sortBySelection;
								string? mainProductId = Dynamicweb.Context.Current?.Request.QueryString.Get("MainProductID");

								<form method="get" data-response-target-element=".product-list" data-swap="afterend" class="w-100">
									@if (productList?.FacetGroups != null)
									{
										foreach (FacetGroupViewModel facetGroup in productList.FacetGroups)
										{
											foreach (FacetViewModel facetItem in facetGroup.Facets)
											{
												foreach (FacetOptionViewModel facetOption in facetItem.Options)
												{
													if (facetOption.Selected)
													{
														<input type="hidden" name="@facetItem.QueryParameter" value="[@facetOption.Value]">
													}
												}
											}
										}
									}

									@if (!string.IsNullOrEmpty(searchQuery))
									{
										<input type="hidden" name="q" value="@searchQuery">
										<input type="hidden" name="SearchLayout" value="@searchLayout">
									}

									@if (!string.IsNullOrEmpty(mainProductId))
									{
										<input type="hidden" name="MainProductID" value="@mainProductId">
									}

									@if (productList?.Group?.Id != null)
									{
										<input type="hidden" name="GroupId" value="@groupId">
									}

									<input type="hidden" name="OriginalPageSize" value="@pageSizeSetting">
									<input type="hidden" name="PageSize" value="@(loadedProducts + pageSizeSetting)">
									<input type="hidden" name="PageNum" value="@pageNumber">
									<input type="hidden" name="SortBy" value="@sortBySelection">
									<input type="hidden" name="RequestType" value="UpdateList">
									<input type="hidden" name="ParagraphID" value="@Model.ID">

									@if (productList?.FacetGroups is object)
									{
										string nextPageLink = $"/Default.aspx?ID={Model.PageID}&PageNum={pageNumber}&SortBy={sortBySelection}";

										foreach (FacetGroupViewModel facetGroup in productList.FacetGroups)
										{
											foreach (FacetViewModel facetItem in facetGroup.Facets)
											{
												foreach (FacetOptionViewModel facetOption in facetItem.Options)
												{
													if (facetOption.Selected)
													{
														nextPageLink += "&" + facetItem.QueryParameter + "=[" + facetOption.Value + "]";
													}
												}
											}
										}

										nextPageLink += !string.IsNullOrEmpty(searchQuery) ? "&q=" + searchQuery : "";

										<a href="@nextPageLink" class="btn btn-primary swift_load_more_button" data-dw-button="primary" onclick="swift.ProductList.Update(event)" id="LoadMoreButton_@Model.ID">@Translate("Load more products")</a>
									}
								</form>
							}
						</div>
					</div>

					<script>
						function switchVariantProduct(id, price, imagesrc) {
							var productImageElement = document.querySelector("#ProductImage_" + id);
							var productPriceElement = document.querySelector("#ProductPrice_" + id + " .text-price");

							if (productPriceElement) {
								productPriceElement.innerText = price;
							}

							if (productImageElement) {
								productImageElement.src = imagesrc;

								var imageSrcset = productImageElement.srcset;
								imageSrcset = imageSrcset.replace(/image=.*?&/g, 'image=' + imagesrc + "&");

								productImageElement.srcset = imageSrcset;
							}
						}
					</script>
				}
				else if (Pageview.IsVisualEditorMode)
				{
					<div class="alert alert-dark m-0" role="alert">
						<span>@Translate("The selected component does not exist anymore")</span>
					</div>
				}
			}
			else
			{
				string? noProductsFoundMessage = Model.Item?.GetString("NoProductsFoundMessage") ?? Translate("We did not find anything matching your search result");
				bool hasSubgroups = false;

				if (productList?.SubGroups != null)
				{
					hasSubgroups = productList.SubGroups.Any();
				}

				if (Model.Item is not null && !Model.Item.GetBoolean("HideNoProductsFoundMessage"))
				{
					if (!isVisualEditor)
					{
						<div class="alert alert-dark m-0" role="alert">
							@noProductsFoundMessage
						</div>
					}
					else
					{
						<div class="alert alert-dark m-0" role="alert">
							@Translate("Product list: The list will be shown here, if any")
						</div>
					}
				}
				else if (!hasSubgroups)
				{
					<div class="alert alert-dark m-0" role="alert">
						@noProductsFoundMessage
					</div>
				}
			}
		}
	</div>
}
else if (Pageview.IsVisualEditorMode)
{
	<div class="alert alert-dark m-0" role="alert">
		<span>@Translate("Product list item repeater: The repeater paragraph will be shown here, if any products are available")</span>
	</div>
}
