#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
// ---------- CONFIGURACIÓN AUTOMÁTICA ----------
// ⚠️ Cambiar a true si usas hardware real
#define MODO_REAL false  // false = Wokwi, true = ESP32 físico
// Red WiFi (usa red 2.4 GHz, no 5GHz)
const char* ssid_real = "CELERITY_AYALA_5GHZ";
const char* pass_real = "Alfonsina1981";
const char* ssid_wokwi = "Wokwi-GUEST";
const char* pass_wokwi = "";
// IP y puerto de tu PC con Node-RED (solo aplica en modo real)
const char* node_red_host = "192.168.1.68";
const int node_red_port = 1880;
// Web server en puerto 80
WebServer server(80);
// Simulación de sensores
int fakeMotion = 0;
int fakeGas = 0;
// Página web simulada (sin cámara real)
String fakeCameraPage() {
  return "<html><body><h1>📷 Imagen simulada</h1><p>ESP32-CAM sin cámara real (modo Wokwi).</p></body></html>";
}
// Enviar datos a Node-RED
void sendData(String path, String value) {
  WiFiClient client;
  String url = "/api/" + path + "?value=" + value;
  if (client.connect(node_red_host, node_red_port)) {
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + node_red_host + "\r\n" +
                 "Connection: close\r\n\r\n");
    Serial.println("🔄 Enviado a Node-RED → " + url);
    client.stop();
  } else {
    Serial.println("❌ Error al conectar con Node-RED");
  }
}
void handleRoot() {
  server.send(200, "text/html", fakeCameraPage());
}
void setup() {
  Serial.begin(115200);
  delay(1000);
  const char* ssid = MODO_REAL ? ssid_real : ssid_wokwi;
  const char* password = MODO_REAL ? pass_real : pass_wokwi;
  Serial.print("🔌 Conectando a WiFi ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  int intentos = 0;
  while (WiFi.status() != WL_CONNECTED && intentos < 20) {
    delay(500);
    Serial.print(".");
    intentos++;
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\n✅ WiFi conectado");
    Serial.print("🌐 Dirección IP: ");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("\n❌ No se pudo conectar. Verifica SSID/clave/red 2.4GHz");
    return;
  }
  server.on("/", handleRoot);
  server.begin();
  Serial.println("🚀 Servidor web iniciado en /");
}
void loop() {
  server.handleClient();
  fakeMotion = !fakeMotion;
  fakeGas = random(0, 2);
  if (MODO_REAL) {
    sendData("motionDetectAlert", String(fakeMotion));
    sendData("gasDetectAlert", String(fakeGas));
  }
  Serial.print("👁️ Movimiento: ");
  Serial.print(fakeMotion);
  Serial.print(" | 🔥 Gas: ");
  Serial.println(fakeGas);
  delay(5000);
}