class PlankTimer {
  int duration;
  bool running;
  unsigned long startTime;
  bool beepedAt[3];
  bool beepActive;
  unsigned long beepStartTime;

  public:
    PlankTimer() {
      running = false;
      duration = 0;
      startTime = 0;
      beepActive = false;
      beepStartTime = 0;
      clearBeepedAtArray();
    }

    void update() {
      if (!running) return;
  
      unsigned long elapsedSec = (millis() - startTime) / 1000;
  
      if (elapsedSec < duration) {
        float percentage = (float)elapsedSec / duration;
        int litPixels = round(percentage * LED_COUNT);
  
        for (int i = 0; i < LED_COUNT; i++) {
          if (i < litPixels) {
            strip.setPixelColor(i, strip.Color(0, 150, 0));
          } else {
            strip.setPixelColor(i, 0);
          }
        }
        strip.show();
  
        int timeLeft = duration - elapsedSec;
        if (timeLeft <= 3 && timeLeft >= 1 && !beepedAt[timeLeft - 1]) {
          beepedAt[timeLeft - 1] = true;
          beep();
        }
      } else {
        running = false;
        for (int i = 0; i < LED_COUNT; i++) {
          strip.setPixelColor(i, strip.Color(0, 0, 255)); // Done
        }
        strip.show();
        ledcWriteTone(TONE_PWM_CHANNEL, 1047);
        delay(500);
        ledcWriteTone(TONE_PWM_CHANNEL, 0);
      }

      if (beepActive && millis() - beepStartTime >= 200) {
        ledcWriteTone(TONE_PWM_CHANNEL, 0);
        beepActive = false;
      }
    }
  
    void setDuration(int seconds) {
      duration = seconds;
    }
  
    void start() {
      running = true;
      beepActive = false;
      startTime = millis();
      strip.clear();
      strip.show();
      clearBeepedAtArray();
    }
    
    bool isRunning() {
      return running;
    }

  private:
    void beep() {
      ledcWriteTone(TONE_PWM_CHANNEL, 262);
      beepActive = true;
      beepStartTime = millis();
      delay(200);
      ledcWriteTone(TONE_PWM_CHANNEL, 0);
      delay(1000);
    }

    void clearBeepedAtArray() {
      for (int i = 0; i < 3; i++) {
        beepedAt[i] = false;
      }
    }
};
