@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.ParagraphViewModel>
@using Dynamicweb.Ecommerce.ProductCatalog
@using Dynamicweb.Frontend.Navigation
@using Dynamicweb.Environment
@using Dynamicweb.Core.Encoders
@using System.Text.RegularExpressions

@{
	string deviceType = !string.IsNullOrEmpty(GetViewParameterString("DeviceType")) ? GetViewParameterString("DeviceType") : "desktop";

	ProductListViewModel productList = new ProductListViewModel();
	if (Dynamicweb.Context.Current.Items.Contains("ProductList"))
	{
		productList = (ProductListViewModel)Dynamicweb.Context.Current.Items["ProductList"];
	}

	string groupId = !string.IsNullOrEmpty(Dynamicweb.Context.Current.Request.QueryString.Get("GroupID")) ? Dynamicweb.Context.Current.Request.QueryString.Get("GroupID") : string.Empty;

	string iconPath = "/Files/Images/Icons/";
	string pageSize = !string.IsNullOrEmpty(Dynamicweb.Context.Current.Request.QueryString.Get("PageSize")) ? Dynamicweb.Context.Current.Request.QueryString.Get("PageSize") : productList.PageSize.ToString();

	string searchQuery = !string.IsNullOrEmpty(Dynamicweb.Context.Current.Request.QueryString.Get("q")) ? Dynamicweb.Context.Current.Request.QueryString.Get("q") : string.Empty;
	searchQuery = !string.IsNullOrEmpty(Dynamicweb.Context.Current.Request.Form.Get("q")) ? Dynamicweb.Context.Current.Request.Form.Get("q") : searchQuery;
	string searchLayout = !string.IsNullOrEmpty(Dynamicweb.Context.Current.Request.QueryString.Get("SearchLayout")) ? Dynamicweb.Context.Current.Request.QueryString.Get("SearchLayout") : string.Empty;

	int groupCount = 0;
	int maxGroups = 8;
	int totalGroups = productList?.FacetGroups != null ? productList.FacetGroups.Count() : 0;

	bool enableSorting = Model.Item.GetBoolean("SortByNameAZ");
	enableSorting = Model.Item.GetBoolean("SortByNameZA") || enableSorting == true ? true : false;
	enableSorting = Model.Item.GetBoolean("SortByNewest") || enableSorting == true ? true : false;
	enableSorting = Model.Item.GetBoolean("SortByLowestPrice") || enableSorting == true ? true : false;
	enableSorting = Model.Item.GetBoolean("SortByHighestPrice") || enableSorting == true ? true : false;

	string layout = Model.Item.GetRawValueString("Layout", "vertical");
	layout = deviceType == "mobile" ? "vertical" : layout;

	var sortingParms = new Dictionary<string, object>();
	sortingParms.Add("DeviceType", deviceType);
}

<input type="hidden" name="PageSize" value="@pageSize">

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

@if (Model.Item.GetBoolean("EnableGroupNavigation") && layout == "vertical")
{
	int startLevel = Convert.ToInt32(Model.Item.GetRawValueString("GroupNavigationStartLevel", "2"));
	int stopLevel = Convert.ToInt32(Model.Item.GetRawValueString("GroupNavigationStopLevel", "9"));

	var navigationSettings = new NavigationSettings();
	navigationSettings.StartLevel = startLevel;
	navigationSettings.StopLevel = stopLevel;
	navigationSettings.ExpandMode = ExpandMode.All;
	navigationSettings.Parameters.Add("menu-id", "product-list-facets");
	navigationSettings.Parameters.Add("ID", deviceType);
	navigationSettings.Parameters.Add("HideTexts", false);
	navigationSettings.Parameters.Add("HideIcons", true);

	<div class="border-bottom py-2">
		<div class="d-flex" data-bs-toggle="collapse" data-bs-target="#ProductGroupNavigation_@(deviceType)_@Model.ID" role="button" aria-expanded="true" aria-controls="ProductGroupNavigation_@(deviceType)_@Model.ID">
			<span class="opacity-85 m-0 flex-fill h6">@Translate("Navigation")</span>
			<div class="my-auto collapse-chevron-icon"></div>
		</div>
		<div class="collapse show" id="ProductGroupNavigation_@(deviceType)_@Model.ID">
			@Navigation.RenderNavigation("Navigation/VerticalAndBreadcrumb.cshtml", navigationSettings)
		</div>
	</div>
}

@if (enableSorting)
{
	if (layout == "vertical")
	{
		<div class="border-bottom">
			<h2 class="opacity-85 m-0 my-2 flex-fill h6">@Translate("Sort by")</h2>
			<div class="d-flex flex-column gap-2" id="SortBy_@(deviceType)_@Model.ID">
				@RenderPartial("Paragraph/ProductListFacets/Sorting.cshtml", Model, sortingParms)
			</div>
		</div>
	}
	if (layout == "horizontal")
	{
		<button class="btn dropdown-toggle" type="button" id="SortBy_@(deviceType)_@Model.ID" data-bs-toggle="dropdown" aria-expanded="false" tabindex="0">
			@Translate("Sort by")
		</button>
		<div class="dropdown-menu p-3" aria-labelledby="SortBy_@(deviceType)_@Model.ID" style="min-width: 280px">
			<div class="d-flex flex-column gap-2">
				@RenderPartial("Paragraph/ProductListFacets/Sorting.cshtml", Model, sortingParms)
			</div>
		</div>
	}
}

