#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

byte rowPins[ROWS] = {9, 8, 7, 6}; 
byte colPins[COLS] = {5, 4, 3};    

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

int numeroSecreto;
String intento = "";
int vidas = 7;
bool juegoTerminado = false;

void setup() {
  lcd.init();        
  lcd.backlight();   
  lcd.clear();
  iniciarJuego();
}

void iniciarJuego() {
  randomSeed(analogRead(0)); 
  numeroSecreto = random(1, 100);
  vidas = 7;
  intento = "";
  juegoTerminado = false;
  
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("NUEVO JUEGO!");
  lcd.setCursor(0, 1);
  lcd.print("Tienes 7 vidas");
  delay(2500);
  
  // ACÁ ESTÁ LA CORRECCIÓN: Frase más corta para no pisar las vidas
  actualizarInterfaz("Rango: 1-99");
}

void actualizarInterfaz(String pista) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(pista);
  
  // Dibuja las vidas en la esquina derecha (espacios 13, 14 y 15)
  lcd.setCursor(13, 0);
  lcd.print("V:");
  lcd.print(vidas);
  
  // Dibuja el cursor para escribir abajo
  lcd.setCursor(0, 1);
  lcd.print("> ");
}

void loop() {
  char key = keypad.getKey();
  
  if (key) {
    if (juegoTerminado) {
      if (key == '#') {
        iniciarJuego();
      }
      return; 
    }

    if (key >= '0' && key <= '9' && intento.length() < 2) {
      intento += key;
      lcd.setCursor(2, 1);
      lcd.print(intento); 
    } 
    
    else if (key == '#') { 
      if (intento == "") return; 

      int numeroIngresado = intento.toInt();
      vidas--; 
      
      if (numeroIngresado == numeroSecreto) {
        juegoTerminado = true;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("!GANASTE! :D");
        lcd.setCursor(0, 1);
        int usados = 7 - vidas;
        lcd.print("En " + String(usados) + " intentos!");
      } 
      else if (vidas == 0) {
        juegoTerminado = true;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("GAME OVER :(");
        lcd.setCursor(0, 1);
        lcd.print("Era el num " + String(numeroSecreto));
      } 
      else if (numeroIngresado < numeroSecreto) {
        actualizarInterfaz("Sube! > " + String(numeroIngresado));
        intento = ""; 
      } 
      else {
        actualizarInterfaz("Baja! < " + String(numeroIngresado));
        intento = ""; 
      }
    } 
    
    else if (key == '*') { 
      intento = "";
      lcd.setCursor(2, 1);
      lcd.print("  "); 
    }
  }
}
