/**
 * Answyr — Insights page tabs.
 * Toggle the .answyr-insights-section[data-answyr-tab] panels client-side so Tickets and
 * Chat read as tabbed sections. No-JS keeps both sections visible.
 */
(() => {
	var nav = document.querySelector('.answyr-insights-tabs');
	if (!nav) {
		return;
	}
	var tabs = Array.prototype.slice.call(nav.querySelectorAll('.nav-tab'));
	var sections = Array.prototype.slice.call(
		document.querySelectorAll('.answyr-insights-section[data-answyr-tab]'),
	);
	var ids = tabs.map((t) => t.getAttribute('data-answyr-tab'));
	var STORAGE_KEY = 'ss_insights_tab';

	function activate(id) {
		tabs.forEach((t) => {
			t.classList.toggle('nav-tab-active', t.getAttribute('data-answyr-tab') === id);
		});
		sections.forEach((s) => {
			s.hidden = s.getAttribute('data-answyr-tab') !== id;
		});
		try {
			window.localStorage.setItem(STORAGE_KEY, id);
		} catch (_e) {
			// storage may be unavailable — tabs still work for the session
		}
	}

	tabs.forEach((t) => {
		t.addEventListener('click', (e) => {
			e.preventDefault();
			activate(t.getAttribute('data-answyr-tab'));
		});
	});

	// First-choice order: URL hash, then last-used, then the first tab whose
	// section is enabled (skip a dimmed "Off" surface), else the first tab.
	var hash = window.location.hash.replace('#answyr-', '');
	var stored = '';
	try {
		stored = window.localStorage.getItem(STORAGE_KEY) || '';
	} catch (_e) {
		stored = '';
	}
	var firstEnabled = sections.find((s) => !s.classList.contains('answyr-section-off'));
	var firstEnabledId = firstEnabled ? firstEnabled.getAttribute('data-answyr-tab') : '';
	var initial =
		ids.indexOf(hash) !== -1
			? hash
			: ids.indexOf(stored) !== -1
				? stored
				: firstEnabledId || ids[0];
	activate(initial);
})();
