function trimTrailingSlash(value: string) {
  return value.replace(/\/+$/, "");
}

function getDefaultGlitchComponentBaseUrl() {
  return trimTrailingSlash(
    import.meta.env.VITE_GLITCH_COMPONENT_BASE_URL || "/glitch"
  );
}

export function getGlitchComponentFolderName(componentId: string) {
  return `glitch_${componentId.replace(/-/g, "_")}`;
}

export function resolveGlitchComponentUrl(
  componentId: string,
  componentUrl?: string
) {
  const explicitUrl = componentUrl?.trim();

  if (explicitUrl) {
    return explicitUrl;
  }

  const baseUrl = getDefaultGlitchComponentBaseUrl();
  const folderName = getGlitchComponentFolderName(componentId);
  return `${baseUrl}/${folderName}/index.html`;
}
