export function safeInternalHref(value: unknown, fallback = '/') {
  const target = String(value || '').trim()
  if (!target) return fallback
  if (!target.startsWith('/') || target.startsWith('//')) return fallback
  if (/[\u0000-\u001f]/.test(target)) return fallback
  return target.slice(0, 512)
}

export function navigateReliably(target: string, replace: (href: string) => void, fallback = '/') {
  const safeTarget = safeInternalHref(target, fallback)
  replace(safeTarget)
  window.setTimeout(() => {
    const current = `${window.location.pathname}${window.location.search}`
    if (current !== safeTarget) window.location.assign(safeTarget)
  }, 800)
}
