/**
 * Active Plugins First — section headings (ordering is done server-side).
 *
 * @package ActivePluginsFirst
 * @since 1.0.0
 */
(function () {
	'use strict';

	var STORAGE_KEY = 'wpps_apf_collapsed';

	function getStored() {
		try {
			var raw = localStorage.getItem(STORAGE_KEY);
			return raw ? JSON.parse(raw) : {};
		} catch (e) {
			return {};
		}
	}

	function setStored(obj) {
		try {
			localStorage.setItem(STORAGE_KEY, JSON.stringify(obj));
		} catch (e) {}
	}

	function getPluginStatus() {
		var statusMatch = window.location.search.match(/plugin_status=([^&]+)/);
		return statusMatch ? statusMatch[1] : 'all';
	}

	function getWpCount(sectionKey) {
		var sel = '.subsubsub li.' + sectionKey + ' .count';
		var el = document.querySelector(sel) || document.querySelector('a[href*="plugin_status=' + sectionKey + '"] .count');
		return el ? el.textContent.trim() : '';
	}

	function classifyRows(rows) {
		var active = [];
		var inactive = [];

		rows.forEach(function (tr) {
			if (tr.classList.contains('active')) {
				active.push(tr);
			} else if (tr.classList.contains('inactive')) {
				inactive.push(tr);
			}
		});

		return { active: active, inactive: inactive };
	}

	function run() {
		var cfg = window.wppsActivePluginsFirst;
		if (!cfg || !cfg.strings) {
			return;
		}

		var pluginStatus = getPluginStatus();
		if (pluginStatus !== 'all' && pluginStatus !== 'active' && pluginStatus !== 'inactive') {
			return;
		}

		var tbody = document.querySelector('.plugins .wp-list-table tbody') || document.querySelector('.plugins tbody');
		if (!tbody) {
			return;
		}

		var rows = Array.from(tbody.querySelectorAll('tr')).filter(function (tr) {
			return !tr.classList.contains('hidden') &&
				!tr.classList.contains('no-items') &&
				!tr.classList.contains('wp-powersuite-plugin-heading');
		});

		if (!rows.length) {
			return;
		}

		var groups = classifyRows(rows);
		var table = tbody.closest('table');
		var headerCells = table && table.tHead ? table.tHead.querySelectorAll('th') : null;
		var colspan = (headerCells && headerCells.length) ? headerCells.length : 4;
		var fallback = rows.reduce(function (max, tr) {
			var n = (tr.cells && tr.cells.length) || 0;
			return n > max ? n : max;
		}, 0);
		if (fallback > colspan) {
			colspan = fallback;
		}

		var stored = getStored();
		tbody.innerHTML = '';

		function addSection(sectionKey, label, items, defaultCollapsed) {
			if (!items.length) {
				return;
			}

			var collapsed = stored[sectionKey] !== undefined ? stored[sectionKey] : !!defaultCollapsed;
			var tableEl = tbody.closest('table');
			var attr = 'apfCollapsed' + sectionKey.charAt(0).toUpperCase() + sectionKey.slice(1);

			if (collapsed && tableEl) {
				tableEl.dataset[attr] = 'true';
			}

			var headingRow = document.createElement('tr');
			headingRow.className = 'wp-powersuite-plugin-heading';
			headingRow.dataset.section = sectionKey;
			var td = document.createElement('td');
			td.colSpan = colspan;

			var toggle = document.createElement('button');
			toggle.type = 'button';
			toggle.className = 'wp-powersuite-plugin-heading__toggle';
			toggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
			toggle.setAttribute('aria-label', cfg.strings.toggle);
			toggle.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>';

			var title = document.createElement('h2');
			var countSpan = document.createElement('span');
			countSpan.className = 'wp-powersuite-plugin-heading__count';
			countSpan.textContent = getWpCount(sectionKey) || '(' + items.length + ')';
			title.appendChild(document.createTextNode(label + ' '));
			title.appendChild(countSpan);

			var inner = document.createElement('div');
			inner.className = 'wp-powersuite-plugin-heading__inner';
			inner.appendChild(toggle);
			inner.appendChild(title);
			td.appendChild(inner);
			headingRow.appendChild(td);

			toggle.addEventListener('click', function () {
				var tbl = tbody.closest('table');
				if (!tbl) {
					return;
				}
				var isCollapsed = toggle.getAttribute('aria-expanded') === 'false';
				toggle.setAttribute('aria-expanded', isCollapsed ? 'true' : 'false');
				var a = 'apfCollapsed' + sectionKey.charAt(0).toUpperCase() + sectionKey.slice(1);
				if (isCollapsed) {
					delete tbl.dataset[a];
					stored[sectionKey] = false;
				} else {
					tbl.dataset[a] = 'true';
					stored[sectionKey] = true;
				}
				setStored(stored);
			});

			tbody.appendChild(headingRow);
			items.forEach(function (r) {
				r.dataset.section = sectionKey;
				tbody.appendChild(r);
			});
		}

		if (pluginStatus === 'active') {
			addSection('active', cfg.strings.active, groups.active, false);
		} else if (pluginStatus === 'inactive') {
			addSection('inactive', cfg.strings.inactive, groups.inactive, true);
		} else {
			addSection('active', cfg.strings.active, groups.active, false);
			addSection('inactive', cfg.strings.inactive, groups.inactive, true);
		}
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', run);
	} else {
		run();
	}
})();
