#include "raylib.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Definition der verschiedenen Spielbildschirme inklusive Bestätigungs-Screen
typedef enum GameScreen { 
    SCREEN_MENU, 
    SCREEN_TUTORIAL, 
    SCREEN_GAME, 
    SCREEN_CONFIRM_RESET 
} GameScreen;

// Funktionen zum Speichern and Laden des Balances
int LoadBalance() {
    int balance = 0;
    FILE *file = fopen("save.txt", "r");
    if (file != NULL) {
        fscanf(file, "%d", &balance);
        fclose(file);
    }
    return balance;
}

void SaveBalance(int balance) {
    FILE *file = fopen("save.txt", "w");
    if (file != NULL) {
        fprintf(file, "%d", balance);
        fclose(file);
    }
}

int main(void) {
    // Initialisierung des Fensters
    const int screenWidth = 800;
    const int screenHeight = 600;
    InitWindow(screenWidth, screenHeight, "Guessing Game Deluxe");
    SetTargetFPS(60);
    srand(time(NULL));

    // Spielvariablen
    GameScreen currentScreen = SCREEN_MENU;
    int balance = LoadBalance();
    int targetNumber = 0;
    int attempts = 0;
    int roundCount = 1;
    
    // Variablen for die Texteingabe
    char guessBuffer[4] = "\0"; 
    int letterCount = 0;
    
    // Feedback-Text for den Spieler
    char feedbackText[60] = "Enter a number and press ENTER!";
    Color feedbackColor = MAROON;
    bool gameWon = false;

    // Hauptspielschleife
    while (!WindowShouldClose()) {
        // --- LOGIK ---
        switch (currentScreen) {
            case SCREEN_MENU: {
                // Tastensteuerung im Hauptmenü
                if (IsKeyPressed(KEY_S) || IsKeyPressed(KEY_ENTER)) {
                    currentScreen = SCREEN_GAME;
                    targetNumber = rand() % 100 + 1;
                    attempts = 0;
                    gameWon = false;
                    letterCount = 0;
                    guessBuffer[0] = '\0';
                    TextCopy(feedbackText, "Enter a number and press ENTER!");
                    feedbackColor = LIGHTGRAY;
                }
                if (IsKeyPressed(KEY_T)) {
                    currentScreen = SCREEN_TUTORIAL;
                }
                if (IsKeyPressed(KEY_R)) {
                    currentScreen = SCREEN_CONFIRM_RESET; // Wechselt zur Bestätigung
                }
            } break;

            case SCREEN_CONFIRM_RESET: {
                // Bestätigungsmenü abfragen
                if (IsKeyPressed(KEY_Y)) { // Y for Yes (Yes)
                    balance = 0;
                    SaveBalance(balance);
                    currentScreen = SCREEN_MENU;
                }
                if (IsKeyPressed(KEY_N) || IsKeyPressed(KEY_ESCAPE)) { // N or ESC for No
                    currentScreen = SCREEN_MENU;
                }
            } break;

            case SCREEN_TUTORIAL: {
                if (IsKeyPressed(KEY_B) || IsKeyPressed(KEY_ESCAPE)) {
                    currentScreen = SCREEN_MENU;
                }
            } break;

            case SCREEN_GAME: {
                if (IsKeyPressed(KEY_ESCAPE)) {
                    currentScreen = SCREEN_MENU;
                }

                if (!gameWon) {
                    // Zeichen-Input for die Zahl (only Tasten 0-9)
                    int key = GetCharPressed();
                    while (key > 0) {
                        if ((key >= '0') && (key <= '9') && (letterCount < 3)) {
                            guessBuffer[letterCount] = (char)key;
                            guessBuffer[letterCount + 1] = '\0';
                            letterCount++;
                        }
                        key = GetCharPressed();
                    }

                    // Backspace zum Löschen einzelner Ziffern
                    if (IsKeyPressed(KEY_BACKSPACE)) {
                        letterCount--;
                        if (letterCount < 0) letterCount = 0;
                        guessBuffer[letterCount] = '\0';
                    }

                    // Auswertung at ENTER-Druck
                    if (IsKeyPressed(KEY_ENTER) && letterCount > 0) {
                        int currentGuess = atoi(guessBuffer);
                        attempts++;
                        balance--; // Jeder Attempt kostet 1$
                        
                        if (currentGuess > targetNumber) {
                            TextCopy(feedbackText, "Too high! Try again.");
                            feedbackColor = RED;
                        } else if (currentGuess < targetNumber) {
                            TextCopy(feedbackText, "Too low! Try again.");
                            feedbackColor = RED;
                        } else {
                            // Gewonnen!
                            TextCopy(feedbackText, "Correct! You win +$8!");
                            feedbackColor = LIME;
                            balance += 8;
                            gameWon = true;
                            SaveBalance(balance); // Sofort in save.txt sichern
                        }
                        
                        // Buffer after dem Tippen leeren
                        guessBuffer[0] = '\0';
                        letterCount = 0;
                    }
                } else {
                    // Wenn die Round gewonnen wurde, startet ein erneuter ENTER-Druck das Game neu
                    if (IsKeyPressed(KEY_ENTER)) {
                        roundCount++;
                        targetNumber = rand() % 100 + 1;
                        attempts = 0;
                        gameWon = false;
                        TextCopy(feedbackText, "New round! Enter a number.");
                        feedbackColor = LIGHTGRAY;
                    }
                }
            } break;
        }

        // --- ZEICHNEN ---
        BeginDrawing();
        ClearBackground(GetColor(0x181818FF)); // Schicker Dark-Mode Hintergrund

        // Permanenter Balance oben rechts (außer im Tutorial and Reset-Bildschirm)
        if (currentScreen != SCREEN_TUTORIAL && currentScreen != SCREEN_CONFIRM_RESET) {
            DrawText(TextFormat("Balance: %d$", balance), screenWidth - 220, 20, 24, GREEN);
        }

        switch (currentScreen) {
            case SCREEN_MENU: {
                DrawText("GUESSING GAME DELUXE", screenWidth/2 - MeasureText("GUESSING GAME DELUXE", 40)/2, 150, 40, GOLD);
                
                DrawText("[S] Start game", screenWidth/2 - MeasureText("[S] Start game", 20)/2, 280, 20, RAYWHITE);
                DrawText("[T] Show tutorial", screenWidth/2 - MeasureText("[T] Show tutorial", 20)/2, 330, 20, RAYWHITE);
                DrawText("[R] Reset balance", screenWidth/2 - MeasureText("[R] Reset balance", 16)/2, 450, 16, RED);
                
                DrawText("Press the corresponding key", screenWidth/2 - MeasureText("Press the corresponding key", 14)/2, 540, 14, GRAY);
            } break;

            case SCREEN_CONFIRM_RESET: {
                // Bestätigungsfenster (Hintergrund bleibt leicht sichtbar verdunkelt)
                DrawText("ARE YOU SURE?", screenWidth/2 - MeasureText("ARE YOU SURE?", 32)/2, 180, 32, RED);
                DrawText("Your entire saved balance will be deleted!", screenWidth/2 - MeasureText("Your entire saved balance will be deleted!", 20)/2, 240, 20, RAYWHITE);
                
                DrawText("[Y] YES, DELETE EVERYTHING", screenWidth/2 - MeasureText("[Y] YES, DELETE EVERYTHING", 20)/2, 340, 20, RED);
                DrawText("[N] NO, CANCEL", screenWidth/2 - MeasureText("[N] NO, CANCEL", 20)/2, 390, 20, LIME);
            } break;

            case SCREEN_TUTORIAL: {
                DrawText("TUTORIAL", screenWidth/2 - MeasureText("TUTORIAL", 30)/2, 80, 30, GOLD);
                
                int startY = 180;
                int spacing = 40;
                DrawText("- The computer chooses a secret number between 1 and 100.", 50, startY, 20, RAYWHITE);
                DrawText("- Each guess costs exactly $1.", 50, startY + spacing, 20, RAYWHITE);
                DrawText("- Guess the number correctly and win $8.", 50, startY + (spacing * 2), 20, RAYWHITE);
                DrawText("- The game tells you whether your guess was too high or too low.", 50, startY + (spacing * 3), 20, RAYWHITE);
                DrawText("- Your balance is saved automatically!", 50, startY + (spacing * 4), 20, GREEN);

                DrawText("[B] Back to main menu", screenWidth/2 - MeasureText("[B] Back to main menu", 20)/2, 480, 20, GOLD);
            } break;

            case SCREEN_GAME: {
                DrawText(TextFormat("Round: %d", roundCount), 40, 20, 24, BLUE);
                DrawText(TextFormat("Attempts: %d", attempts), 40, 50, 20, ORANGE);

                DrawText("Guess the number (1-100):", screenWidth/2 - MeasureText("Guess the number (1-100):", 24)/2, 180, 24, RAYWHITE);

                // Hier ist die korrigierte Raylib-Funktion for das Rechteck:
                DrawRectangleLines(screenWidth/2 - 60, 240, 120, 50, GRAY);
                
                if (letterCount == 0 && !gameWon) {
                    DrawText("???", screenWidth/2 - MeasureText("???", 28)/2, 250, 28, DARKGRAY);
                } else {
                    DrawText(guessBuffer, screenWidth/2 - MeasureText(guessBuffer, 28)/2, 250, 28, RAYWHITE);
                }

                // Feedback-Texte
                DrawText(feedbackText, screenWidth/2 - MeasureText(feedbackText, 20)/2, 340, 20, feedbackColor);

                if (gameWon) {
                    DrawText("Press ENTER for the next round!", screenWidth/2 - MeasureText("Press ENTER for the next round!", 18)/2, 420, 18, GOLD);
                }
                
                DrawText("[ESC] Back to menu", 40, screenHeight - 40, 16, GRAY);
            } break;
        }

        EndDrawing();
    }

    // Fenster schließen and Ressourcen freigeben
    CloseWindow();

    return 0;
}