// Plant monitor: small (10-port) board, TWO Soil modules, Screen, Button.
// Two faces side by side, one per plant: happy, thirsty (tongue out) or soaked. Bar under each = moisture.
// Button: tap = big view of plant A / plant B / both · hold 1 s = store "dry" (probes in air) · double tap = store "wet" (probes in water).
// The board's 14 onboard lights follow the thirstier plant: green ok, orange dry, blue soaked.
// Optional Light Grid on port 4: the same as a traffic light, red (thirsty) / amber (getting dry) / green (fine), blue when soaked.
#include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#include "drivers/i2c_software.h"
#include <Preferences.h>
#include "modules/display/st7735_tft.h"
#include "modules/input/button.h"
#ifdef GRID_A
#include "modules/led/neopixel.h"
NeoPixelGrid grid(GRID_A, GRID_B);
#endif

ST7735_TFT   screen(SCR_SCLK, SCR_CS, SCR_MOSI, SCR_DC);
SoftwareI2C  busA(SOILA_SDA, SOILA_SCL), busB(SOILB_SDA, SOILB_SCL);
// The soil modules answer at 0x42 and ignore the register address: every read returns
// [raw lo, raw hi, status, 01, 01]. raw is ~0xFF00 with the prongs in air (open) and drops as the soil gets wetter
// (wet fingers: 0x6300 -> 0x3800). status 0x03 = prongs open, 0x02 = conducting. Read directly, no library.
struct RawSoil {
    SoftwareI2C* bus; uint16_t raw = 0xFF00; uint8_t status = 0; bool present = false;
    explicit RawSoil(SoftwareI2C* b) : bus(b) {}
    bool read() {
        bus->beginTransmission(0x42); bus->write((uint8_t)0);
        if (bus->endTransmission(false) != 0) { present = false; return false; }
        if (bus->requestFrom(0x42, 3) != 3) { present = false; return false; }
        uint8_t lo = bus->read(), hi = bus->read(); status = bus->read();
        raw = lo | (hi << 8); present = true; return true;
    }
};
RawSoil      soilA(&busA), soilB(&busB);
Preferences  prefs;
uint16_t dryRaw = 0xFF00, wetRaw = 0x2000;      // calibration: raw in air / raw in wet soil (button hold / double tap)
static float pctOf(uint16_t raw) { if (dryRaw <= wetRaw) return 0; float p = 100.0f * (float)(dryRaw - raw) / (float)(dryRaw - wetRaw); return constrain(p, 0.0f, 100.0f); }
ButtonModule button(BTN_SW);

static const int LED_PIN = 42, LED_EN = 11, LED_N = 14;
Adafruit_NeoPixel leds(LED_N, LED_PIN, NEO_GRB + NEO_KHZ800);

static const float DRY_BELOW = 30.0f, WET_ABOVE = 75.0f;
enum Mood { THIRSTY, HAPPY, SOAKED, NO_PROBE };
struct Plant { RawSoil* s; bool present; float pct; Mood mood; const char* name; };
Plant plants[2] = { { &soilA, false, 0, NO_PROBE, "A" }, { &soilB, false, 0, NO_PROBE, "B" } };
int view = 0;                 // 0 = both, 1 = A big, 2 = B big
uint32_t lastRead = 0, lastBlink = 0, flashUntil = 0; bool blinking = false; const char* flashMsg = "";

static uint16_t rgb(uint8_t r, uint8_t g, uint8_t b) { return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); }
static uint16_t skinOf(Mood m) { return m == THIRSTY ? rgb(255, 150, 40) : m == SOAKED ? rgb(70, 140, 255) : m == HAPPY ? rgb(90, 200, 90) : rgb(110, 110, 110); }

