import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class GameGUI extends JFrame {
    private final int SIZE = 10;
    private JButton[][] buttons = new JButton[SIZE][SIZE];
    private Game game;
    private int round = 0;

    public GameGUI(Game game) {
        this.game = game;
        setTitle("Catch the Mouse - Sprint 2 GUI");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(SIZE, SIZE));

        initializeGrid();
        updateGrid();
        
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initializeGrid() {
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                JButton button = new JButton();
                button.setFont(new Font("Arial", Font.BOLD, 20));
                final int r = i;
                final int c = j;
                button.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        handleMove(r, c);
                    }
                });
                buttons[i][j] = button;
                add(button);
            }
        }
    }

    private void handleMove(int x, int y) {
        try {
            if (game.gameOver()) return;

            // Log Round
            game.writer.write("Round " + round);
            game.writer.newLine();

            // 1. Mouse moves first (as per our improved strategy)
            game.mouse.movePlayer();

            // 2. Tom moves to clicked position
            game.cat.movePlayer(x, y);

            round++;
            updateGrid();

            if (game.gameOver()) {
                game.writer.flush();
                JOptionPane.showMessageDialog(this, "Congrats! You caught the mouse!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
                System.exit(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateGrid() {
        Position[][] field = game.gArea.getPlayingField();
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                char ch = field[i][j].displayChar;
                buttons[i][j].setText(String.valueOf(ch));
                
                // Styling
                if (ch == DisplayChars.TOM.getCharacter()) {
                    buttons[i][j].setForeground(Color.BLUE);
                } else if (ch == DisplayChars.JERRY.getCharacter()) {
                    buttons[i][j].setForeground(Color.RED);
                } else {
                    buttons[i][j].setForeground(Color.BLACK);
                }
            }
        }
    }
}
