const LOCAL_EXPLORER_API_FALLBACK = 'http://localhost:8080'

function normalizeApiBase(value: string | null | undefined): string {
  return (value || '').trim().replace(/\/$/, '')
}

export function resolveExplorerApiBase(options: {
  envValue?: string | null
  browserOrigin?: string | null
  serverFallback?: string
} = {}): string {
  const explicitBase = normalizeApiBase(options.envValue ?? process.env.NEXT_PUBLIC_API_URL ?? '')
  if (explicitBase) {
    return explicitBase
  }

  const browserOrigin = normalizeApiBase(
    options.browserOrigin ?? (typeof window !== 'undefined' ? window.location.origin : '')
  )
  if (browserOrigin) {
    return browserOrigin
  }

  return normalizeApiBase(options.serverFallback ?? LOCAL_EXPLORER_API_FALLBACK)
}
