#include "gamecube.h"
#include <algorithm>
#include <ctime>
#include <menu.h>

// -----------------------------------------------------------
// 3D Memory Game – Hauptprogramm
// -----------------------------------------------------------
int main()
{
    // Fenster und Kamera
    InitWindow(800, 600, "3D Memory Game with Matrix3D Library");
    SetTargetFPS(60);

    // Zufall initialisieren
    srand(time(NULL));

    Camera3D camera{};
    camera.position = {6.0f, 6.0f, 6.0f};
    camera.target   = {0.0f, 0.0f, 0.0f};
    camera.up       = {0.0f, 1.0f, 0.0f};
    camera.fovy     = 45.0f;
    camera.projection = CAMERA_PERSPECTIVE;

    // Nur 3 Farben für 3 Paare
    Color colors[] = { RED, GREEN, BLUE };


    // 6 Karten-Positionen im 3x2 Raster
    std::vector<Vec3> positions = {{-2, 0, -2}, {0, 0, -2}, {2, 0, -2},{-2, 0,  0}, {0, 0,  0}, {2, 0,  0}};

    // Farben doppelt in einen Pool legen und mischen
    std::vector<Color> colorPool;
    for (int i = 0; i < 3; i++)
    {
        colorPool.push_back(colors[i]);
        colorPool.push_back(colors[i]);
    }

    // Fisher-Yates Shuffle mit rand()
    for (int i = colorPool.size() - 1; i > 0; --i)
    {
        int j = rand() % (i + 1);   // Zufallsindex von 0 bis i
        std::swap(colorPool[i], colorPool[j]);
    }

    // Karten/Würfel erstellen
    std::vector<gamecube> cubes;
    for (int i = 0; i < 6; i++)
        cubes.emplace_back(positions[i], colorPool[i]);

    gamecube* first  = nullptr;
    gamecube* second = nullptr;
    float flipSpeed = 5.0f;  // Drehgeschwindigkeit
    bool gameWon = false;


    enum class GameState
    {
        Menu,
        Idle,          // kein Würfel offen, Eingabe erlaubt
        OneFlipped,    // ein Würfel offen
        LockInput,     // Würfel drehen gerade – Eingabe kurz blockiert
        CheckingMatch  // zwei Würfel vollständig aufgeklappt, Vergleich läuft
    };

    GameState state = GameState::Menu;

    while (!WindowShouldClose()) {

        if (state == GameState::Menu)
        {
            MenuResult res = DrawMenu();
            switch (res)
            {
                case MENU_SELECT_3:
                case MENU_SELECT_6:
                case MENU_SELECT_9:
                    state = GameState::Idle;
                    break;
                default:
                    break;
            }
            if (state == GameState::Menu)
                continue;
        }

        // === GAME ===
        // Klick-Erkennung
        if (!gameWon
            && state != GameState::LockInput
            && state != GameState::CheckingMatch
            && IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
        {
            Vector2 mouse = GetMousePosition();

            for (auto &c : cubes)
            {
                if (!c.IsAnimating() && !c.IsMatched())
                {
                    Vector2 screenPos = GetWorldToScreen({c.GetPosition().x, c.GetPosition().y, c.GetPosition().z}, camera);

                    if (fabs(mouse.x - screenPos.x) < 40 && fabs(mouse.y - screenPos.y) < 40)
                    {
                        c.FlipForward();
                        if (!first)
                        {
                            first = &c;
                            state = GameState::OneFlipped;
                        }
                        else if (!second)
                        {
                            second = &c;
                            state = GameState::LockInput;
                        }
                        break;
                    }
                }
            }
        }

        // Animation aller Würfel
        bool anyAnimating = false;
        for (auto &c : cubes)
        {
            c.Update(flipSpeed);
            if (c.IsAnimating()) anyAnimating = true;
        }


        if (state == GameState::LockInput && !anyAnimating)
        {
            // If both pointers are null → this was a failed attempt finishing its backflip
            if (!first && !second)
            {
                state = GameState::Idle;
            }
            else
            {
                // Two cubes fully opened → proceed to matching
                state = GameState::CheckingMatch;
            }
        }

        // Matching-Logik
        if (state == GameState::CheckingMatch && first && second)
        {
            bool match =
                first->GetColor().r == second->GetColor().r &&
                first->GetColor().g == second->GetColor().g &&
                first->GetColor().b == second->GetColor().b;

            if (match)
            {
                first->SetMatched(true);
                second->SetMatched(true);

                first = nullptr;
                second = nullptr;

                state = GameState::Idle;
            }
            else
            {
                first->FlipBackward();
                second->FlipBackward();

                first = nullptr;
                second = nullptr;

                // WAIT FOR BACKFLIP ANIMATION
                state = GameState::LockInput;
            }
        }

        // -----------------------------------------------------------
        // Zeichnen
        // -----------------------------------------------------------
        BeginDrawing();
        ClearBackground(RAYWHITE);
        BeginMode3D(camera);

        for (auto &c : cubes)
            c.Draw();

        EndMode3D();

        if (gameWon)
            DrawText("Congrats! You found all pairs!", 150, 260, 30, DARKBLUE);
        else
            DrawText("Flip 2 cubes - find matching pairs!", 10, 10, 20, DARKGRAY);

        EndDrawing();
    }

    CloseWindow();
    return 0;
}