Point $B$ is in the exterior of the regular $n$-sided polygon $A_1A_2\cdots A_n$, and $A_1A_2B$ is an isosceles right triangle with the right angle at $A_1$. What is the largest value of $n$ for which $A_1$, $A_n$, and $B$ are consecutive vertices of a regular polygon?