const int buttonPin = 4;

int lastButtonState = LOW;
int buttonState = LOW;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;

// For triple press detection
int pressCount = 0;
unsigned long firstPressTime = 0;
const unsigned long pressWindow = 3000; // 3 seconds

// For toggle switch
bool toggleState = false;

void setup() 
{
  Serial.begin(115200);
  Serial.println("Press the button.");
  pinMode(buttonPin, INPUT);
}

void loop() 
{
  int reading = digitalRead(buttonPin);

  // Debounce check
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;

      // Detect rising edge (button press)
      if (buttonState == HIGH) {
        // Serial.println("The button is pressed.");

        // --- Toggle Logic ---
        toggleState = !toggleState;
        if (toggleState) {
          Serial.println("ON");
        } else {
          Serial.println("OFF");
        }

        // --- Triple Press Logic ---
        unsigned long now = millis();

        // First press starts the timer
        if (pressCount == 0) {
          firstPressTime = now;
        }

        pressCount++;

        // Check for triple press within the time window
        if (pressCount == 3 && (now - firstPressTime <= pressWindow)) {
          Serial.println("Clear screen");
          pressCount = 0; // Reset after success
        }

        // If time window expired, reset counter
        if (now - firstPressTime > pressWindow) {
          pressCount = 1; // This is the new first press
          firstPressTime = now;
        }
      }

      if (buttonState == LOW) {
        // Serial.println("The button is released.");
      }
    }
  }

  lastButtonState = reading;
}