//#include <LiquidCrystal_I2C.h> // Uncomment this line if you're using an LCD

const int LED1 = 14;
const int LED2 = 32;
const int LED3 = 27; // Changed from 36 to 34 for common GPIO
const int PB1 = 5; // Button pin
const int PB2 = 4;
const int Buzzer = 13;
int ButtonState = 0;
int lastButtonStatePB1 = LOW;
int BuzzerState = 0;
int lastButtonStatePB2 = LOW;
bool countdownActive = false;
unsigned long countdownStart = 0;
const unsigned long countdownDuration = 10000; // 10 seconds

void LED1Flash() {
  digitalWrite(LED1, HIGH);
  delay(1000); // Adjust the delay to control blink duration
  digitalWrite(LED1, LOW);
}

void LED2Flash() {
  digitalWrite(LED2, HIGH);
  delay(1000); // Adjust the delay to control blink duration
  digitalWrite(LED2, LOW);
}

void LED3Flash() {
  digitalWrite(LED3, HIGH);
  delay(1000); // Adjust the delay to control blink duration
  digitalWrite(LED3, LOW);
}

void Buzz() {
  digitalWrite(Buzzer, HIGH);
  delay(100); // Buzzer on duration
  digitalWrite(Buzzer, LOW);
}

void setup() {
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(Buzzer, OUTPUT);
  pinMode(PB1, INPUT);
  pinMode(PB2, INPUT);
}

void loop() {
  ButtonState = digitalRead(PB1);
  BuzzerState = digitalRead(PB2);

  // Check if the button state has changed from LOW to HIGH for PB1
  if (ButtonState == HIGH && lastButtonStatePB1 == LOW) {
    Serial.println("Button pressed");
    LED1Flash(); // Flash LED1 once when the button is pressed

    // Start the countdown
    countdownActive = true;
    countdownStart = millis();
  }

  // Save the current state as the last state for the next loop
  lastButtonStatePB1 = ButtonState;

  // Countdown logic
  if (countdownActive) {
    unsigned long elapsed = millis() - countdownStart;
    unsigned long remaining = countdownDuration - elapsed;
    
    // Print countdown to serial monitor
    Serial.print("Countdown: ");
    Serial.println(remaining / 1000);

    // Flash LEDs sequentially
    LED1Flash();
    delay(1500);
    LED2Flash();
    delay(1500);
    LED3Flash();
    delay(1500);

    if (elapsed >= countdownDuration) {
      countdownActive = false; // End the countdown after 10 seconds
      Serial.println("Countdown finished");
    }
  }

  // Check if the button state has changed from LOW to HIGH for PB2
  if (BuzzerState == HIGH && lastButtonStatePB2 == LOW) {
    Serial.print("Buzzer pressed");
    Buzz(); // Buzz once when the button is pressed
  }

  // Save the current state as the last state for the next loop
  lastButtonStatePB2 = BuzzerState;

  // Small delay to help with debouncing
  delay(10);
}