#include <iostream>
#include<fstream>
#include <windows.h>
#include <conio.h>
#include <math.h>

using namespace std;


void getRowColbyLeftClick(int& rpos, int& cpos) {
    HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
    DWORD Events;
    INPUT_RECORD InputRecord;
    SetConsoleMode(hInput, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT |
        ENABLE_EXTENDED_FLAGS);
    do
    {
        ReadConsoleInput(hInput, &InputRecord, 1, &Events);
        if (InputRecord.Event.MouseEvent.dwButtonState ==


            FROM_LEFT_1ST_BUTTON_PRESSED)


        {
            cpos = InputRecord.Event.MouseEvent.dwMousePosition.X;
            rpos = InputRecord.Event.MouseEvent.dwMousePosition.Y;
            break;
        }
    } while (true);
}


void gotoRowCol(int rpos, int cpos) {
    COORD scrn;
    HANDLE hOuput = GetStdHandle(STD_OUTPUT_HANDLE);
    scrn.X = cpos;
    scrn.Y = rpos;
    SetConsoleCursorPosition(hOuput, scrn);
}

void color(int k) {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, k);
}

void hideConsoleCursor() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cursorInfo;
    GetConsoleCursorInfo(hConsole, &cursorInfo);
    cursorInfo.bVisible = false;
    SetConsoleCursorInfo(hConsole, &cursorInfo);
}



const int boardSize = 5;


int beads[boardSize][boardSize];
int owner[boardSize][boardSize];

bool firstMove[3];


void initializeBoard() {

    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardSize;j++) {

            beads[i][j] = 0;
            owner[i][j] = 0;


        }
    }

    firstMove[1] = true;
    firstMove[2] = true;
}


void displayBoard(int currentPlayer) {

    system("cls");

    cout << "    0   1   2   3   4  " << endl;
    cout << "  +---+---+---+---+---+" << endl;

    for (int i = 0; i < boardSize; i++) {

        cout << i << " |";

        for (int j = 0; j < boardSize; j++) {

            if (owner[i][j] == 0) {
                color(7);
                cout << " . |";
            }
            else {
                if (owner[i][j] == 1) {
                    color(12);
                }
                else {
                    color(9);
                }

                cout << " " << beads[i][j] << " ";
                color(7);
                cout << "|";
            }


        }

        cout << "\n  +---+---+---+---+---+" << endl;
    }

    cout << "\nTurn: ";
    if (currentPlayer == 1) {
        color(12);
        cout << "Red";
    }
    else {
        color(9);
        cout << "Blue";
    }

    color(7);

    if (firstMove[currentPlayer]) {
        cout << "(place on empty cell)";
    }
    else {
        cout << " (play on your own cell only)";
    }

    cout << endl;

    cout << "\nClick HERE to SAVE & EXIT\n";
    color(13);
    cout << "[ SAVE ]\n";
    color(7);
}


bool isvalidMove(int rows, int cols, int player) {

    if (rows < 0 || cols < 0 || cols>=5 || rows>=5) {

        return false;

    }

    if (firstMove[player]) {
        if (owner[rows][cols] != 0) {
            return false;
        }
        return true;
    }

    if (owner[rows][cols] == player) {
        return true;
    }

    return false;
}


bool getCellFromclick(int& rows, int& cols) {

    int rpos, cpos;

    getRowColbyLeftClick(rpos, cpos);

    rows = (rpos - 2) / 2;
    cols = (cpos - 4) / 4;

    if (rows < 0 || rows >= 5 || cols < 0 || cols >= 5) {
        return false;
    }

    return true;

}

void explode(int player) {

    bool exploded = true;

    while (exploded) {
        exploded = false;

        for (int i = 0; i < boardSize;i++) {
            for (int j = 0; j < boardSize;j++) {

                if (beads[i][j] < 4) {
                    continue;
                }

                exploded = true;

                beads[i][j] = beads[i][j] - 4;

                if (beads[i][j] == 0) {
                    owner[i][j] = 0;
                }

                if (i - 1 >= 0) {
                    beads[i - 1][j]++;
                    owner[i - 1][j] = player;
                }

                if (i + 1 < 5) {
                    beads[i + 1][j]++;
                    owner[i + 1][j] = player;
                }

                if (j - 1 >= 0) {
                    beads[i][j - 1]++;
                    owner[i][j - 1] = player;
                }

                
                if (j + 1 < 5) {
                    beads[i][j + 1]++;
                    owner[i][j + 1] = player;
                }
            }
        }
    }


}

bool makeMove(int rows, int cols, int player) {

    if (firstMove[player]) {
        beads[rows][cols] = 3;
        owner[rows][cols] = player;
        firstMove[player] = false;
    }

    else {
        beads[rows][cols]++;
    }

    if (beads[rows][cols] >= 4) {
        explode(player);
    }
}

