/**
 * Builder UX: unsaved-changes guard, mobile shell hint, header title sync with document title field.
 */
(function ($) {
	'use strict';

	var HINT_KEY = 'ei_builder_shell_hint_v1';

	function getI18n(key, fallback) {
		if (window.easyInvoice && easyInvoice.i18n && easyInvoice.i18n[key]) {
			return easyInvoice.i18n[key];
		}
		return fallback;
	}

	function setupDirtyGuard() {
		var $forms = $('#invoice-form, #quote-form');
		if (!$forms.length) {
			return;
		}

		window.eiBuilderDirty = false;

		function markDirty() {
			window.eiBuilderDirty = true;
		}

		$(document).on('input change', '#invoice-form :input, #quote-form :input', function () {
			markDirty();
		});

		$(document).on('easy-invoice-saved', function (e, response) {
			if (response && response.success) {
				window.eiBuilderDirty = false;
			}
		});
		$(document).on('easy-quote-saved', function (e, response) {
			if (response && response.success) {
				window.eiBuilderDirty = false;
			}
		});

		$(window).on('beforeunload', function (e) {
			if (!window.eiBuilderDirty) {
				return;
			}
			e.preventDefault();
			e.returnValue = getI18n(
				'builder_unsaved_warning',
				'You have unsaved changes. If you leave this page, your changes may be lost.'
			);
			return e.returnValue;
		});
	}

	function setupShellHint() {
		var $box = $('#ei-builder-shell-hint');
		if (!$box.length) {
			return;
		}

		function dismissed() {
			try {
				return window.localStorage.getItem(HINT_KEY) === '1';
			} catch (err) {
				return false;
			}
		}

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

		function apply() {
			if (dismissed() || isLarge()) {
				$box.addClass('hidden').attr('hidden', 'hidden');
				return;
			}
			$box.removeClass('hidden').removeAttr('hidden');
		}

		apply();
		$(window).on('resize', apply);

		$(document).on('click', '#ei-builder-shell-hint-dismiss', function () {
			try {
				window.localStorage.setItem(HINT_KEY, '1');
			} catch (err) {}
			$box.addClass('hidden').attr('hidden', 'hidden');
		});
	}

	function setupHeaderTitleSync() {
		var $h = $('#ei-builder-header-title');
		var $inp = $('#invoice-form input[name="title"], #quote-form input[name="title"]').first();
		if (!$h.length || !$inp.length) {
			return;
		}
		var def = $h.attr('data-ei-default') || '';

		function apply() {
			var v = ($inp.val() || '').trim();
			$h.text(v || def);
		}

		$inp.on('input', apply);
	}

	$(function () {
		setupDirtyGuard();
		setupShellHint();
		setupHeaderTitleSync();
	});
})(jQuery);
