#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_SSD1306 display;

unsigned long startMs = 0;
unsigned long stopMs = 0;
float seconds = 0.0;

int buttonState = 0;
int laserState = 0;
bool timerRunning = false;  // New state variable
bool waitForRelease = false;  // New state variable

const int buttonPin = 8;  // Pin where the button is connected

void displayTime(float currentTime, bool pressAgain) {
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.print(currentTime);
  display.print(" sec");

  if (pressAgain) {
    display.setTextSize(1);
    display.setCursor(0, 20);
    display.print("Press to start again!");
  }

  display.display();
}

void setup() {
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  pinMode(buttonPin, INPUT_PULLUP);  // Button pin
  delay(1000);
  displayTime(0.00, false);
}

void loop() {
  laserState = analogRead(3);  // LDR pin
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW && !timerRunning && laserState < 100 && !waitForRelease) {
    // Start the timer only if the button is pressed, the timer is not already running, laser is detected, and not waiting for release
    startMs = millis();
    timerRunning = true;
    waitForRelease = true;
  }

  if (timerRunning) {
    unsigned long currentTime = millis() - startMs;
    seconds = (float)currentTime / 1000;
    displayTime(seconds, false);
  }

  if (timerRunning && (laserState > 100)) {
    // Stop the timer if the laser is no longer detected
    stopMs = millis();
    unsigned long elapsedTime = stopMs - startMs;
    seconds = (float)elapsedTime / 1000;
    displayTime(seconds, true);  // Display "Press again to reset"
    timerRunning = false;
  }

  if (!timerRunning && buttonState == LOW && laserState < 100 && !waitForRelease) {
    // Reset the timer to 0.00 if the button is pressed again when the timer is not running, laser is detected, and not waiting for release
    displayTime(0.00, false);
    waitForRelease = true;
  }

  if (buttonState == HIGH && waitForRelease) {
    // Reset waitForRelease when the button is released
    waitForRelease = false;
  }
}
