#include <Adafruit_CircuitPlayground.h>

#define PUMP_PIN A5  // MOSFET IN connected to CPB pin A5

bool lastButtonState = false;  // Store last button state
bool isHolding = false;  // Track if in 30s holding period

void setup() {
    CircuitPlayground.begin();
    Serial.begin(115200);
    pinMode(PUMP_PIN, OUTPUT);
    digitalWrite(PUMP_PIN, LOW);  // Ensure pump is off at start
    setLEDs(255, 165, 0);  // Set default Orange LED
}

void loop() {
    bool buttonA = CircuitPlayground.leftButton();  // Read built-in Button A

    // Detect button press event (rising edge)
    if (buttonA && !lastButtonState && !isHolding) {  
        Serial.println("\nButton A PRESSED -> Activating Pump");
        testPump();
    }

    // If no button press and not holding, ensure default Orange LED
    if (!buttonA && !isHolding) {
        setLEDs(255, 165, 0);  // Orange
    }

    lastButtonState = buttonA;  // Update button state
    delay(100);  // Short delay for debouncing
}

void testPump() {
    Serial.println("\nPump Activated: Running for 5 seconds...");
    
    setLEDs(0, 255, 0);  // Green LED for pump activation
    digitalWrite(PUMP_PIN, HIGH);  // Turn on pump
    delay(5000);  // Run for 5 seconds
    digitalWrite(PUMP_PIN, LOW);   // Turn off pump

    Serial.println("Holding for 30 seconds...");
    
    isHolding = true;
    setLEDs(128, 0, 128);  // Purple LED for holding period

    for (int i = 30; i > 0; i--) {  // 30-second countdown
        Serial.print(i);
        Serial.print(".. ");
        delay(1000);
    }

    isHolding = false;
    setLEDs(255, 165, 0);  // Return to Orange LED
    Serial.println("\nHolding period over. Ready for next activation.");
}

// Function to set all LEDs to a given color
void setLEDs(int r, int g, int b) {
    for (int i = 0; i < 10; i++) {
        CircuitPlayground.setPixelColor(i, r, g, b);
    }
}
