import { resolveBrowserAppUrl } from '@/lib/appUrls'

function toAppBase(url: string): string {
  try {
    const parsed = new URL(url)
    return (parsed.origin + parsed.pathname).replace(/\/$/, '')
  } catch {
    return url.replace(/\/$/, '')
  }
}

function withCarplacePath(url: string): string {
  const base = toAppBase(url)
  return /\/carplace$/i.test(base) ? base : `${base}/carplace`
}

export const websiteUrl = toAppBase(
  resolveBrowserAppUrl(process.env.NEXT_PUBLIC_WEBSITE_URL ?? 'http://localhost:3000'),
)

export const carplaceUrl = withCarplacePath(
  resolveBrowserAppUrl(process.env.NEXT_PUBLIC_CARPLACE_URL ?? websiteUrl),
)

export const adminUrl = toAppBase(
  resolveBrowserAppUrl(process.env.NEXT_PUBLIC_ADMIN_URL ?? `${websiteUrl}/admin`),
)
