let enhance_textareas_debounce_timeout;
function enhance_textareas() {
	if (enhance_textareas_debounce_timeout) {
		clearTimeout(enhance_textareas_debounce_timeout);
	}

	enhance_textareas_debounce_timeout = setTimeout(() => {
		enhance_textareas_debounce_timeout = undefined;

		const textareas = document.body.querySelectorAll("textarea:not([data-enhanced])");
		for (const textarea of textareas) {
			const max_length_attr = textarea.getAttribute("maxlength");
			if (/^\d+$/.test(max_length_attr)) {
				const max_length = parseInt(max_length_attr, 10);

				function on_updated() {
					const counters = this.parentElement.querySelectorAll(
						`[data-limit-counter-for="${this.name}"]`,
					);
					for (const counter of counters) {
						counter.innerHTML = `${this.value.length} / ${max_length}`;
					}
				}

				textarea.addEventListener("keyup", on_updated);
				textarea.addEventListener("paste", on_updated);
				textarea.addEventListener("blur", on_updated);
				on_updated.call(textarea);
			}

			textarea.dataset.enhanced = true;
		}
	}, 10);
}

const textarea_enhancement_observer = new MutationObserver(enhance_textareas);
textarea_enhancement_observer.observe(document, {
	childList: true,
	subtree: true,
});
