const int LED_PINS[] = {11, 10, 9, 6, 5, 3};
const int LED_COUNT = 6;

int speed = 0;
int state = 0;
int index = 0;
int brightnessOn = 0;
int brightnessOff = 0;

void handleButtonPress() {
  state = LED_COUNT + 1;
  index = 0;
  brightnessOn = 0;
  brightnessOff = 0;
  turnOffAllLEDs();
}

void setup() {
  for (int i = 0; i < LED_COUNT; i++) {
    pinMode(LED_PINS[i], OUTPUT);
  }
  pinMode(2, INPUT);
  pinMode(A0, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), handleButtonPress, FALLING);
}

void turnOffAllLEDs() {
  for (int i = 0; i < LED_COUNT; i++) {
    analogWrite(LED_PINS[i], 0);
  }
}

void loop() {
  speed = analogRead(A0) / 40 + 10;

  for (index = 0; index < LED_COUNT - state; index++) {
    int currentPin = LED_PINS[index];
    brightnessOn = 10;
    brightnessOff = 10;
    
    if (index > 0) {
      int previousPin = LED_PINS[index - 1];
      fadeOut(previousPin);
    }
    
    fadeIn(currentPin);
  }

  if (state > LED_COUNT) {
    state = 0;
  } else if (state < LED_COUNT) {
    state++;
  }

  delay(speed);
}

void fadeOut(int pin) {
  while (brightnessOff-- > 0) {
    analogWrite(pin, brightnessOff * 25);
    delay(speed);
  }
}

void fadeIn(int pin) {
  while (brightnessOn-- > 0) {
    analogWrite(pin, (10 - brightnessOn) * 25);
    delay(speed);
  }
}