#include <Seeed_Arduino_SSCMA.h>      // Grove Vision AI V2 inference
#include <Adafruit_NeoPixel.h>       // WS2812 control

// —— Configuration —— 
#define LED_PIN        D2            // XIAO ESP32 pin connected to WS2812 DIN
#define LED_COUNT      10            // number of LEDs in your strip
#define WARM_WHITE_R   255           // warm white RGB
#define WARM_WHITE_G   244
#define WARM_WHITE_B   229
#define DEEP_RED_R     128           // deep red RGB
#define DEEP_RED_G     0
#define DEEP_RED_B     0
#define DETECT_DELAY   10000UL       // 10 seconds

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
SSCMA Infer;

unsigned long phoneSeenAt = 0;
bool isInRedState = false;

// helper: set all LEDs to one color immediately
void fillColor(uint8_t r, uint8_t g, uint8_t b) {
  for (uint16_t i = 0; i < LED_COUNT; i++) {
    strip.setPixelColor(i, r, g, b);
  }
  strip.show();
}

// helper: smooth fade from (r0,g0,b0) to (r1,g1,b1)
void smoothTransition(uint8_t r0, uint8_t g0, uint8_t b0,
                      uint8_t r1, uint8_t g1, uint8_t b1) {
  const int steps = 100;
  for (int i = 0; i <= steps; i++) {
    float t = i / float(steps);
    uint8_t r = r0 + t * (r1 - r0);
    uint8_t g = g0 + t * (g1 - g0);
    uint8_t b = b0 + t * (b1 - b0);
    fillColor(r, g, b);
    delay(20);  // total fade ≈ (steps × 20 ms) = 2 s
  }
}

void setup() {
  Serial.begin(115200);
  // start AI module
  if (!Infer.begin()) {
    Serial.println("Failed to init Grove Vision AI V2!");
    while (1);
  }
  // start LED strip
  strip.begin();
  strip.show();
  // initial state: warm white
  fillColor(WARM_WHITE_R, WARM_WHITE_G, WARM_WHITE_B);
}

void loop() {
  // invoke inference
  if (!Infer.invoke()) {
    size_t n = Infer.boxes().size();
    bool phoneDetected = (n > 0);

    if (phoneDetected) {
      // first detection → record timestamp
      if (phoneSeenAt == 0) {
        phoneSeenAt = millis();
      }
      // if still detected after delay, transition to red
      else if (!isInRedState && millis() - phoneSeenAt >= DETECT_DELAY) {
        smoothTransition(
          WARM_WHITE_R, WARM_WHITE_G, WARM_WHITE_B,
          DEEP_RED_R,   DEEP_RED_G,   DEEP_RED_B
        );
        isInRedState = true;
        Serial.println("→ RED");
      }
    } else {
      // phone gone → reset timer
      phoneSeenAt = 0;
      // if we were red, fade back to warm white
      if (isInRedState) {
        smoothTransition(
          DEEP_RED_R,   DEEP_RED_G,   DEEP_RED_B,
          WARM_WHITE_R, WARM_WHITE_G, WARM_WHITE_B
        );
        isInRedState = false;
        Serial.println("→ WARM WHITE");
      }
    }
  }
  delay(200);  // small pause between inferences
}
