/**
 * Mobile-only tabs: Editor vs Preview on invoice/quote builders (lg+ shows both).
 */
(function ($) {
	'use strict';

	function mqLarge() {
		return window.matchMedia('(min-width: 1024px)').matches;
	}

	function applyLayout() {
		var $e = $('#ei-builder-editor');
		var $p = $('#ei-builder-preview');
		if (!$e.length || !$p.length) {
			return;
		}
		if (mqLarge()) {
			$e.removeClass('hidden');
			$p.removeClass('hidden');
			return;
		}
		var tab = window.sessionStorage.getItem('ei_builder_tab') || 'editor';
		if (tab === 'preview') {
			$e.addClass('hidden');
			$p.removeClass('hidden');
		} else {
			$e.removeClass('hidden');
			$p.addClass('hidden');
		}
	}

	function setActiveTab(which) {
		$('.ei-builder-tab').each(function () {
			var isSel = $(this).data('tab') === which;
			$(this).attr('aria-selected', isSel ? 'true' : 'false');
			$(this).toggleClass('bg-white shadow-sm text-indigo-700', isSel);
			$(this).toggleClass('text-gray-600 hover:text-gray-800', !isSel);
		});
	}

	$(document).on('click', '.ei-builder-tab', function () {
		var which = $(this).data('tab');
		if (!which) {
			return;
		}
		window.sessionStorage.setItem('ei_builder_tab', which);
		setActiveTab(which);
		applyLayout();
	});

	$(window).on('resize', function () {
		applyLayout();
	});

	$(function () {
		var initial = window.sessionStorage.getItem('ei_builder_tab') || 'editor';
		setActiveTab(initial);
		applyLayout();
	});
})(jQuery);
