#include <Adafruit_NeoPixel.h>

#define LED_PIN    2         // Pin where WS2812B strip is connected
#define LED_COUNT  8         // Number of LEDs in the strip
#define THROTTLE_PIN A0      // Analog pin for simulated throttle input

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  Serial.begin(9600); // Initialize serial communication for debugging
  strip.begin();
  strip.show();       // Initialize all LEDs to an off state
}

void loop() {
  int throttleValue = analogRead(THROTTLE_PIN); // Read the throttle input from the potentiometer/slider
  int throttlePercentage = map(throttleValue, 0, 1023, 0, 100); // Map throttle to 0-100%

  Serial.print("Throttle Percentage: ");
  Serial.println(throttlePercentage);

  // Control WS2812B strip based on throttle input
  if (throttlePercentage < 50) {
    int redSegmentLength = map(throttlePercentage, 0, 49, LED_COUNT, 0); // Reverse mapping for red segment length

    // Code for red segments starting from the left
    for (int i = 0; i < LED_COUNT; i++) {
      if (i < redSegmentLength) {
        strip.setPixelColor(i, strip.Color(127, 0, 0)); // Red at half brightness for LEDs within the red segment length
      } else {
        strip.setPixelColor(i, strip.Color(0, 0, 0)); // Turn off LEDs beyond the red segment
      }
    }
    strip.show(); // Update the LED strip
  } else {
    int throttleAbove50 = throttlePercentage - 50;
    int segment = throttleAbove50 / 12.5;

    // Turn off all LEDs before specifying the segments
    for (int i = 0; i < LED_COUNT; i++) {
      strip.setPixelColor(i, strip.Color(0, 0, 0));
    }

    // Code for green segments...
    if (segment > 0) {
      int greenSegmentLength = map(throttleAbove50, 0, 49, 0, LED_COUNT); // Map the green segment length based on throttleAbove50
      for (int i = 0; i < greenSegmentLength; i++) {
        strip.setPixelColor(i, strip.Color(0, 127, 0)); // Green at half brightness for LEDs within the green segment length
      }
    }

    // Set blue as neutral for only the last two LEDs at half brightness when throttle is above 50 but not in the green segment
    if (throttlePercentage >= 50 && segment == 0) {
      strip.setPixelColor(6, strip.Color(0, 0, 127)); // Blue at half brightness for LED 7
      strip.setPixelColor(7, strip.Color(0, 0, 127)); // Blue at half brightness for LED 8
    }
    strip.show(); // Update the LED strip
  }
}