/**
 * Copyright © Volker Schukai and all contributing authors, {{copyRightYear}}. All rights reserved.
 * Node module: @schukai/monster
 *
 * This source code is licensed under the GNU Affero General Public License version 3 (AGPLv3).
 * The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.en.html
 *
 * For those who do not wish to adhere to the AGPLv3, a commercial license is available.
 * Acquiring a commercial license allows you to use this software without complying with the AGPLv3 terms.
 * For more information about purchasing a commercial license, please contact Volker Schukai.
 *
 * SPDX-License-Identifier: AGPL-3.0
 */

import { getWindow } from "../../dom/util.mjs";

export { generateUniqueConfigKey };

/**
 * Generate a unique configuration key based on the current browser location,
 * component name, id, and a prefix.
 *
 * @since 3.55.0 the function remove the hash from the key
 *
 * @param {string} componentName - The name of the component.
 * @param {string} id - A unique identifier for the component.
 * @param {string} prefix - A prefix to use in the unique key.
 * @return {string} The generated unique configuration key.
 */
function generateUniqueConfigKey(componentName, id, prefix) {
	// Get the browser location without parameters
	const urlWithoutParams = getWindow().location.href.split("?")[0];

	// Without hash (since 3.55.0)
	const urlWithoutParamsAndHash = urlWithoutParams.split("#")[0];

	// Combine the parts to create a unique key
	const uniqueKey = `${prefix}_${urlWithoutParamsAndHash}_${componentName}_${id}`;

	// Replace any special characters and spaces with underscores
	return uniqueKey.replace(/[^\w\s]/gi, "_").replace(/\s+/g, "_");
}
