void setup()
{
  Serial.begin( 115200 );
}

void loop()
{
  uint32_t currentMillis = millis();
  static uint32_t timerStarted = 0;

  uint16_t currentValue = analogRead(A0);
  static uint16_t previousValue = currentValue;

  if ( currentValue != 0 && currentValue != 1023 ) // just for wokwi because sometimes it jumps to pot limits when moved with mouse
  {
    if ( previousValue != currentValue )
    {
      previousValue = currentValue;

      if ( currentValue > 52 && currentValue < 512 )
      {
        if ( timerStarted == 0 )
        {
          Serial.println( "LED on" );
          digitalWrite( LED_BUILTIN, HIGH );
        }

        timerStarted = currentMillis;
      }
      else if ( timerStarted )
      {
        timerStarted = 0;
        Serial.println( "LED off (out of range)" );
        digitalWrite( LED_BUILTIN, LOW );
      }
    }
  }

  if ( timerStarted && currentMillis - timerStarted >= 3000 )
  {
    timerStarted = 0;
    Serial.println( "LED off (timer finished)" );
    digitalWrite( LED_BUILTIN, LOW );
  }
}