@if (productList.FacetGroups != null)
{
	foreach (FacetGroupViewModel facetGroup in productList.FacetGroups)
	{
		string border = groupCount != totalGroups ? "border-bottom" : string.Empty;

		foreach (FacetViewModel facet in facetGroup.Facets)
		{
			string collapseClass = string.Empty;
			string showClass = " show";
			string ariaExpanded = "true";
			var expandedFacetGroups = Model.Item.GetRawValueString("ExpandFacetGroups", "all");
			string facetGroupId = Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", string.Empty);

			if (expandedFacetGroups != "all" && System.Text.RegularExpressions.Regex.IsMatch(expandedFacetGroups, "([0-9])"))
			{
				if (groupCount >= Dynamicweb.Core.Converter.ToInt32(expandedFacetGroups) && !facet.Options.Any(f => f.Selected))
				{
					collapseClass = " collapsed";
					showClass = string.Empty;
					ariaExpanded = "false";
				}
			}

			if (facet.Options.Count() > 0)
			{
				if (layout == "vertical")
				{
					<div class="@border">
						<div class="d-flex@(collapseClass)" data-bs-toggle="collapse" data-bs-target="#FacetGroup_@facetGroupId" role="button" aria-expanded="@ariaExpanded" aria-controls="FacetGroup_@facetGroupId" tabindex="0" onfocus="if(this.classList.contains('collapsed')){this.click();}">
							<span class="opacity-85 m-0 flex-fill h6 my-2">@Translate(facet.Name)</span>
							<div class="my-auto collapse-chevron-icon"></div>
						</div>
						<div class="collapse@(showClass)" id="FacetGroup_@facetGroupId" data-swift-facet-container>
							@if (facet.Options.Count() > 10)
							{
								<input type="text" class="form-control mb-2" placeholder="Filter options..." data-swift-facet-filter-input>
							}
							<div class="ps-1 pe-2 overflow-y-auto" style="max-height: 15rem; scrollbar-gutter: stable;">
								@foreach (FacetOptionViewModel facetOption in facet.Options)
								{
									string renderType = facet.RenderType;
									string facetLabel = HtmlEncoder.HtmlEncode(facetOption.Label);
									string disabled = facetOption.Count <= 0 ? "disabled" : string.Empty;
									string selected = facetOption.Selected ? "checked" : string.Empty;
									var optionValue = facet.FacetType != "List" && facetOption.Value.Contains(",") ? $"[{HtmlEncoder.HtmlEncode(facetOption.Value)}]" : HtmlEncoder.HtmlEncode(facetOption.Value);

									if (renderType == "Colors")
									{
										string image = facetOption.Value;
										string colorCode = facetOption.Value;

										var variantOption = Dynamicweb.Ecommerce.Services.VariantOptions.GetVariantOption(facetOption.Value.ToString());
										if (variantOption != null)
										{
											image = variantOption.LargeImage;
											colorCode = variantOption.Color;
										}

										<div class="colorbox">
											<label>
													<input type="checkbox" onclick="swift.ProductList.Update(event)" onkeydown="if(event.key==='Enter'){this.checked=!this.checked;swift.ProductList.Update(event);}" class="@disabled @selected" name="@facet.QueryParameter" value="@optionValue" data-filter-value="@facetLabel" @selected title="@facetOption.Label">
												@if (colorCode.Contains("#"))
												{
													<span class="colorbox-background" style="background-color: @colorCode"></span>
													<span class="visually-hidden">@facetOption.Label</span>
												}
												else
												{
													<span class="colorbox-background">
														<img src="/Admin/Public/GetImage.ashx?width=25&height=25&image=@image">
														<span class="visually-hidden">@facetOption.Label</span>
													</span>
												}
											</label>
										</div>
									}
									else
									{
										facetLabel = facetLabel.ToLower() == "true" ? facetLabel = Translate("Yes") : facetLabel;
										facetLabel = facetLabel.ToLower() == "false" ? facetLabel = Translate("No") : facetLabel;

										<label class="form-check mt-1" @disabled>
											<input type="checkbox" onclick="swift.ProductList.Update(event)" onkeydown="if(event.key==='Enter'){this.checked=!this.checked;swift.ProductList.Update(event);}" class="form-check-input" name="@facet.QueryParameter" value="@optionValue" data-filter-value="@facetLabel" @selected>
											<span class="form-check-label d-flex align-items-center">
												<span class="flex-fill">@facetLabel </span>
												@if (facet.FacetType.ToLower() == "field")
												{
													<small class="opacity-85">@facetOption.Count</small>
												}
											</span>
										</label>
									}
								}
							</div>
						</div>
					</div>
				}
				if (layout == "horizontal")
				{
					string hideSelector = groupCount < maxGroups ? string.Empty : "d-none";
					int selectedFacetsInGroup = 0;

					foreach (FacetOptionViewModel option in facet.Options)
					{
						if (option.Selected)
						{
							selectedFacetsInGroup++;
						}
					}

					string label = selectedFacetsInGroup > 0 ? @Translate(facet.Name) + "<span class=\"badge bg-dark opacity-50 text-white ms-2\">" + selectedFacetsInGroup + "</span>" : @Translate(facet.Name);

					<div class="dropdown @hideSelector js-facets-selector">
						<button class="btn dropdown-toggle" type="button" id="FacetGroup_@facetGroupId" data-bs-toggle="dropdown" aria-expanded="false" tabindex="0">
							@label
						</button>
						<div class="dropdown-menu p-3 overflow-y-auto" role="group" aria-labelledby="FacetGroup_@facetGroupId" style="min-width: 280px;max-height: 15rem;" data-swift-facet-container>
							@if (facet.Options.Count() > 10)
							{
								<input type="text" class="form-control mb-2" placeholder="Filter options..." data-swift-facet-filter-input>
							}
							@foreach (FacetOptionViewModel facetOption in facet.Options)
							{
								string renderType = facet.RenderType;
								string facetLabel = HtmlEncoder.HtmlEncode(facetOption.Label);
								string disabled = facetOption.Count <= 0 ? "disabled" : string.Empty;
								string selected = facetOption.Selected ? "checked" : string.Empty;
								var optionValue = facet.FacetType != "List" && facetOption.Value.Contains(",") ? $"[{HtmlEncoder.HtmlEncode(facetOption.Value)}]" : HtmlEncoder.HtmlEncode(facetOption.Value);

								if (renderType == "Colors")
								{
									string image = facetOption.Value;
									string colorCode = facetOption.Value;

									var variantOption = Dynamicweb.Ecommerce.Services.VariantOptions.GetVariantOption(facetOption.Value.ToString());
									if (variantOption != null)
									{
										image = variantOption.LargeImage;
										colorCode = variantOption.Color;
									}

									<div class="colorbox">
										<label>
											<input type="checkbox" onclick="swift.ProductList.Update(event)" onkeydown="if(event.key==='Enter'){this.checked=!this.checked;swift.ProductList.Update(event);}" class="@disabled @selected" name="@facet.QueryParameter" value="@optionValue" data-filter-value="@facetLabel" @selected title="@facetOption.Label">
											@if (colorCode.Contains("#"))
											{
												<span class="colorbox-background" style="background-color: @colorCode"></span>
												<span class="visually-hidden">@facetOption.Label</span>
											}
											else
											{
												<span class="colorbox-background">
													<img src="/Admin/Public/GetImage.ashx?width=25&height=25&image=@image">
													<span class="visually-hidden">@facetOption.Label</span>
												</span>
											}
										</label>
									</div>
								}
								else
								{
									facetLabel = facetLabel.ToLower() == "true" ? facetLabel = Translate("Yes") : facetLabel;
									facetLabel = facetLabel.ToLower() == "false" ? facetLabel = Translate("No") : facetLabel;

									<label class="form-check mt-1" @disabled>
										<input type="checkbox" onclick="swift.ProductList.Update(event)" onkeydown="if(event.key==='Enter'){this.checked=!this.checked;swift.ProductList.Update(event);}" class="form-check-input" name="@facet.QueryParameter" value="@optionValue" data-filter-value="@facetLabel" @selected>
										<span class="form-check-label d-flex align-items-center">
											<span class="flex-fill">@facetLabel </span>
											@if (facet.FacetType.ToLower() == "field")
											{
												<small class="opacity-85">@facetOption.Count</small>
											}
										</span>
									</label>
								}
							}
						</div>
					</div>
				}

				groupCount++;
			}
		}
	}
}

@if ((groupCount > maxGroups) && layout == "horizontal")
{
	<button type="button" class="btn" onclick="this.closest('form').querySelectorAll('.js-facets-selector').forEach(function (selector) { selector.classList.remove('d-none'); }); this.classList.add('d-none');" tabindex="0"><span class="icon-2">@ReadFile(iconPath + "sliders.svg")</span> @Translate("All filters")</button>
}
<script>
	document.addEventListener('DOMContentLoaded', function () {
	  // Get all facet containers
	  const containers = document.querySelectorAll('[data-swift-facet-container]');

	  containers.forEach(container => {
		const input = container.querySelector('[data-swift-facet-filter-input]');
		const labels = container.querySelectorAll('.form-check');

		if (!input) return; // skip if no input found

		input.addEventListener('input', function () {
		  const filter = input.value.toLowerCase();
		  labels.forEach(label => {
			const text = label.textContent.toLowerCase();
			label.style.display = text.includes(filter) ? '' : 'none';
		  });
		});
	  });
	});
</script>