My Minimax algorithm for the Tic Tac Toe game doesn't work out of the box

This is my codepen:

I had followed as good as I understood the minimax algorithm and then I wrote a function called minimax but sometimes it does not choose the best move, for example it’s Artificial Inteligence (AI) turn and there is an opportunity to win in the next move but it chooses another one.

Another problem is that my AI is not unbeatable, there is a pattern of movements that if the user follows he can win.