Black Caps edge thriller to preserve unbeaten record