(function (root, $, factory) {
	var moduleName = 'PsActivityStream',
		moduleObject = factory(moduleName, $, peepso.ajax, peepso.observer, peepso.modules);

	// Run on document load.
	jQuery(function ($) {
		var $container = $('#ps-activitystream'),
			config,
			inst;

		if ($container.length) {
			config = (peepsodata && peepsodata.activity) || {};
			inst = new moduleObject($container[0], config);
		}
	});
})(window, jQuery, function (moduleName, $, ajax, observer, modules) {
	var LOAD_MORE_ENABLE = 1,
		LOAD_MORE_ENABLE_MOBILE = 2,
		LOAD_MORE_ENABLE_DESKTOP = 3;

	// Constants.
	var EVT_SCROLL = 'scroll.ps-activity-stream',
		IS_ADMIN = +peepsodata.is_admin,
		MY_ID = +peepsodata.currentuserid,
		USER_ID = +peepsodata.userid,
		POST_ID = $('#peepso_post_id').val() || undefined,
		CONTEXT = $('#peepso_context').val() || undefined,
		REVERSE_ORDER = +peepsodata.activity_reverse_order,
		// #8003 Whether the stream-type selector is remembered per-browser (admin option). Show-my-posts
		// and Sort-by always are; stream_id only when this is on.
		STREAM_ID_STICKY = +peepsodata.stream_id_sticky;

	// Handle browser resize event.
	(function (wrapper, observer) {
		if (!wrapper) {
			return;
		}

		function toggle() {
			if (wrapper.clientWidth < 700) {
				wrapper.classList.add('ps-activity--narrow');
			} else {
				wrapper.classList.remove('ps-activity--narrow');
			}
		}

		toggle();
		observer.addAction('browser.resize', toggle);
	})(document.querySelector('.ps-activity'), observer);

	return peepso.createClass(moduleName, {
		/**
		 * Class constructor.
		 * @param {Element} container
		 */
		__constructor: function (container, config) {
			this.$el = $(container);
			this.$recent = $('#ps-activitystream-recent');
			this.$loading = $('#ps-activitystream-loading');
			this.$noPosts = $('#ps-no-posts');
			this.$noPostsMatch = $('#ps-no-posts-match');
			this.$noMorePosts = $('#ps-no-more-posts');
			this.$filters = $('.ps-js-activitystream-filter');
			this.$filtersToggle = $('.ps-js-activitystream-filters-toggle');
			this.$filtersWrapper = $('.ps-js-activitystream-filters-wrapper');
			this.$filtersActive = this.$filtersWrapper
				.parent('[data-ps=filter-forms]')
				.next('[data-ps=filter-active]');

			this.loading = false;
			this.loadEnd = false;
			this.loadPage = 1;
			this.loadIds = [];
			this.loadLimit = +peepsodata.activity_limit_below_fold;

			// Set loadmore button availability.
			var lmEnable = +peepsodata.loadmore_enable;
			if (peepso.isMobile()) {
				lmEnable = lmEnable === LOAD_MORE_ENABLE || lmEnable === LOAD_MORE_ENABLE_MOBILE;
			} else {
				lmEnable = lmEnable === LOAD_MORE_ENABLE || lmEnable === LOAD_MORE_ENABLE_DESKTOP;
			}

			this.loadButtonEnabled = lmEnable;
			this.loadButtonRepeat = this.loadButtonEnabled ? +peepsodata.loadmore_repeat : 0;
			this.loadButtonTemplate = config.template_load_more;

			this.isPermalink = +config.is_permalink;
			this.hideFromGuest = +config.hide_from_guest;

			// Normalize load limit.
			this.loadLimit = this.loadLimit > 0 ? this.loadLimit : 3;

			// Flag to apply activity filter.
			$.proxy(function (hashValue) {
				let $filter = this.$filters.filter('[data-id=peepso_stream_id]');

				if (hashValue) {
					hashValue = 'core_' + hashValue;
					let $hidden = $('[id=peepso_stream_id]');
					let $option = $filter.find(`[data-option-value="${hashValue}"]`);
					let $toggle = $filter.find('.ps-js-dropdown-toggle');

					if ($hidden.val() !== hashValue && $option.length) {
						// Update filter data.
						$hidden.val(hashValue);

						// Update button toggle label + icon (the icon is what shows in compact/mobile mode).
						$toggle.find('span').text($option.find('span').text());
						$toggle
							.find('.ps-js-icon')
							.attr('class', $option.find('.ps-js-icon').attr('class'));
					}
				}

				// Trigger filter on hashchange.
				window.addEventListener('hashchange', e => {
					let hashValue = 'core_' + window.location.hash.slice(1);
					let $option = $filter.find(`[data-option-value="${hashValue}"]`);

					if ($option.length) {
						let $radio = $option.find('[type=radio]');
						if ($radio.length) {
							$filter.find('[type=radio]').prop('checked', false);
							$radio[0].checked = true;
							this.commitFilter($filter);
						}
					}
				});
			}, this)(window.location.hash.slice(1));

			// Stream notice.
			this.$filterNotice = $('[data-ps=filter-warning]');
			if (this.$filterNotice.length) {
				this.$filterNotice.data('html', this.$filterNotice.html().trim());
			}

			// #8046 Inline "your posts are hidden" warning (shown by reset() while hide_mine is
			// active). Cached here; its click binding sits with the other filter handlers below.
			this.$myPostsNotice = $('[data-ps=myposts-warning]');

			// Stream notice label mapper.
			this.filterNoticeMap = {};
			this.$filters
				.filter('[data-id=peepso_stream_id]')
				.find('[data-option-value]')
				.each(
					$.proxy(function (index, opt) {
						var $opt = $(opt),
							key = $opt.data('option-value'),
							label = $opt.data('option-label-warning');

						this.filterNoticeMap[key] = label;
					}, this)
				);

			// Get activitystream hidden input data.
			this.streamData = {};
			$('[type=hidden][id^=peepso_stream_]').each((index, input) => {
				var name = input.id.replace(/^peepso_/, ''),
					value = input.value;

				this.streamData[name] = value;

				// Toggle "hide my posts" filter.
				if (name === 'stream_id') {
					if (!IS_ADMIN && value === 'core_scheduled') {
						this.allowHideMyPosts(false);
					} else {
						this.allowHideMyPosts(true);
					}
				}
			});

			// #8037 Per-family last-used child memory, persisted per-browser (peepso.localStorage) so it
			// survives reloads. The active family+child already round-trip via user-meta; this remembers
			// the OTHER families' last-used child. Load the stored map, then overlay the server-restored
			// active leaf (authoritative — may have been set on another device), and persist the reconciled
			// map. applySortFamily() consults this before falling back to a family's default.
			this.sortVariantMemory = {};
			try {
				var _mem = peepso.localStorage && peepso.localStorage.get('stream_sort_variants_' + MY_ID);
				var _parsed = _mem ? JSON.parse(_mem) : null;
				if (_parsed && typeof _parsed === 'object') {
					this.sortVariantMemory = _parsed;
				}
			} catch (e) {}
			if (this.streamData['stream_filter_sort_group'] && this.streamData['stream_filter_sort_by']) {
				this.sortVariantMemory[this.streamData['stream_filter_sort_group']] = this.streamData['stream_filter_sort_by'];
			}
			this._saveSortMemory();

			// #8003 Overlay this browser's stored filters onto streamData + the controls, BEFORE the
			// first load below, so both the query and the UI reflect them from any context. Runs after
			// sortVariantMemory is loaded (it seeds the family's remembered variant).
			this._restoreStreamFilters();

			// Toggle active class when filter dropdown is expanded/collapsed.
			this.$filters
				.on('ps-dropdown.show', e => $(e.currentTarget).addClass('pso-posts__filter--open'))
				.on('ps-dropdown.hide', e =>
					$(e.currentTarget).removeClass('pso-posts__filter--open')
				);

			// Hide loading if login popup is visible.
			$(document).on('peepso_login_shown', () => this.$loading.hide());

			// Handle activitystream filtering.
			this.$filters.on('click', '.ps-js-dropdown-toggle', $.proxy(this.onFilterToggle, this));
			this.$filters.on('click', '[data-option-value]', $.proxy(this.onFilterSelect, this));
			this.$filters.on('click', '.pso-posts-filter__option--checkbox', $.proxy(this.onFilterMyPosts, this));
			this.$filters.on('click', '.ps-js-cancel', $.proxy(this.onFilterCancel, this));
			this.$filters.on('click', '[type=text]', $.proxy(this.onFilterFocus, this));
			this.$filters.on('keyup', '[type=text]', $.proxy(this.onFilterKeyup, this));
			this.$filters.on('click', '.ps-js-search', $.proxy(this.onFilterSearch, this));
			this.$filtersToggle.on('click', $.proxy(this.onFiltersToggle, this));

			// #8046 Tapping the "your posts are hidden" banner (or Enter/Space on it — it's a
			// role=button) re-enables "show my posts". Bound directly: it sits outside this.$filters.
			this.$myPostsNotice.on('click', $.proxy(this.onMyPostsWarningClick, this));
			this.$myPostsNotice.on('keydown', $.proxy(function (e) {
				if (e.key === 'Enter' || e.key === ' ' || e.which === 13 || e.which === 32) {
					this.onMyPostsWarningClick(e);
				}
			}, this));

			// Flag to load everything.
			this.loadEverything = window.location.hash === '#everything';
			if (this.loadEverything) {
				if (!confirm('Are you sure want to load every post?')) {
					this.loadEverything = false;
				}
			}

			// Adds `peepso_remote_no_cache` parameter to the activitystream's request
			// if present in the URL.
			peepso.observer.addFilter('show_more_posts', params => {
				let searchParams = window.location.search || '';
				if (searchParams.match('peepso_remote_no_cache')) {
					params.peepso_remote_no_cache = 1;
				}

				return params;
			});

			// Initiate infinite load.
			var $search = $('#ps-activitystream-search');
			this.search($search.eq(0).val());

			// Listen to `peepso_stream_reset` actions.
			peepso.observer.addAction('peepso_stream_reset', () => {
				this.search($search.eq(0).val());
			});

			// Do not show `post_saved_notice` on saved stream.
			peepso.observer.addFilter(
				'post_saved_notice',
				$.proxy(function (notice) {
					if ('core_saved' === this.streamData['stream_id']) {
						notice = false;
					}
					return notice;
				}, this),
				10,
				1
			);

			// this._token = ( new Date ).getTime();
			// this.autoload( this._token );
		},

		/**
		 * Search activities based on keyword.
		 *
		 * @param {string} keyword
		 * @param {string} mode
		 */
		search: function (keyword, mode) {
			keyword = (keyword || '').trim();
			this.searchKeyword = keyword;
			this.searchMode = mode || this.searchMode || 'exact';
			this.reset();

			// Update label.
			const $label = this.$filtersActive.find('[data-ps=filter-active-search]');

			if (!keyword) {
				$label.hide().find('[data-text]').empty();
			} else {
				$label.show().find('[data-text]').html(keyword);
				$label
					.find('[data-remove]')
					.off('click')
					.one('click', e => {
						e.preventDefault();

						// Select exact mode if keyword is empty.
						const $dropdown = this.$filters.filter('[data-id=peepso_search]');
						$dropdown.find('[type=radio]').get(0).checked = true;
						$(`#${$dropdown.data('id')}`).val('exact');

						this.search('', 'exact');
						$('#ps-activitystream-search').val('');
					});
			}
		},

		/**
		 * Start infinite load.
		 * @param {number} token
		 */
		autoload: function (token) {
			if (token !== this._token) {
				return;
			}

			if (this.loading) {
				return;
			}

			if (peepso.hooks.applyFilters('activitystream_disable_scroll', false)) {
				return;
			}

			// Check if guest should be able to see the activities.
			if (!MY_ID && this.hideFromGuest) {
				this.$loading.hide();
				return false;
			}

			if (this.shouldLoad()) {
				this.loading = true;
				this.load(token).done(
					$.proxy(function () {
						this.loading = false;
						if (!this.isPermalink && !this.loadEnd) {
							this.autoload(token);
						}
					}, this)
				);
			} else if (this.loadButtonEnabled && !this.$loadButton) {
				this.$loadButton = $(this.loadButtonTemplate).insertAfter(this.$el);
				this.$loadButton.one(
					'click',
					$.proxy(function (e) {
						$(e.currentTarget).remove();
						this.autoload(token);
					}, this)
				);
			} else if (!this._onScrollEnabled) {
				var scrollableContainer = peepso.observer.applyFilters(
					'activitystream_scrollable_container',
					window
				);

				this._onScrollEnabled = true;
				$(scrollableContainer).on(EVT_SCROLL, token, $.proxy(this.onScroll, this));
			}
		},

		/**
		 * Check whether stream should load next activities.
		 * @return {boolean}
		 */
		shouldLoad: function () {
			var $activities = this.$el.children('.ps-js-activity'),
				$last,
				limit,
				position,
				winHeight;

			// Do not try to load next activity if all activities is already loaded.
			if (this.loadEnd) {
				return false;
			}

			// Try to load next activities on empty stream.
			if (!$activities.length) {
				return true;
			}

			// Respect loadEverything flag.
			if (this.loadEverything) {
				return true;
			}

			// Handle fixed-number batch load of activities.
			if (this.loadButtonEnabled && this.loadButtonRepeat) {
				if ($activities.length % this.loadButtonRepeat === 0) {
					if (this.$loadButton) {
						delete this.$loadButton;
						return true;
					} else {
						return false;
					}
				} else {
					return true;
				}
			}

			// Get the first of the last N activities where N is decided by limit value.
			$last = $activities.slice(0 - this.loadLimit).eq(0);
			if (!$last.length) {
				return false;
			}

			// Calculate element from viewport, or from top of the document if trigger button
			// is enabled.
			if (this.loadButtonEnabled && !this.$loadButton) {
				position = $last.eq(0).offset();
			} else {
				position = $last[0].getBoundingClientRect();
			}

			// Load next activities if `$last` is still inside the viewport.
			winHeight = window.innerHeight || document.documentElement.clientHeight;
			if (position.top < winHeight) {
				return true;
			}

			return false;
		},

		/**
		 * Load next activities in the current stream.
		 * @param {number} token
		 * @return {jQuery.Deferred}
		 */
		load: function (token) {
			var that = this;

			var params = _.extend(
				{
					uid: MY_ID,
					user_id: USER_ID,
					post_id: POST_ID,
					context: CONTEXT,
					page: this.loadPage,

					// Search query.
					search: this.searchKeyword || undefined,
					search_mode: (this.searchKeyword && this.searchMode) || undefined,

					// Also get pinned posts on first page.
					pinned: this.loadPage === 1 ? 1 : undefined
				},
				this.streamData || {}
			);

			// Execute filter hooks.
			params = peepso.observer.applyFilters('show_more_posts', params);

			return $.Deferred(function (defer) {
				that.$loading.show();

				ajax.post('activity.show_posts_per_page', params).done(function (json) {
					// Discard if token not match.
					if (token !== that._token) {
						return;
					}

					that.$loading.hide();

					if (json.data.post_count > 0) {
						var id = +json.data.act_id;
						if (!id) {
							that.render(json.data.posts);
						}
						// Do not print duplicate post.
						else if (that.loadIds.indexOf(id) === -1) {
							that.loadIds.push(id);
							that.render(json.data.posts);
						}
						that.loadPage++;
					} else {
						that.loadEnd = true;
					}

					if (that.loadEnd) {
						if (params.page > 1) {
							var pendingHtml = peepso.observer.applyFilters(
								'activitystream_pending_html',
								''
							);
							if (pendingHtml) {
								that.render(pendingHtml);
							}
							that.$noMorePosts.show();
						} else if (that.searchKeyword) {
							that.$noPostsMatch.show();
						} else {
							that.$noPosts.show();
						}
					}

					defer.resolve();
				});
			});
		},

		/**
		 * Reset activitystream.
		 */
		reset: function () {
			this.loading = false;
			this.loadEnd = false;
			this.loadPage = 1;
			this.loadIds = [];

			// Disable scroll event.
			var scrollableContainer = peepso.observer.applyFilters(
				'activitystream_scrollable_container',
				window
			);

			this._onScrollEnabled = false;
			$(scrollableContainer).off(EVT_SCROLL);

			// Remove load more button.
			if (this.$loadButton) {
				this.$loadButton.remove();
				this.$loadButton = undefined;
			}

			// Reset view.
			this.$el.empty().hide();
			this.$recent.empty();
			this.$noMorePosts.hide();
			this.$noPosts.hide();
			this.$noPostsMatch.hide();

			// Show stream notice if needed.
			var hasNotice = this.filterNoticeMap[this.streamData['stream_id']];
			if (!hasNotice) {
				this.$filterNotice.hide();
			} else {
				this.$filterNotice.html(this.$filterNotice.data('html').replace('%s', hasNotice));
				this.$filterNotice.show();
			}

			// #8046 Toggle the "your posts are hidden" warning. Explicit inline display; a no-op when
			// the banner is absent (guests / contexts without the my-posts control).
			this.$myPostsNotice.css(
				'display',
				this.streamData['stream_filter_show_my_posts'] === 'hide_mine' ? 'block' : 'none'
			);

			// Restart autoload.
			this._token = new Date().getTime();
			this.autoload(this._token);

			this.updateFilterIcons();
		},

		/**
		 * Render activities into the stream.
		 * @param {string} html
		 */
		render: function (html) {
			// Manually fix problem with WP Embed as described here:
			// https://core.trac.wordpress.org/ticket/34971
			html = html.replace(/\/embed\/(#\?secret=[a-zA-Z0-9]+)*"/g, '/?embed=true$1"');

			// #5206 Add an extra identifier for WP Embed loaded in the activity stream.
			html = html.replace(/\/\?embed=true([#"])/g, '/?embed=true&peepso=1$1');

			var $posts = $(html),
				query = this.searchKeyword,
				mode = this.searchMode,
				highlight;

			// Filter posts.
			$posts = peepso.observer.applyFilters('peepso_activity', $posts);

			// Filter contents.
			$posts
				.find('.ps-js-activity-content, .ps-js-activity-quote, .ps-comment-item')
				.each(function () {
					var $post = $(this),
						html = $post.html();

					html = peepso.observer.applyFilters('peepso_activity_content', html);
					$post.html(html);
				});

			// Highlight contents if keywords are set.
			if (query) {
				highlight = '<span class="ps-text--highlight">$1</span>';
				$posts.find('.ps-js-activity-content').each(function () {
					var $post = $(this),
						html = $post.html(),
						reQuery = [query];

					if (mode === 'any') {
						reQuery = _.filter(query.split(' '), function (str) {
							return str;
						});
					}

					// Escape string to be used in regex.
					// https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
					reQuery = _.map(reQuery, function (str) {
						return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
					});

					reQuery = RegExp('(' + reQuery.join('|') + ')(?![^<>]+>)', 'ig');
					html = html.replace(reQuery, highlight);
					$post.html(html);
				});
			}

			// Show container if its not already visible.
			if (this.$el.is(':hidden')) {
				this.$el.show();
			}

			// Safely append elements into container as some of them might raise error when added
			// to the document tree, thus breaks the autoload process.
			try {
				if (REVERSE_ORDER) {
					let $latestPosts = this.$el.children('.ps-js-activity-latest');

					if ($latestPosts.length) {
						// Filter-out already added posts.
						let latestPostIds = $.makeArray($latestPosts).map(el => +$(el).data('id'));
						$posts = $posts.map((i, el) => {
							return latestPostIds.indexOf(+$(el).data('id')) > -1 ? null : el;
						});

						$posts.insertBefore($latestPosts.first());
					} else {
						$posts.appendTo(this.$el);
					}
				} else {
					$posts.appendTo(this.$el);
				}

				$posts.each(function () {
					peepso.hooks.doAction('post_added', this);
				});
			} catch (e) {}

			$posts.hide().fadeIn(1000, function () {
				$(document).trigger('ps_activitystream_loaded');

				peepso.observer.doAction('post_loaded', this);

				// Fix Instagram embed issue.
				if (html.match(/\sdata-instgrm-permalink/)) {
					setTimeout(function () {
						try {
							window.instgrm.Embeds.process();
						} catch (e) {}
					}, 1000);
				}
			});
		},

		/**
		 * Enable/disable "hide my posts" dropdown filter.
		 *
		 * @param {boolean} allow
		 */
		allowHideMyPosts: function (allow) {
			// #8037 "Show my posts" is now a checkbox (embedded in the Filter dropdown, or
			// standalone). Non-admins on the "scheduled" stream can't hide their own posts: force
			// "show my posts" (checkbox ticked) and hide the checkbox row.
			var $row = this.$filters.find('[data-myposts]'),
				$checkbox = $row.find('[type=checkbox]');

			if (!$checkbox.length) {
				return;
			}

			if (allow) {
				$row.show();
				return;
			}

			$checkbox.prop('checked', true);
			$('#peepso_stream_filter_show_my_posts').val('show_mine');
			this.streamData['stream_filter_show_my_posts'] = 'show_mine';
			$row.hide();
		},

		/**
		 * Update filter icons based on the selected filters.
		 */
		updateFilterIcons: function () {
			var $toggle = this.$filtersToggle.children('span').empty();
			var $inputs = this.$filtersWrapper.children('input[type=hidden]');

			$inputs.each(function () {
				var $input = $(this);
				var $div = $input.next(`[data-id="${this.id}"]`);
				var $divToggle = $div.children('.ps-js-dropdown-toggle');
				var $selected = $div.find(`[data-option-value="${this.value}"]`);
				var $selectedIcon = $selected.find('.ps-js-icon');

				// #8037 static icons: don't swap the toggle icon to the selected one (reversible).
				// $divToggle.find('.ps-js-icon').replaceWith($selectedIcon.clone());
				$toggle.append($selectedIcon.clone());
			});

			// Toggle active filters visibility.
			peepso.hooks.doAction('activitystream_update_filter_active');
			requestAnimationFrame(() => {
				const chilren = this.$filtersActive.children().toArray();
				const visibleChildren = chilren.filter(el => {
					return getComputedStyle(el).display !== 'none';
				});

				visibleChildren.length ? this.$filtersActive.show() : this.$filtersActive.hide();
			});
		},

		/**
		 * Handle document scroll event.
		 * @param {Event} e
		 */
		onScroll: _.throttle(function (e) {
			var token = e.data;
			this.autoload(token);
		}, 1),

		/**
		 * Handle toggle filter activitystream dropdowns.
		 * @param {Event} e
		 */
		onFilterToggle: _.debounce(function (e) {
			var $toggle = $(e.currentTarget),
				$dropdown = $toggle.closest('.ps-js-activitystream-filter'),
				$menu = $dropdown.find('.ps-js-dropdown-menu'),
				data = $dropdown.data('id').replace(/^peepso_/, ''),
				value = this.streamData[data],
				$radio;

			if ($dropdown.is(':visible')) {
				$radio = $dropdown.find('[type=radio]').filter('[value="' + value + '"]');
				if ($radio.length) {
					$radio[0].checked = true;
				}

				// #8037 re-sync the "Show my posts" checkbox to the last-applied value, so opening
				// (or an outside-click close then reopen) always shows the committed state.
				var $checkbox = $dropdown.find('[data-myposts] [type=checkbox]');
				if ($checkbox.length) {
					$checkbox[0].checked = ('hide_mine' !== this.streamData['stream_filter_show_my_posts']);
				}
			}
		}, 1),

		/**
		 * Handle select filter activitystream dropdowns.
		 * @param {Event} e
		 */
		onFilterSelect: function (e) {
			var $option = $(e.currentTarget),
				$dropdown = $option.closest('.ps-js-activitystream-filter'),
				$radio = $option.find('[type=radio]');

			e.preventDefault();

			// #8037 The search dropdown keeps its explicit Search button (it also holds a text field
			// + match mode), so tapping a mode there only selects it — it must not auto-apply or close.
			// Every other filter now commits on tap (the Apply button is gone).
			if ($dropdown.find('.ps-js-search').length) {
				e.stopPropagation();
				_.defer(function () {
					$radio[0].checked = true;
				});
				return;
			}

			// Apply-on-tap: select this option and commit immediately. We do NOT stopPropagation, so
			// the same click bubbles to document and dropdown.js closes the menu (as Apply used to).
			if ($radio.length) {
				$dropdown.find('[type=radio]').prop('checked', false);
				$radio.prop('checked', true);
			}
			this.commitFilter($dropdown);
		},

		/**
		 * #8037 Toggle the "Show my posts" checkbox and commit immediately — it shares the
		 * apply-on-tap mechanic (the Apply button is gone). The click is allowed to bubble so
		 * dropdown.js's document handler closes the menu.
		 *
		 * A click that lands directly on the native <input type=checkbox> is a special case: the
		 * browser has ALREADY toggled its checkedness (pre-click activation) by the time this
		 * delegated handler runs, and preventDefault() would REVERT that toggle *after* the handler
		 * returns. Flipping it again here would then cancel out, so the row appears to do nothing —
		 * this was the intermittent "clicking exactly on the checkbox changes nothing" bug. So for a
		 * direct hit we let the native toggle stand and just commit it. For a click anywhere else on
		 * the row (label / padding) nothing native has toggled, so we flip manually and
		 * preventDefault() to stop the label's `for=` synthetic checkbox click from re-firing this
		 * handler.
		 * @param {Event} e
		 */
		onFilterMyPosts: function (e) {
			var $option = $(e.currentTarget),
				$checkbox = $option.find('[type=checkbox]');

			if (e.target !== $checkbox[0]) {
				e.preventDefault();
				$checkbox.prop('checked', !$checkbox.prop('checked'));
			}

			this.commitFilter($option.closest('.ps-js-activitystream-filter'));
		},

		/**
		 * #8046 Handle a tap (or Enter/Space) on the "your posts are hidden" banner: re-enable
		 * "show my posts" directly and reload. Mirror the value into the Filter dropdown's checkbox +
		 * hidden input so every control agrees, persist it, then reset() — which hides the banner.
		 * @param {Event} e
		 */
		onMyPostsWarningClick: function (e) {
			e.preventDefault();

			this.streamData['stream_filter_show_my_posts'] = 'show_mine';
			$('#peepso_stream_filter_show_my_posts').val('show_mine');
			this.$filters.find('[data-myposts] [type=checkbox]').prop('checked', true);

			this._saveStreamFilters();
			this.reset();
		},

		/**
		 * Handle cancel activitystream filter.
		 * @param {Event} e
		 */
		onFilterCancel: function (e) {
			var $button = $(e.currentTarget),
				$dropdown = $button.closest('.ps-js-activitystream-filter'),
				$toggle = $dropdown.find('.ps-js-dropdown-toggle'),
				data = $dropdown.data('id').replace(/^peepso_/, ''),
				applied = this.streamData[data];

			// #8037 Cancel = discard unapplied changes: restore this dropdown's controls to the
			// last-applied state. Only touch radios when we have a tracked value (skips the search
			// dropdown, whose mode lives in searchMode, not streamData).
			if (typeof applied !== 'undefined') {
				var $radio = $dropdown.find('[type=radio][value="' + applied + '"]');
				if ($radio.length) {
					$dropdown.find('[type=radio]').prop('checked', false);
					$radio.prop('checked', true);
				}
			}

			var $checkbox = $dropdown.find('[data-myposts] [type=checkbox]');
			if ($checkbox.length) {
				$checkbox.prop('checked', 'hide_mine' !== this.streamData['stream_filter_show_my_posts']);
			}

			$toggle.focus();
		},

		/**
		 * #8037 Commit a filter dropdown's current selection: sync the hidden input + streamData,
		 * update the toggle label/icon, run the sort family/variant + "show my posts" side-effects,
		 * and reload the stream. Called on option tap / checkbox toggle (apply-on-tap) and on
		 * hashchange — there is no longer an Apply button.
		 * @param {jQuery} $dropdown  The .ps-js-activitystream-filter being committed.
		 */
		commitFilter: function ($dropdown) {
			var $toggle = $dropdown.find('.ps-js-dropdown-toggle'),
				$option = $dropdown.find('[type=radio]:checked').closest('[data-option-value]'),
				value = $option.data('optionValue'),
				data = $dropdown.data('id').replace(/^peepso_/, '');

			// Radio-based filters (stream_id, sort family/variant). Skipped for the checkbox-only
			// "Filter" dropdown, which carries no radio.
			if ($option.length) {
				// Update filter data.
				$('#' + $dropdown.data('id')).val(value);
				this.streamData[data] = value;

				// #8037 remember this variant as its family's last-used child (session only), so
				// switching away and back to the family restores it instead of resetting to default.
				if (data === 'stream_filter_sort_by') {
					var grp = $option.data('group');
					if (grp) {
						this.sortVariantMemory[grp] = value;
						this._saveSortMemory();
					}
				}

				// Update button toggle label + icon (the icon is what shows in compact/mobile mode).
				$toggle.find('span').text($option.find('span').text());
				$toggle.find('.ps-js-icon').attr('class', $option.find('.ps-js-icon').attr('class'));
			}

			$toggle.focus();

			// #8037 "Show my posts" checkbox (embedded in the Filter dropdown, or standalone).
			var $myposts = $dropdown.find('[data-myposts] [type=checkbox]');
			if ($myposts.length) {
				var mpValue = $myposts.is(':checked') ? 'show_mine' : 'hide_mine';
				$('#peepso_stream_filter_show_my_posts').val(mpValue);
				this.streamData['stream_filter_show_my_posts'] = mpValue;
			}

			// Toggle "hide my posts" availability.
			if (data === 'stream_id') {
				if (!IS_ADMIN && value === 'core_scheduled') {
					this.allowHideMyPosts(false);
				} else {
					this.allowHideMyPosts(true);
				}
			}

			// #8037 family picker: repopulate the variant sub-picker for the chosen family.
			if (data === 'stream_filter_sort_group') {
				this.applySortFamily(value);
			}

			// #8003 Persist the committed filters per-browser (localStorage), so they stick on reload
			// from any context. Runs after the sort family/variant side-effects have settled streamData.
			this._saveStreamFilters();

			// Reset activitystream.
			this.reset();
		},

		/**
		 * #8037 Persist the per-family last-used child map to browser-local storage (peepso.localStorage,
		 * per-user key). Guarded — a no-op if storage is unavailable (private mode / older browser), so the
		 * picker degrades to session-only memory. Called after every mutation of this.sortVariantMemory.
		 */
		_saveSortMemory: function () {
			try {
				if (peepso.localStorage) {
					peepso.localStorage.set('stream_sort_variants_' + MY_ID, JSON.stringify(this.sortVariantMemory));
				}
			} catch (e) {}
		},

		/**
		 * #8003 Persist the active stream filters per-browser (peepso.localStorage, per-user key) so they
		 * survive reloads on THIS browser without leaking cross-device (or into the RN WebView app). This
		 * replaces the old server-side user-meta persistence. show-my-posts and sort-by/group always
		 * persist; stream_id only when the admin sticky option is on. Guarded — a no-op if storage is
		 * unavailable (private mode / older browser). Called from commitFilter after streamData settles.
		 */
		_saveStreamFilters: function () {
			try {
				if (!peepso.localStorage) {
					return;
				}
				// Merge onto the existing blob and only write keys we actually hold, so saving from a
				// context that lacks a control (e.g. no stream-type selector on profile/group/page, or
				// no filters at all on a single-post view) never erases the other stored filters.
				var data = {};
				try {
					var raw = peepso.localStorage.get('stream_filters_' + MY_ID);
					var prev = raw ? JSON.parse(raw) : null;
					if (prev && typeof prev === 'object') {
						data = prev;
					}
				} catch (e) {}

				var sd = this.streamData || {};
				if (typeof sd['stream_filter_show_my_posts'] !== 'undefined') {
					data.show_my_posts = sd['stream_filter_show_my_posts'];
				}
				if (typeof sd['stream_filter_sort_by'] !== 'undefined') {
					data.sort_by = sd['stream_filter_sort_by'];
				}
				if (typeof sd['stream_filter_sort_group'] !== 'undefined') {
					data.sort_group = sd['stream_filter_sort_group'];
				}
				if (STREAM_ID_STICKY && typeof sd['stream_id'] !== 'undefined') {
					data.stream_id = sd['stream_id'];
				}

				peepso.localStorage.set('stream_filters_' + MY_ID, JSON.stringify(data));
			} catch (e) {}
		},

		/**
		 * #8003 Overlay this browser's stored filters (written by _saveStreamFilters) onto streamData, the
		 * hidden inputs and the dropdown controls — BEFORE the first load — so the query params and the UI
		 * both reflect the stored state from ANY context (this is what fixes profile/group/page not
		 * remembering). stream_id is only restored when the admin sticky option is on and its dropdown is
		 * present (main stream). Reuses applySortFamily for the sort variant side. Storage-guarded.
		 */
		_restoreStreamFilters: function () {
			var stored;
			try {
				var raw = peepso.localStorage && peepso.localStorage.get('stream_filters_' + MY_ID);
				stored = raw ? JSON.parse(raw) : null;
			} catch (e) {
				stored = null;
			}
			if (!stored || typeof stored !== 'object') {
				return;
			}

			// Show my posts (checkbox). Only when the row exists (absent for guests / scheduled stream).
			var $myposts = this.$filters.find('[data-myposts] [type=checkbox]');
			if ($myposts.length && (stored.show_my_posts === 'show_mine' || stored.show_my_posts === 'hide_mine')) {
				this.streamData['stream_filter_show_my_posts'] = stored.show_my_posts;
				$('#peepso_stream_filter_show_my_posts').val(stored.show_my_posts);
				$myposts.prop('checked', stored.show_my_posts !== 'hide_mine');
			}

			// Sort family + variant. Seed the family's remembered variant so applySortFamily picks it,
			// sync the family control here, then let applySortFamily handle the variant sub-picker.
			var $family = this.$filters.filter('[data-id=peepso_stream_filter_sort_group]');
			if ($family.length && stored.sort_group) {
				var $fopt = $family.find('[data-option-value="' + stored.sort_group + '"]');
				if ($fopt.length) {
					this.streamData['stream_filter_sort_group'] = stored.sort_group;
					$('#peepso_stream_filter_sort_group').val(stored.sort_group);
					$family.find('[type=radio]').prop('checked', false);
					$fopt.find('[type=radio]').prop('checked', true);
					var $ftoggle = $family.find('.ps-js-dropdown-toggle');
					$ftoggle.find('span').text($fopt.find('span').text());
					$ftoggle.find('.ps-js-icon').attr('class', $fopt.find('.ps-js-icon').attr('class'));

					if (stored.sort_by) {
						this.sortVariantMemory[stored.sort_group] = stored.sort_by;
					}
					this.applySortFamily(stored.sort_group);
				}
			}

			// Stream type: only when sticky is enabled and the selector is present (main stream).
			var $stream = this.$filters.filter('[data-id=peepso_stream_id]');
			if (STREAM_ID_STICKY && $stream.length && stored.stream_id) {
				var $sopt = $stream.find('[data-option-value="' + stored.stream_id + '"]');
				if ($sopt.length) {
					this.streamData['stream_id'] = stored.stream_id;
					$('#peepso_stream_id').val(stored.stream_id);
					$stream.find('[type=radio]').prop('checked', false);
					$sopt.find('[type=radio]').prop('checked', true);
					var $stoggle = $stream.find('.ps-js-dropdown-toggle');
					$stoggle.find('span').text($sopt.find('span').text());
					$stoggle.find('.ps-js-icon').attr('class', $sopt.find('.ps-js-icon').attr('class'));

					// Re-evaluate "hide my posts" availability for the restored stream (e.g. scheduled).
					if (!IS_ADMIN && stored.stream_id === 'core_scheduled') {
						this.allowHideMyPosts(false);
					} else {
						this.allowHideMyPosts(true);
					}
				}
			}
		},

		/**
		 * #8037 Repopulate the variant (sub) sort dropdown for the selected family: show only
		 * that family's options, select the family's default (first) variant, sync the hidden
		 * input / streamData / toggle, and hide the whole sub-picker when it has a single option.
		 * @param {string} family
		 */
		applySortFamily: function (family) {
			var $variant = this.$filters.filter('[data-id=peepso_stream_filter_sort_by]'),
				$options = $variant.find('[data-option-value]'),
				$default = $(),
				$remembered = $(),
				remembered = this.sortVariantMemory[family],
				count = 0;

			$options.each(function () {
				var $o = $(this),
					match = $o.data('group') === family;
				$o.toggle(match);
				if (match) {
					count++;
					if (!$default.length) {
						$default = $o;
					}
					// #8037 the family's last-used child this session, if it's still a valid variant.
					if (remembered && $o.data('optionValue') === remembered) {
						$remembered = $o;
					}
				}
			});

			// Show the sub-picker only when the family has more than one variant.
			$variant.toggle(count > 1);

			// #8037 The sub-picker's title mirrors the selected family (Recent/Top/Hot), so the
			// header always names the parent choice rather than a static "Show"/"Period".
			// #8117 ...unless only one family exists: the family pill is then hidden and this
			// dropdown stands alone, so keep the PHP-rendered "Sort by" rather than naming an
			// invisible family. Without this a first-load user sees "Sort by" and a returning user
			// (restored from localStorage, which reaches applySortFamily) sees "Recent".
			if (!$variant.is('[data-solo]')) {
				$variant.find('.pso-posts-filter__title span').text(
					this.$filters.filter('[data-id=peepso_stream_filter_sort_group]')
						.find('[data-option-value="' + family + '"] .pso-posts-filter-option__name').text()
				);
			}

			// Prefer the family's last-used variant this session; else its first (default) variant.
			var $option = $remembered.length ? $remembered : $default;
			if (!$option.length) {
				return;
			}

			// Select the resolved variant and sync everything the widget relies on.
			var leaf = $option.data('optionValue'),
				$toggle = $variant.find('.ps-js-dropdown-toggle');

			$options.find('[type=radio]').prop('checked', false);
			$option.find('[type=radio]').prop('checked', true);

			$('#peepso_stream_filter_sort_by').val(leaf);
			this.streamData['stream_filter_sort_by'] = leaf;
			// Keep the memory authoritative even when the family is switched without opening the
			// variant picker (records the default the first time a family is used).
			this.sortVariantMemory[family] = leaf;
			this._saveSortMemory();

			$toggle.find('span').text($option.find('span').text());
			$toggle.find('.ps-js-icon').attr('class', $option.find('.ps-js-icon').attr('class'));
		},

		/**
		 * Handle focus on input inside filter activitystream dropdowns.
		 * @param {Event} e
		 */
		onFilterFocus: function (e) {
			e.stopPropagation();
		},

		/**
		 * Handle keyup on input inside filter activitystream dropdowns.
		 * @param {Event} e
		 */
		onFilterKeyup: function (e) {
			var $dropdown, $search;

			e.stopPropagation();
			if (e.which === 13) {
				$dropdown = $(e.currentTarget).closest('.ps-js-activitystream-filter');
				$search = $dropdown.find('.ps-js-search');
				$search.click();
			}
		},

		/**
		 * Handle searching.
		 */
		onFilterSearch(e) {
			let $button = $(e.currentTarget),
				$dropdown = $button.closest('.ps-js-activitystream-filter'),
				$hidden = $('#' + $dropdown.data('id')),
				$input = $dropdown.find('[type=text]'),
				keyword = $input.val().trim().replace(/</g, '&lt;').replace(/>/g, '&gt;'),
				mode;

			// Select exact mode if keyword is empty.
			if (!keyword) {
				let $radio = $dropdown.find('[type=radio]').eq(0);
				let $option = $radio.closest('[data-option-value]');
				mode = $option.data('optionValue');
				$radio.get(0).checked = true;
			} else {
				let $radio = $dropdown.find('[type=radio]:checked');
				let $option = $radio.closest('[data-option-value]');
				mode = $option.data('optionValue');
			}

			$hidden.val(mode);
			this.search(keyword, mode);
		},

		/**
		 * Handle filters toggle.
		 */
		onFiltersToggle: function (e) {
			if (this.$filtersWrapper.is(':visible')) {
				this.$filtersWrapper.hide();
				this.$filtersToggle.removeClass('ps-posts__filters-toggle--active');
			} else {
				this.$filtersWrapper.show();
				this.$filtersToggle.addClass('ps-posts__filters-toggle--active');
			}
		}
	});
});
