#include <TM1637Display.h>
#define CLK 3
#define DT 4
#define SW 2
#define CLK_DISPLAY 5
#define DIO 6
TM1637Display display(CLK_DISPLAY, DIO);

class Astratimer {
private:
  int _countDelay;
  unsigned long _previousMillis;
public:
  Astratimer(int countDelay) : _countDelay(countDelay), _previousMillis(0) {}
  bool canExecute() {
    if (millis() - _previousMillis >= _countDelay) {
      _previousMillis = millis();
      return true;
    }
    return false;
  }
};
Astratimer tim1(1000);
Astratimer tim2(500);
bool lastLed = true;

int counter = 0;
int interval = 20;
volatile int menuState = -1;
int leds[] = {7,8,9,10,11,12};

void displayNumber(int num) {
  display.showNumberDec(num, true);
}

void toggleMenu() {
  menuState *= -1;
}

void countDown() {
  if (counter > 0) {
    counter--;
    displayNumber(counter);
    if(counter > 3){
      int ledn = map(counter, 1, interval, 6,-1);
      digitalWrite(leds[ledn-1], LOW);
    }
    else{
          for(int i=0; i<6; i++){
      digitalWrite(leds[i], LOW);
    }
    }



  } else {
    counter = interval;
    displayNumber(counter);
    for(int i=0; i<6; i++){
      digitalWrite(leds[i], HIGH);
    }
  }
}

void setup() {

  for(int i=0; i<6; i++){
    pinMode(leds[i], OUTPUT);
  }
  pinMode(CLK, INPUT);
  pinMode(DT, INPUT);
  pinMode(SW, INPUT_PULLUP);
  pinMode(14, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(SW), toggleMenu, FALLING);

  Serial.begin(9600);
  display.setBrightness(1);
  display.clear();
}

void loop() {
  static int lastStateCLK = digitalRead(CLK);
  int currentStateCLK = digitalRead(CLK);

  if (menuState == 1) {
    if (currentStateCLK != lastStateCLK && currentStateCLK == 1) {
      if (digitalRead(DT) != currentStateCLK) {
        interval--;
        if (interval < 10) interval = 10;
      } else {
        interval++;
        if (interval > 60) interval = 60;
      }
          for(int i=0; i<6; i++){
      digitalWrite(leds[i], HIGH);
    }
      displayNumber(interval);
      counter = interval;
    }
    lastStateCLK = currentStateCLK;
  } else {
    if (tim1.canExecute()) {
      countDown();
    }
    if(counter < 3){
        if(tim2.canExecute()){
        digitalWrite(leds[5], !digitalRead(leds[5]));
        
        //digitalWrite(13, !digitalRead(13));
      }
    }
    if(counter == 1){
        tone(14, 261, 500);
    }
  }
}
4-Digit Display