// Works around a Frappe core bug that throws on every Azerbaijani declaration form.
//
// When a tab is activated, Frappe writes the tab's fieldname into the URL hash
// (form.js, set_active_tab). Our Tab Break fieldnames are Azerbaijani — `ümumi_məlumat_tab`
// — and assigning them through the URL API percent-encodes them, so the hash becomes
// `#%C3%BCmumi_m%C9%99lumat_tab`.
//
// Frappe then feeds that hash straight to jQuery as a selector (form.js, scroll_to_element:
// `if ($(window.location.hash).length)`). `%` is not legal in a CSS identifier, so jQuery
// throws "Syntax error, unrecognized expression" — on load, on every declaration.
//
// It is caught as an unhandled page error rather than breaking the form, but it fires
// constantly and buries real errors in the console. Patching Frappe itself would be
// undone by the next update, and renaming the tab fields would touch 24 doctypes and the
// subtab hierarchy, so the guard lives here.
//
// Frappe's intent in that branch is "scroll to the element the hash names, else treat the
// hash as a fieldname". Both paths still work below — the hash is just decoded first, and
// matched with getElementById instead of a CSS selector.

frappe.provide("taxes_az");

(function () {
	const Form = frappe.ui && frappe.ui.form && frappe.ui.form.Form;
	if (!Form || !Form.prototype.scroll_to_element || Form.prototype.__hash_fix) return;

	const original = Form.prototype.scroll_to_element;

	Form.prototype.scroll_to_element = function () {
		try {
			return original.apply(this, arguments);
		} catch (e) {
			if (!/unrecognized expression/i.test(e.message || "")) throw e;

			// jQuery choked on the percent-encoded hash. Redo what Frappe meant to do.
			let target;
			try {
				target = decodeURIComponent(window.location.hash || "").replace("#", "");
			} catch (decode_error) {
				return;
			}
			if (!target) return;

			if (document.getElementById(target)) {
				frappe.utils.scroll_to("#" + target, true, 200, null, null, true);
			} else if (this.scroll_to_field(target)) {
				history.replaceState(null, null, " ");
			}
		}
	};

	Form.prototype.__hash_fix = true;
})();
