const RETURN_KEY = "ultidrive-editor-return-to"

function isSafeDriveReturnPath(path: string): boolean {
  if (!path.startsWith("/drive")) return false
  if (path.startsWith("//")) return false
  if (path.includes("://")) return false
  return true
}

/** Remember browser location before opening an editor (not stored in URL). */
export function stashDriveEditorReturnTo(path?: string) {
  if (typeof window === "undefined") return
  const href = path ?? window.location.pathname + window.location.search
  if (isSafeDriveReturnPath(href)) {
    sessionStorage.setItem(RETURN_KEY, href)
  }
}

export function readDriveEditorReturnTo(): string | null {
  if (typeof window === "undefined") return null
  const value = sessionStorage.getItem(RETURN_KEY)
  return value && isSafeDriveReturnPath(value) ? value : null
}

export function clearDriveEditorReturnTo() {
  if (typeof window === "undefined") return
  sessionStorage.removeItem(RETURN_KEY)
}