// A face of radius r at (cx, cy)
void face(int cx, int cy, int r, Mood m, bool blink) {
    uint16_t skin = skinOf(m), ink = ST7735_TFT::COLOR_BLACK;
    screen.fillCircle(cx, cy, r, skin);
    int ex = r * 0.42f, ey = r * 0.28f, er = max(2, r / 6);
    if (blink) { screen.fillRect(cx - ex - er, cy - ey, 2 * er, 2, ink); screen.fillRect(cx + ex - er, cy - ey, 2 * er, 2, ink); }
    else if (m == NO_PROBE) {
        for (int sx : {-ex, ex}) { screen.drawLine(cx + sx - er, cy - ey - er, cx + sx + er, cy - ey + er, ink); screen.drawLine(cx + sx + er, cy - ey - er, cx + sx - er, cy - ey + er, ink); }
    } else { screen.fillCircle(cx - ex, cy - ey, er, ink); screen.fillCircle(cx + ex, cy - ey, er, ink); }
    int my = cy + r * 0.3f, mr = r * 0.38f;
    if (m == HAPPY)        { screen.fillCircle(cx, my, mr, ink); screen.fillCircle(cx, my - max(2, mr / 3), mr, skin); }
    else if (m == THIRSTY) { screen.fillCircle(cx, my + mr, mr, ink); screen.fillCircle(cx, my + mr + max(2, mr / 3), mr, skin); screen.fillRect(cx - mr, my + mr, 2 * mr, mr, skin);
                             screen.fillRoundRect(cx - mr / 3, my + mr / 2, 2 * (mr / 3), mr, 2, rgb(230, 60, 90)); }
    else if (m == SOAKED)  { screen.fillRoundRect(cx - mr / 2, my - 1, mr, mr / 2 + 2, 2, ink); screen.fillCircle(cx + r - 4, cy - r + 6, 3, rgb(140, 200, 255)); }
    else                   { screen.fillRect(cx - mr / 2, my, mr, 2, ink); }
}

void bar(int x, int y, int w, const Plant& p) {
    screen.drawRoundRect(x, y, w, 8, 2, ST7735_TFT::COLOR_WHITE);
    int fill = p.present ? (int)((w - 4) * constrain(p.pct, 0.0f, 100.0f) / 100.0f) : 0;
    if (fill > 0) screen.fillRoundRect(x + 2, y + 2, fill, 4, 1, skinOf(p.mood));
}

const char* wordOf(const Plant& p) { return !p.present ? "no probe" : p.mood == THIRSTY ? "WATER ME" : p.mood == SOAKED ? "too wet" : "happy"; }

void redraw() {
    screen.fillScreen(ST7735_TFT::COLOR_BLACK);
    screen.setTextSize(1);
    if (view == 0) {
        for (int i = 0; i < 2; i++) {
            int cx = 40 + i * 80;
            face(cx, 30, 24, plants[i].mood, blinking);
            bar(cx - 30, 60, 60, plants[i]);
            screen.setTextColor(ST7735_TFT::COLOR_WHITE); screen.setCursor(cx - 30, 70); screen.print(plants[i].name); screen.print(": "); screen.print(wordOf(plants[i]));
        }
        screen.drawLine(80, 4, 80, 76, rgb(60, 60, 60));
    } else {
        const Plant& p = plants[view - 1];
        face(40, 40, 34, p.mood, blinking);
        screen.setTextSize(2); screen.setTextColor(skinOf(p.mood)); screen.setCursor(84, 8); screen.print("plant "); screen.print(p.name);
        screen.setTextSize(1); screen.setTextColor(ST7735_TFT::COLOR_WHITE); screen.setCursor(84, 30); screen.print(wordOf(p));
        bar(84, 44, 70, p);
        screen.setCursor(84, 58); if (p.present) { screen.print("soil "); screen.print((int)p.pct); screen.print("%"); } else screen.print("check port");
        screen.setCursor(84, 70); screen.setTextColor(rgb(120, 120, 120)); screen.print("tap: next view");
    }
    if (millis() < flashUntil) { screen.fillRect(0, 0, 160, 12, rgb(40, 40, 40)); screen.setTextSize(1); screen.setTextColor(ST7735_TFT::COLOR_WHITE); screen.setCursor(4, 2); screen.print(flashMsg); }
    screen.display();
    // onboard lights = the thirstier plant
    Mood worst = HAPPY; for (auto& p : plants) if (p.present) { if (p.mood == THIRSTY) worst = THIRSTY; else if (p.mood == SOAKED && worst != THIRSTY) worst = SOAKED; }
    if (!plants[0].present && !plants[1].present) worst = NO_PROBE;
    uint32_t c = worst == THIRSTY ? leds.Color(60, 25, 0) : worst == SOAKED ? leds.Color(0, 20, 60) : worst == HAPPY ? leds.Color(0, 50, 5) : leds.Color(25, 0, 0);
    for (int i = 0; i < LED_N; i++) leds.setPixelColor(i, c);
    leds.show();
#ifdef GRID_A
    // traffic light on the grid: the thirstier plant's moisture
    float low = 101; for (auto& p : plants) if (p.present && p.pct < low) low = p.pct;
    if (worst == NO_PROBE)      grid.setAll(12, 12, 12);
    else if (worst == SOAKED)   grid.setAll(30, 90, 255);
    else if (worst == THIRSTY)  grid.setAll(255, 40, 30);
    else if (low < DRY_BELOW + 15) grid.setAll(255, 170, 30);
    else                        grid.setAll(40, 220, 70);
    grid.show();
#endif
}

