const LEGACY_SITE_ORIGIN = "https://homebuyers-nationwide.com";

export function getRuntimeCanonicalUrl(canonicalUrl?: string, runtimeOrigin?: string): string {
  const origin = (runtimeOrigin || (typeof window !== "undefined" ? window.location.origin : LEGACY_SITE_ORIGIN)).replace(/\/$/, "");
  const fallbackPath = typeof window !== "undefined" ? window.location.pathname : "/";
  const source = canonicalUrl || fallbackPath;

  try {
    const parsed = new URL(source, `${origin}/`);
    return `${origin}${parsed.pathname}`;
  } catch {
    return `${origin}/`;
  }
}

export function rebaseSameSiteSchemaUrls(value: unknown, runtimeOrigin: string): unknown {
  const origin = runtimeOrigin.replace(/\/$/, "");

  if (typeof value === "string") {
    return value.startsWith(LEGACY_SITE_ORIGIN)
      ? `${origin}${value.slice(LEGACY_SITE_ORIGIN.length)}`
      : value;
  }

  if (Array.isArray(value)) {
    return value.map(item => rebaseSameSiteSchemaUrls(item, origin));
  }

  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value).map(([key, item]) => [key, rebaseSameSiteSchemaUrls(item, origin)])
    );
  }

  return value;
}
