// ============================================================
//  Lotus Meditation — Arduino
//  TTP223B touch sensor + NeoPixel Ring 16
//  Web Serial API: receives brightness (0-255) from p5.js
//                  sends touch state (T1 / T0) to p5.js
// ============================================================

#include <Adafruit_NeoPixel.h>

#define LED_PIN     6
#define LED_COUNT   16
#define TOUCH_PIN   2

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

int  lastTouch     = -1;
int  currentBright = 0;
int  targetBright  = 0;

String inputBuffer = "";

void setup() {
  Serial.begin(9600);
  pinMode(TOUCH_PIN, INPUT);

  strip.begin();
  strip.setBrightness(255);
  strip.show();
  strip.gamma32(strip.Color(255,255,255));
}

void loop() {

  // ----------------------------------------------------------
  //  READ brightness from p5.js
  //  format: "B###\n"  e.g. "B128\n"
  // ----------------------------------------------------------
  while (Serial.available() > 0) {
    char c = (char)Serial.read();
    if (c == '\n') {
      if (inputBuffer.startsWith("B")) {
        targetBright = inputBuffer.substring(1).toInt();
        targetBright = constrain(targetBright, 0, 255);
      }
      inputBuffer = "";
    } else {
      inputBuffer += c;
    }
  }

  // ----------------------------------------------------------
  //  SMOOTH LED toward targetBright
  // ----------------------------------------------------------
  if (currentBright < targetBright) {
    currentBright = min(currentBright + 2, targetBright);
  } else if (currentBright > targetBright) {
    currentBright = max(currentBright - 2, targetBright);
  }

  // off-white warm glow  R:255 G:248 B:235
  int r = map(currentBright, 0, 255,   0, 255);
  int g = map(currentBright, 0, 255,   0, 210);
  int b = map(currentBright, 0, 255,   0, 130);

  for (int i = 0; i < LED_COUNT; i++) {
    uint32_t color =
  strip.gamma32(
    strip.Color(r,g,b)
  );

strip.setPixelColor(i, color);
  }
  strip.show();

  // ----------------------------------------------------------
  //  SEND touch state to p5.js
  //  format: "T1\n" = touched,  "T0\n" = released
  // ----------------------------------------------------------
  int touch = digitalRead(TOUCH_PIN);
  if (touch != lastTouch) {
    Serial.print("T");
    Serial.println(touch);
    lastTouch = touch;
  }

  delay(20);
}