int checkWinner(int totalMoves) {

    if (totalMoves < 2) {
        return 0;
    }

    int p1 = 0, p2 = 0;

    for (int i = 0; i < boardSize;i++) {
        for (int j = 0; j < boardSize; j++) {

            if (owner[i][j] == 1) {
                p1++;
            }
            else if(owner[i][j] == 2) {
                p2++;
            }
        }
    }

    if (p1 == 0) {
        return 2;
    }
    if (p2 == 0) {
        return 1;
    }

    return 0;
}


void saveGame(int currentPlayer, int totalMoves) {

    ofstream wrt("save.txt");

    wrt << currentPlayer << " " << totalMoves << endl;


    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardSize; j++) {

            wrt << beads[i][j] << " ";

        }
        wrt << endl;
    }

    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardSize; j++) {

            wrt << owner[i][j] << " ";

        }
        wrt << endl;
    }

    wrt << firstMove[1] << " " << firstMove[2];

}


bool loadGame(int& currentPlayer, int& moveCount) {

    ifstream rdr("save.txt");

    if (!rdr) {
        return false;
    }

    rdr >> currentPlayer >> moveCount;

    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardSize; j++) {
            rdr >> beads[i][j];
        }
    }


    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardSize; j++) {
            rdr >> owner[i][j];
        }
    }

    rdr >> firstMove[1] >> firstMove[2];

    rdr.close();
    return true;

}

void showRules() {
    system("cls");

    color(13);
    cout << "====== GAME RULES ======\n\n";
    color(7);

    color(14);
    cout << "1. Board: ";
    color(7);
    cout << "5 x 5 grid.\n";

    color(14);
    cout << "2. Players: ";
    color(12);
    cout << "Red ";
    color(7);
    cout << "(P1) and ";
    color(9);
    cout << "Blue ";
    color(7);
    cout << "(P2).\n";

    color(14);
    cout << "3. First Move: ";
    color(7);
    cout << "Place on EMPTY cell → value = 3.\n";

    color(14);
    cout << "4. Later Moves:\n";
    color(7);
    cout << "   - Play only on your own cells\n";
    cout << "   - Value increases by 1\n";

    color(14);
    cout << "5. Explosion: ";
    color(7);
    cout << "Value = 4 , cell resets & spreads to neighbors\n";

    color(14);
    cout << "6. Capture: ";
    color(7);
    cout << "Neighbors become yours\n";

    color(14);
    cout << "7. Chain Reaction: ";
    color(7);
    cout << "Explosions can continue\n";

    color(14);
    cout << "8. Win: ";
    color(7);
    cout << "Own all occupied cells\n";

    cout << "\n";
    color(11);
    cout << "Press any key to return...";
    color(7);

    _getch();
}

int showMenu() {

    system("cls");

    cout << "=========================\n";
    cout << "   CHAIN REACTION GAME\n";
    cout << "=========================\n";
    cout << "1. New Game\n";
    cout << "2. Load Game\n";
    cout << "3. Rules\n";
    cout << "3. Exit\n";
    cout << "Choose option: ";

    int choice;
    cin >> choice;

    return choice;
}


int main() {

    hideConsoleCursor();

    int currentPlayer = 1;
    int totalMoves = 0;

    int choice = showMenu();

    if (choice == 1) {
        initializeBoard();
    }
    else if (choice == 2) {
        if (!loadGame(currentPlayer, totalMoves)) {
            cout << "No saved game found. Starting new game...\n";
            Sleep(1000);
            initializeBoard();
        }
    }
    else if (choice == 3) {

        showRules();

    }
    else {
        return 0;
    }

    while (true) {

        displayBoard(currentPlayer);

        int r, c;
        getRowColbyLeftClick(r, c);

        // Check if user clicked the SAVE button
        if (r == 16 && c >= 0 && c <= 7) {
            saveGame(currentPlayer, totalMoves);
            cout << "\nGame Saved!\n";
            Sleep(800);
            break;
        }

        // Convert screen coords -> grid coords
        int gridR = (r - 2) / 2;
        int gridC = (c - 4) / 4;

        if (gridR < 0 || gridR >= 5 || gridC < 0 || gridC >= 5) {
            continue;
        }

        if (!isvalidMove(gridR, gridC, currentPlayer)) {
            cout << "Invalid move! try again" << endl;
            Sleep(600);
            continue;
        }

        makeMove(gridR, gridC, currentPlayer);
        totalMoves++;

        int winner = checkWinner(totalMoves);

        if (winner != 0) {
            displayBoard(currentPlayer);

            cout << "\n*** ";
            if (winner == 1) {
                color(12);
                cout << "RED";
            }
            else {
                color(9);
                cout << "BLUE";
            }
            color(7);
            cout << " WINS! ***\n";

            break;
        }

        if (currentPlayer == 1)
            currentPlayer = 2;
        else
            currentPlayer = 1;
    }

    return 0;
}