#include <WiFi.h>
#include <AsyncTCP.h>          
#include <ESPAsyncWebServer.h>


// ================== WiFi Credentials ==================
const char* ssid     = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

// ================== GPIO Pins ==================
static const uint8_t OUTPUT_PIN = 2;   // LED / Relay
static const uint8_t BUTTON_PIN = 13;  // Push button (INPUT_PULLUP)

// ================== Globals ==================
AsyncWebServer server(80);

bool outputState = false;
bool lastButtonState = HIGH;

unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;

// ================== Web Page ==================
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
  <title>QUAD ROBOTICS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      background-color: #f4f4f4;
      padding: 30px;
    }
    h1 { color: #2c3e50; margin-bottom: 0; }
    h4 { color: #7f8c8d; margin-top: 5px; font-weight: normal; }
    .state { font-size: 2em; margin: 30px 0 20px; }
    .toggle-button {
      font-size: 1.5em;
      padding: 12px 25px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      color: white;
    }
    .on { background-color: #27ae60; }
    .off { background-color: #c0392b; }
  </style>
</head>
<body>
  <h1>QUAD ROBOTICS</h1>
  <h4>A unit of Quad Store</h4>

  <div class="state">
    Status: <span id="outputState">...</span>
  </div>

  <button id="toggleBtn" class="toggle-button" onclick="toggleOutput()">
    Loading...
  </button>

  <script>
    function updateUI(state) {
      const btn = document.getElementById("toggleBtn");
      btn.innerText = state === "ON" ? "Turn OFF" : "Turn ON";
      btn.className = "toggle-button " + (state === "ON" ? "on" : "off");
      document.getElementById("outputState").innerText = state;
    }

    function fetchState() {
      fetch("/status")
        .then(res => res.text())
        .then(updateUI);
    }

    function toggleOutput() {
      fetch("/toggle")
        .then(res => res.text())
        .then(updateUI);
    }

    setInterval(fetchState, 1000);
    window.onload = fetchState;
  </script>
</body>
</html>
)rawliteral";

// ================== Setup ==================
void setup() {
  Serial.begin(115200);

  pinMode(OUTPUT_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  digitalWrite(OUTPUT_PIN, LOW);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nConnected!");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // ---------- Web Routes ----------
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send_P(200, "text/html", index_html);
  });

  server.on("/toggle", HTTP_GET, [](AsyncWebServerRequest *request) {
    outputState = !outputState;
    digitalWrite(OUTPUT_PIN, outputState ? HIGH : LOW);
    request->send(200, "text/plain", outputState ? "ON" : "OFF");
  });

  server.on("/status", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", outputState ? "ON" : "OFF");
  });

  server.begin();
}

// ================== Loop ==================
void loop() {
  bool reading = digitalRead(BUTTON_PIN);

  if (reading == LOW &&
      lastButtonState == HIGH &&
      (millis() - lastDebounceTime) > debounceDelay) {

    lastDebounceTime = millis();
    outputState = !outputState;
    digitalWrite(OUTPUT_PIN, outputState ? HIGH : LOW);

    Serial.println(outputState ? "Button -> ON" : "Button -> OFF");
  }

  lastButtonState = reading;
}
