#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>

// Define TFT pins
#define TFT_CS    5
#define TFT_RST   4
#define TFT_DC    16
#define TFT_MOSI  23
#define TFT_SCLK  18
#define TFT_MISO  19

// Define joystick and button pins
#define JOY_X     34
#define JOY_Y     35
#define JOY_SW    27
#define BTN1 25
#define BTN2 32
#define BTN3 26
#define BTN4 33

// Initialize TFT
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);

enum GameState { MENU, PING_PONG, SPACE_INVADER, SNAKE };
GameState gameState = MENU;

void setup() {
  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_BLACK);

  pinMode(BTN1, INPUT_PULLUP);
  pinMode(BTN2, INPUT_PULLUP);
  pinMode(BTN3, INPUT_PULLUP);
  pinMode(BTN4, INPUT_PULLUP);

  drawMenu();
}

void loop() {
  if (gameState == MENU) {
    handleMenu();
  } else if (gameState == PING_PONG) {
    playPingPong();
  } else if (gameState == SPACE_INVADER) {
    playSpaceInvader();
  } else if (gameState == SNAKE) {
    playSnake();
  }
}

void drawMenu() {
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE);
  tft.setTextSize(2);
  tft.setCursor(20, 30);
  tft.println("Select Game:");
  tft.setCursor(20, 60);
  tft.println("1. Ping Pong");
  tft.setCursor(20, 90);
  tft.println("2. Space Invader");
  tft.setCursor(20, 120);
  tft.println("3. Snake");
}

void handleMenu() {
  if (digitalRead(BTN1) == LOW) {
    gameState = PING_PONG;
    tft.fillScreen(TFT_BLACK);
  } else if (digitalRead(BTN2) == LOW) {
    gameState = SPACE_INVADER;
    tft.fillScreen(TFT_BLACK);
  } else if (digitalRead(BTN3) == LOW) {
    gameState = SNAKE;
    tft.fillScreen(TFT_BLACK);
  }
}