const mergeDeep = (target, ...sources) => {
	if (!sources.length) return target;
	const source = sources.shift();

	if (typeof target === "object" && typeof source === "object") {
		for (const key in source) {
			if (source[key] instanceof Object && !Array.isArray(source[key])) {
				if (!target[key]) Object.assign(target, { [key]: {} });
				mergeDeep(target[key], source[key]);
			} else {
				Object.assign(target, { [key]: source[key] });
			}
		}
	}

	return mergeDeep(target, ...sources);
};

const parseParams = (search) => {
	return search
		.replace(/^\?/, "") // Remove o "?" inicial
		.split("&") // Divide os parâmetros
		.reduce((params, param) => {
			const [key, value] = param.split("="); // Separa chave e valor
			params[decodeURIComponent(key)] = decodeURIComponent(value || "");
			return params;
		}, {});
};

const stringifyParams = (params) => {
	return Object.keys(params)
		.map(
			(key) =>
				`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`,
		)
		.join("&");
};

const capitalize = (text) => {
	if (typeof text !== "string") return "";
	return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
};

window.mergeDeep = mergeDeep;
window.parseParams = parseParams;
window.stringifyParams = stringifyParams;
window.capitalize = capitalize;