void readSensors() {
    for (auto& p : plants) {
        p.present = p.s->read();
        if (p.present) { p.pct = pctOf(p.s->raw); p.mood = p.pct < DRY_BELOW ? THIRSTY : p.pct > WET_ABOVE ? SOAKED : HAPPY; }
        else p.mood = NO_PROBE;
    }
    Serial.printf("[plant] A: %s raw=%u %.0f%%   B: %s raw=%u %.0f%%   (dry=%u wet=%u)\n", plants[0].present ? "ok" : "--", soilA.raw, plants[0].pct, plants[1].present ? "ok" : "--", soilB.raw, plants[1].pct, dryRaw, wetRaw);
}


void note(const char* m) { flashMsg = m; flashUntil = millis() + 2000; redraw(); Serial.printf("[plant] %s\n", m); }

void setup() {
    Serial.begin(115200); delay(200); Serial.println("[plant] boot");
    pinMode(LED_EN, OUTPUT); digitalWrite(LED_EN, HIGH); leds.begin(); leds.clear(); leds.show();
#ifdef GRID_A
    grid.begin(); grid.clear(); grid.show();
#endif
    screen.begin(); screen.setRotation(1);
    screen.fillScreen(ST7735_TFT::COLOR_BLACK); screen.setTextColor(ST7735_TFT::COLOR_WHITE); screen.setTextSize(2); screen.setCursor(14, 30); screen.print("plant monitor"); screen.display();
    button.begin();
    busA.begin(); busB.begin();
    prefs.begin("plant", false); dryRaw = prefs.getUShort("dry", dryRaw); wetRaw = prefs.getUShort("wet", wetRaw);
    for (auto& p : plants) { bool ok = p.s->read(); Serial.printf("[plant] soil %s on %s: %s\n", p.name, p.name[0] == 'A' ? "port 6" : "port 3", ok ? "found" : "NOT found"); }
    delay(600); readSensors(); redraw();
}

void loop() {
    uint32_t now = millis();
    button.update();
    AtechGesture g = button.getGesture();
    if (g == GESTURE_TAP) { view = (view + 1) % 3; redraw(); }
    // calibration uses plant A's probe: hold = "this is dry" (in air or dry soil), double tap = "this is wet" (just watered)
    if (g == GESTURE_LONG_PRESS) { if (soilA.present) { dryRaw = soilA.raw; prefs.putUShort("dry", dryRaw); note("dry point stored"); } else note("no probe on port 6"); }
    if (g == GESTURE_DOUBLE_TAP) { if (soilA.present) { wetRaw = soilA.raw; prefs.putUShort("wet", wetRaw); note("wet point stored"); } else note("no probe on port 6"); }
    if (now - lastRead > 2000) { lastRead = now; readSensors(); redraw(); }
    if (!blinking && now - lastBlink > 4000) { blinking = true; lastBlink = now; redraw(); }
    if (blinking && now - lastBlink > 150) { blinking = false; redraw(); }
    if (flashUntil && now > flashUntil) { flashUntil = 0; redraw(); }
    delay(10);
}
