/**
 * Returns whether the app is running inside an iframe.
 *
 * In cross-origin embeds, reading `window.top` can throw; in that case we
 * conservatively return `true`.
 */
export function inIframe(): boolean {
  try {
    return window.self !== window.top
  } catch {
    // if we can't access window.top due to cross-origin, we're in an iframe
    return true
  }
}

/**
 * Build a URL suitable for opening app routes in a new tab.
 *
 * In DSS iframe mode, convert iframe context URL into a /webapps/{projectKey}/{webAppId} URL.
 * Outside DSS iframe mode, resolve to a regular absolute URL.
 */
export function buildNewTabRouteUrl(resolvedHref: string, resolvedFullPath: string): string {
  const isDssIframeContext =
    inIframe() && window.location.pathname.includes('/dip/api/webapps/view')

  if (isDssIframeContext) {
    const currentUrl = new URL(window.location.href)
    const projectKey = currentUrl.searchParams.get('projectKey')
    const webAppId = currentUrl.searchParams.get('webAppId')

    if (projectKey && webAppId) {
      const normalizedFullPath = resolvedFullPath.startsWith('/')
        ? resolvedFullPath
        : `/${resolvedFullPath}`

      return `${window.location.origin}/webapps/${encodeURIComponent(projectKey)}/${encodeURIComponent(webAppId)}${normalizedFullPath}`
    }
  }

  return new URL(resolvedHref, window.location.origin).toString()
}
