#define LASER_PIN 4
#define BUTTON_PIN 7
#define SENSOR_PIN A0
#define RED_LED_PIN 9
#define GREEN_LED_PIN 8
#define BUZZER_PIN 2

#define THRESHOLD 980
#define BLINK_INTERVAL 250
#define BUZZER_INTERVAL 5
#define BUZZER_MIN_FREQ 600
#define BUZZER_MAX_FREQ 1800
#define BUZZER_FREQ_STEP 5

void setup() {
  pinMode(LASER_PIN, OUTPUT);
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(GREEN_LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT);
}

void loop() {
  static bool enabled = false;
  static bool alarm = false;

  if (digitalRead(BUTTON_PIN)) {
    enabled = !enabled;
    alarm = false;
    digitalWrite(RED_LED_PIN, LOW);
    digitalWrite(LASER_PIN, enabled);
    digitalWrite(GREEN_LED_PIN, enabled);
    noTone(BUZZER_PIN);
    delay(200);
  }

  if (!enabled) {
    return;
  }

  if (alarm) {
    unsigned long currentTime = millis();
    updateLed(currentTime);
    updateBuzzer(currentTime);
    return;
  }

  if (analogRead(SENSOR_PIN) < THRESHOLD) {
    digitalWrite(LASER_PIN, LOW);
    digitalWrite(GREEN_LED_PIN, LOW);
    alarm = true;
  }
}

void updateLed(unsigned long time) { 
  static unsigned long lastTime = 0;

  if (time - lastTime >= BLINK_INTERVAL) {
    digitalWrite(RED_LED_PIN, !digitalRead(RED_LED_PIN));
    lastTime = time;
  }
}

void updateBuzzer(unsigned long time) {
  static unsigned long lastTime = 0;
  static int frequency = BUZZER_MIN_FREQ;
  static int direction = 1;

  if (time - lastTime >= BUZZER_INTERVAL) {
    frequency += direction * BUZZER_FREQ_STEP;

    if (frequency <= BUZZER_MIN_FREQ || frequency >= BUZZER_MAX_FREQ) {
      direction *= -1;
    }

    tone(BUZZER_PIN, frequency);
    lastTime = time;
  }
}
