const initializedRoots = new WeakSet();

function init(root = document) {
	if(initializedRoots.has(root)) {
		return;
	}

	root.addEventListener("click", event => {
		const clearButton = event.target.closest("[data-input-clear]");

		if(!clearButton) {
			return;
		}

		const group = clearButton.closest(".input-group");
		const input = group?.querySelector("input, textarea");

		if(!input) {
			return;
		}

		input.value = "";
		input.dispatchEvent(new Event("input", { bubbles: true }));
		input.focus();
	});

	initializedRoots.add(root);
}

export default {
	init
};
