/** Normalize user input to a safe http(s) URL for embedded iframe navigation. */
export function normalizeBrowserUrl(input: string): string | null {
  const trimmed = input.trim()
  if (!trimmed) return null
  try {
    const withProto = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`
    const parsed = new URL(withProto)
    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null
    if (parsed.username || parsed.password) return null
    return parsed.href
  } catch {
    return null
  }
}

/** Derive a site URL from server domain (SSH host; strip trailing :port). */
export function guessSiteUrlFromDomain(domain: string): string {
  const raw = domain.trim()
  if (!raw) return ''
  const host = raw.includes(':') ? raw.split(':')[0]!.trim() : raw
  return normalizeBrowserUrl(host) ?? `https://${host}`
}
