// Guard for any href/src/action/formAction attribute fed from stored or API data.
// A stored `javascript:`/`data:`/`vbscript:` URL executes on click if interpolated
// straight into a URL attribute — this is the only sanctioned way in.

/**
 * Returns `value` when it is a safe navigation target: an absolute http(s) URL,
 * or a same-origin relative path/query/fragment (`/…`, `?…`, `#…`). Returns
 * `undefined` for everything else, including scheme-relative `//host` (that
 * changes origin) and non-http(s) schemes such as `javascript:`/`data:`.
 *
 * Uses the WHATWG URL parser rather than a regex blocklist: the parser already
 * strips leading/trailing C0 controls and embedded tab/newline characters and
 * lower-cases the scheme, so `JaVaScRiPt:`, embedded whitespace, and leading
 * control-character variants resolve to the same rejected protocol without
 * bespoke normalization.
 */
export function safeHttpUrl(value: string | null | undefined): string | undefined {
  if (typeof value !== 'string' || value === '') return undefined
  if (value.startsWith('//')) return undefined
  if (value.startsWith('/') || value.startsWith('?') || value.startsWith('#')) return value
  try {
    const parsed = new URL(value)
    return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? value : undefined
  } catch {
    return undefined
  }
}
