#include WiFi.h>
#include esp_now.h>
#include esp_wifi.h>

// =====================
// CONFIG
// =====================
const int buttonPin = 0;   // BOOT button on many ESP32 DevKit boards
bool lastButtonState = HIGH;

// MAC address of ESP32-C3-Zero
uint8_t c3Address[] = {0xAC, 0xA7, 0x04, 0xBD, 0xD6, 0x28};

// Shared message structure
typedef struct struct_message {
  char command[16];
  int value;
} struct_message;

struct_message outgoingMessage;
struct_message incomingMessage;

// =====================
// CALLBACKS
// =====================
void onDataSent(const wifi_tx_info_t *info, esp_now_send_status_t status) {
  Serial.print("Send status: ");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Success" : "Fail");
}

void onDataRecv(const esp_now_recv_info_t *info, const uint8_t *incomingData, int len) {
  memcpy(&incomingMessage, incomingData, sizeof(incomingMessage));

  Serial.print("Received command: ");
  Serial.print(incomingMessage.command);
  Serial.print(" | value: ");
  Serial.println(incomingMessage.value);

  if (strcmp(incomingMessage.command, "ACK") == 0) {
    Serial.println("ACK received from ESP32-C3");
  }
}

// =====================
// SETUP
// =====================
void setup() {
  Serial.begin(115200);
  delay(1000);

  pinMode(buttonPin, INPUT_PULLUP);

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();

  // Force same WiFi channel on both boards
  esp_wifi_set_promiscuous(true);
  esp_wifi_set_channel(1, WIFI_SECOND_CHAN_NONE);
  esp_wifi_set_promiscuous(false);

  Serial.println("ESP32 DevKit V1 - ESP-NOW Sender/Receiver");
  Serial.print("My MAC address: ");
  Serial.println(WiFi.macAddress());

  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  esp_now_register_send_cb(onDataSent);
  esp_now_register_recv_cb(onDataRecv);

  esp_now_peer_info_t peerInfo = {};
  memcpy(peerInfo.peer_addr, c3Address, 6);
  peerInfo.channel = 1;
  peerInfo.encrypt = false;

  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }

  Serial.println("Peer added successfully");
  Serial.println("Press BOOT to send TRIGGER");
}

// =====================
// LOOP
// =====================
void loop() {
  bool currentButtonState = digitalRead(buttonPin);

  // Detect button press (active LOW)
  if (lastButtonState == HIGH && currentButtonState == LOW) {
    Serial.println("BOOT pressed -> sending TRIGGER");

    strcpy(outgoingMessage.command, "TRIGGER");
    outgoingMessage.value = 1;

    esp_err_t result = esp_now_send(c3Address, (uint8_t *)&outgoingMessage, sizeof(outgoingMessage));

    if (result == ESP_OK) {
      Serial.println("TRIGGER sent");
    } else {
      Serial.print("Error sending TRIGGER: ");
      Serial.println(result);
    }

    delay(250); // simple debounce
  }

  lastButtonState = currentButtonState;
}