/**
 * Shop With Sidebar — price slider + AJAX filters (no full page reload).
 */
(function ($) {
	'use strict';

	var ajaxCfg =
		typeof window.WcommeroProShopSidebar === 'object' && window.WcommeroProShopSidebar
			? window.WcommeroProShopSidebar
			: {};

	function getCfg(id) {
		if (!window.WcommeroProShopSidebarCfg || !id) {
			return null;
		}
		return window.WcommeroProShopSidebarCfg[id] || null;
	}

	/**
	 * Resolve the correct Archive Grid elementId for a filter widget click.
	 *
	 * Filters and grids can be in different Elementor sections/columns, so if the
	 * filter's data-szp-element doesn't match a known config, we try:
	 *  1) nearest element with [data-szp-main]
	 *  2) first grid config (fallback)
	 *
	 * When resolved, update the closest `.szp-shop-sidebar` data-szp-element so
	 * syncSidebarActiveStates() can find the right filter links.
	 */
	function resolveElementIdForSource($source, explicitId) {
		var id = explicitId || ($source && $source.attr ? $source.attr('data-szp-element') : '') || '';
		var cfg = getCfg(id);
		if (cfg) {
			return { id: id, cfg: cfg };
		}

		// Try nearest main container inside the current Elementor area.
		var $root = $source && $source.closest ? $source.closest('.szp-shop-sidebar') : $();
		var $scope = $source && $source.closest
			? $source.closest('.elementor-section, .elementor-container, .elementor-column, .elementor-row')
			: $();
		if ($scope && $scope.length) {
			var $main = $scope.find('[data-szp-main]').first();
			if ($main && $main.length) {
				id = $main.attr('data-szp-main') || '';
				cfg = getCfg(id);
				if (cfg) {
					if ($root && $root.length) {
						$root.attr('data-szp-element', id);
					}
					return { id: id, cfg: cfg };
				}
			}
		}

		// Fallback: if only one grid exists, use it.
		var cfgObj = window.WcommeroProShopSidebarCfg;
		if (cfgObj && typeof cfgObj === 'object') {
			var keys = Object.keys(cfgObj);
			if (keys.length === 1) {
				id = keys[0];
				cfg = getCfg(id);
				if (cfg) {
					if ($root && $root.length) {
						$root.attr('data-szp-element', id);
					}
					return { id: id, cfg: cfg };
				}
			}
		}

		return { id: id, cfg: null };
	}

	function normalizeFilterArrays(f) {
		var out = $.extend(true, {}, f);
		var map = [
			['product_cat_slugs', 'product_cat_slug'],
			['color_slugs', 'color_slug'],
			['brand_slugs', 'brand_slug'],
			['attribute_slugs', 'attribute_slug'],
			['stock_states', 'stock_state'],
			['rating_values', 'rating_value'],
		];
		map.forEach(function (pair) {
			var plural = pair[0];
			var singular = pair[1];
			if (!Array.isArray(out[plural])) {
				out[plural] = [];
			}
			if (out[plural].length === 0 && out[singular]) {
				out[plural] = [String(out[singular])];
			}
			delete out[singular];
		});
		return out;
	}

	function ensureRuntimeFilters(cfg) {
		if (!cfg._runtimeFilters) {
			cfg._runtimeFilters = normalizeFilterArrays(cfg.initialFilters);
		}
		return cfg._runtimeFilters;
	}

	function syncSidebarActiveStates(elementId, filters) {
		var f = normalizeFilterArrays(filters);
		var $root = $('.szp-shop-sidebar[data-szp-element="' + elementId + '"]');
		$root.find('.szp-filter-link').each(function () {
			var $btn = $(this);
			var key = $btn.attr('data-szp-filter');
			var slug = $btn.attr('data-szp-slug') || '';
			var list = key && f[key] !== undefined && f[key] !== null ? f[key] : [];
			if (!Array.isArray(list)) {
				list = list ? [String(list)] : [];
			}
			var active = slug !== '' && list.indexOf(slug) !== -1;
			$btn.toggleClass('is-active', active).attr('aria-pressed', active ? 'true' : 'false');
		});
	}

	function storageViewKey(elementId) {
		return 'wcpShopView_' + elementId;
	}

	function setMainProductLayout(elementId, mode) {
		var $main = $('[data-szp-main="' + elementId + '"]');
		if (!$main.length || !$main.hasClass('szp-has-view-toggle')) {
			return;
		}
		mode = mode === 'list' ? 'list' : 'grid';
		$main
			.removeClass('szp-layout-grid szp-layout-list')
			.addClass(mode === 'list' ? 'szp-layout-list' : 'szp-layout-grid');
		var $btns = $main.find('.szp-grid-list .szp-view-btn');
		$btns.removeClass('active').attr('aria-pressed', 'false');
		$btns.filter('[data-szp-view="' + mode + '"]').addClass('active').attr('aria-pressed', 'true');
		try {
			if (window.localStorage) {
				localStorage.setItem(storageViewKey(elementId), mode);
			}
		} catch (e) {}
	}

	function applyStoredProductLayout(elementId) {
		var mode = 'grid';
		try {
			if (window.localStorage && localStorage.getItem(storageViewKey(elementId)) === 'list') {
				mode = 'list';
			}
		} catch (e) {}
		setMainProductLayout(elementId, mode);
	}

	function runAjax(elementId, filters) {
		var cfg = getCfg(elementId);
		if (!cfg || !ajaxCfg.ajaxUrl || !ajaxCfg.action) {
			return;
		}

		var $main = $('[data-szp-main="' + elementId + '"]');
		if (!$main.length) {
			return;
		}

		$main.addClass('szp-is-loading');

		$.ajax({
			url: ajaxCfg.ajaxUrl,
			type: 'POST',
			dataType: 'json',
			data: {
				action: ajaxCfg.action,
				nonce: ajaxCfg.nonce || '',
				element_id: elementId,
				page_url: cfg.pageUrl || window.location.href,
				settings: JSON.stringify(cfg.settings),
				filters: JSON.stringify(filters),
			},
		})
			.done(function (res) {
				if (!res || !res.success || !res.data || typeof res.data.html !== 'string') {
					return;
				}
				$main.replaceWith(res.data.html);
				cfg._runtimeFilters = $.extend(true, {}, filters);
				syncSidebarActiveStates(elementId, filters);
				applyStoredProductLayout(elementId);
			})
			.always(function () {
				$('[data-szp-main="' + elementId + '"]').removeClass('szp-is-loading');
			});
	}

	function applyFilterPatch(elementId, patch) {
		var cfg = getCfg(elementId);
		if (!cfg) {
			return;
		}
		var f = $.extend(true, {}, ensureRuntimeFilters(cfg), patch);
		runAjax(elementId, f);
	}

	function destroyPriceSlider($slider) {
		if ($slider && $slider.length && $slider.hasClass('ui-slider')) {
			try {
				$slider.slider('destroy');
			} catch (err) {
				$slider.removeClass('ui-slider ui-corner-all ui-slider-horizontal');
				$slider.empty();
			}
		}
	}

	function clampPriceRange(min, max, curMin, curMax) {
		if (max < min) {
			var t = min;
			min = max;
			max = t;
		}
		if (isNaN(curMin)) {
			curMin = min;
		}
		if (isNaN(curMax)) {
			curMax = max;
		}
		curMin = Math.min(Math.max(curMin, min), max);
		curMax = Math.min(Math.max(curMax, min), max);
		if (curMax < curMin) {
			var swap = curMin;
			curMin = curMax;
			curMax = swap;
		}
		return { min: min, max: max, curMin: curMin, curMax: curMax };
	}

	function applySliderValues($slider, $minIn, $maxIn, $out, curMin, curMax) {
		if (!$slider.hasClass('ui-slider')) {
			return;
		}
		$minIn.val(curMin);
		$maxIn.val(curMax);
		try {
			$slider.slider('option', 'values', [curMin, curMax]);
		} catch (e) {}
		if ($out.length) {
			$out.val('$' + curMin + ' - $' + curMax);
		}
	}

	function scheduleSliderLayoutFix($slider, $minIn, $maxIn, $out, curMin, curMax) {
		var run = function () {
			applySliderValues($slider, $minIn, $maxIn, $out, curMin, curMax);
		};
		run();
		if (window.requestAnimationFrame) {
			window.requestAnimationFrame(function () {
				window.requestAnimationFrame(run);
			});
		}
		setTimeout(run, 0);
		setTimeout(run, 50);
		setTimeout(run, 200);
		setTimeout(run, 600);
	}

	function initSliders() {
		if (typeof $.fn.slider !== 'function') {
			return;
		}
		$('.szp-shop-sidebar .price-filter-wrap').each(function () {
			var $wrap = $(this);
			var $slider = $wrap.find('.price-slider-range');
			if (!$slider.length) {
				return;
			}

			destroyPriceSlider($slider);

			var min = parseFloat($wrap.attr('data-min'));
			var max = parseFloat($wrap.attr('data-max'));
			if (isNaN(min)) {
				min = 0;
			}
			if (isNaN(max) || max <= min) {
				max = min + 1;
			}

			var $minIn = $wrap.find('input[name="min_price"]');
			var $maxIn = $wrap.find('input[name="max_price"]');
			var $out = $wrap.find('.szp-price-readout');

			var curMin = parseFloat($minIn.val());
			var curMax = parseFloat($maxIn.val());
			var r = clampPriceRange(min, max, curMin, curMax);
			curMin = r.curMin;
			curMax = r.curMax;

			$slider.slider({
				range: true,
				min: min,
				max: max,
				values: [curMin, curMax],
				slide: function (event, ui) {
					$minIn.val(ui.values[0]);
					$maxIn.val(ui.values[1]);
					if ($out.length) {
						$out.val('$' + ui.values[0] + ' - $' + ui.values[1]);
					}
				},
			});

			if ($out.length) {
				$out.val('$' + curMin + ' - $' + curMax);
			}

			scheduleSliderLayoutFix($slider, $minIn, $maxIn, $out, curMin, curMax);
		});
	}

	function refreshPriceSliderPositions() {
		if (typeof $.fn.slider !== 'function') {
			return;
		}
		$('.szp-shop-sidebar .price-filter-wrap').each(function () {
			var $wrap = $(this);
			var $slider = $wrap.find('.price-slider-range');
			if (!$slider.hasClass('ui-slider')) {
				return;
			}
			var min = parseFloat($wrap.attr('data-min'));
			var max = parseFloat($wrap.attr('data-max'));
			if (isNaN(min)) {
				min = 0;
			}
			if (isNaN(max) || max <= min) {
				max = min + 1;
			}
			var $minIn = $wrap.find('input[name="min_price"]');
			var $maxIn = $wrap.find('input[name="max_price"]');
			var $out = $wrap.find('.szp-price-readout');
			var curMin = parseFloat($minIn.val());
			var curMax = parseFloat($maxIn.val());
			var r = clampPriceRange(min, max, curMin, curMax);
			applySliderValues($slider, $minIn, $maxIn, $out, r.curMin, r.curMax);
		});
	}

	var wcpResizeTimer = null;
	$(window).on('resize orientationchange', function () {
		clearTimeout(wcpResizeTimer);
		wcpResizeTimer = setTimeout(refreshPriceSliderPositions, 150);
	});

	$(document).on('click', '.szp-view-btn', function (e) {
		e.preventDefault();
		var $btn = $(this);
		var mode = $btn.attr('data-szp-view');
		var id = $btn.closest('.szp-grid-list').attr('data-szp-element');
		if (!id || !mode) {
			return;
		}
		setMainProductLayout(id, mode);
	});

	$(document).on('click', '.szp-filter-link', function (e) {
		e.preventDefault();
		var $btn = $(this);
		var id = $btn.attr('data-szp-element');
		var key = $btn.attr('data-szp-filter');
		var slug = $btn.attr('data-szp-slug') || '';
		if (!id || !key) {
			return;
		}
		var pluralKeys = {
			product_cat_slugs: 1,
			color_slugs: 1,
			brand_slugs: 1,
			attribute_slugs: 1,
			stock_states: 1,
			rating_values: 1,
		};
		if (!pluralKeys[key]) {
			return;
		}
		var resolved = resolveElementIdForSource($btn, id);
		id = resolved.id;
		var cfg = resolved.cfg;
		if (!cfg) {
			return;
		}
		var multi = $btn.closest('.szp-shop-sidebar').attr('data-szp-multi') === '1';
		var f = normalizeFilterArrays($.extend(true, {}, ensureRuntimeFilters(cfg)));
		var list = Array.isArray(f[key]) ? f[key].slice() : [];
		var idx = slug !== '' ? list.indexOf(slug) : -1;
		if (multi) {
			if (idx >= 0) {
				list.splice(idx, 1);
			} else if (slug !== '') {
				list.push(slug);
			}
		} else {
			if (idx >= 0) {
				list = [];
			} else if (slug !== '') {
				list = [slug];
			}
		}
		f[key] = list;
		f.paged = 1;
		runAjax(id, f);
	});

	$(document).on('submit', '.szp-shop-sidebar .szp-price-filter-form', function (e) {
		e.preventDefault();
		var $form = $(this);
		var id = $form.attr('data-szp-element');
		if (!id) {
			return;
		}
		var resolved = resolveElementIdForSource($form, id);
		id = resolved.id;
		var cfg = resolved.cfg;
		if (!cfg) {
			return;
		}
		var min = parseFloat($form.find('input[name="min_price"]').val());
		var max = parseFloat($form.find('input[name="max_price"]').val());
		if (isNaN(min) || isNaN(max)) {
			return;
		}
		var f = $.extend(true, {}, ensureRuntimeFilters(cfg));
		f.min_price = min;
		f.max_price = max;
		f.paged = 1;
		runAjax(id, f);
	});

	$(document).on('submit', '.szp-shop-sidebar .szp-keyword-filter-form', function (e) {
		e.preventDefault();
		var $form = $(this);
		var id = $form.attr('data-szp-element');
		if (!id) {
			return;
		}
		var resolved = resolveElementIdForSource($form, id);
		id = resolved.id;
		var cfg = resolved.cfg;
		if (!cfg) {
			return;
		}
		var keyword = $.trim($form.find('.szp-keyword-input').val() || '');
		var f = $.extend(true, {}, ensureRuntimeFilters(cfg));
		f.keyword = keyword;
		f.paged = 1;
		runAjax(id, f);
	});

	$(document).on('change', '.szp-sort-select', function () {
		var $sel = $(this);
		var id = $sel.attr('data-szp-element');
		if (!id) {
			return;
		}
		var orderby = $sel.val() || '';
		applyFilterPatch(id, { orderby: orderby, paged: 1 });
	});

	$(document).on('click', '.szp-page-btn', function (e) {
		e.preventDefault();
		var $btn = $(this);
		var $pag = $btn.closest('.szp-pagination');
		var id = $pag.attr('data-szp-element');
		if (!id) {
			id = $btn.closest('[data-szp-main]').attr('data-szp-main');
		}
		if (!id) {
			return;
		}
		var page = parseInt($btn.attr('data-szp-page'), 10);
		if (isNaN(page) || page < 1) {
			return;
		}
		applyFilterPatch(id, { paged: page });
	});

	$(function () {
		initSliders();
		setTimeout(refreshPriceSliderPositions, 200);
		setTimeout(refreshPriceSliderPositions, 600);
		$('.szp-shop-sidebar__main.szp-has-view-toggle[data-szp-main]').each(function () {
			applyStoredProductLayout($(this).attr('data-szp-main'));
		});
	});
	$(window).on('load', function () {
		if ($('.szp-shop-sidebar .price-slider-range.ui-slider').length) {
			refreshPriceSliderPositions();
		} else {
			initSliders();
		}
	});
	$(window).on('elementor/frontend/init', function () {
		if (typeof window.elementorFrontend !== 'undefined' && elementorFrontend.hooks) {
			elementorFrontend.hooks.addAction(
				'frontend/element_ready/storzen-shop-sidebar.default',
				function () {
					initSliders();
					setTimeout(refreshPriceSliderPositions, 100);
					setTimeout(refreshPriceSliderPositions, 400);
					$('.szp-shop-sidebar__main.szp-has-view-toggle[data-szp-main]').each(function () {
						applyStoredProductLayout($(this).attr('data-szp-main'));
					});
				}
			);
			elementorFrontend.hooks.addAction(
				'frontend/element_ready/storzen-archive-grid.default',
				function () {
					initSliders();
					setTimeout(refreshPriceSliderPositions, 100);
					setTimeout(refreshPriceSliderPositions, 400);
					$('.szp-shop-sidebar__main.szp-has-view-toggle[data-szp-main]').each(function () {
						applyStoredProductLayout($(this).attr('data-szp-main'));
					});
				}
			);
			elementorFrontend.hooks.addAction(
				'frontend/element_ready/storzen-sidebar-filter.default',
				function () {
					initSliders();
					setTimeout(refreshPriceSliderPositions, 100);
					setTimeout(refreshPriceSliderPositions, 400);
					$('.szp-shop-sidebar__main.szp-has-view-toggle[data-szp-main]').each(function () {
						applyStoredProductLayout($(this).attr('data-szp-main'));
					});
				}
			);
		}
	});
})(jQuery);
