#include "AppGlobals.h"
#include "Helpers.h"
#include "WebUi.h"
#include "MqttArrival.h"
#include "WebPages.h"

void setup() {
  Serial.begin(115200);
  delay(200);
  Serial.println();
  Serial.println(F("NodeMCU Ankomsttavle v1.3 starter"));
  loadConfig();

  Wire.begin(D2, D1);
  if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println(F("SSD1306 allocation failed"));
  }
  for (uint8_t i = 0; i < MAX_TRACKS; i++) { trackTrain[i] = "."; trackFrom[i] = "."; trackTime[i] = "."; }
  updateDisplay();

  connectWifiOrPortal();
  if (!portalMode && WiFi.isConnected()) { MDNS.begin(cfg.hostname); MDNS.addService("http", "tcp", 80); }
  setupMqtt();
  startWeb();
  logHealth("setup done");
}

void loop() {
  if (portalMode) dnsServer.processNextRequest();
  server.handleClient();
  if (!portalMode) MDNS.update();
  if (!portalMode && WiFi.status() != WL_CONNECTED && millis() - lastWifiAttempt > 10000) {
    lastWifiAttempt = millis();
    WiFi.begin(cfg.wifiSsid, cfg.wifiPassword);
  }
  connectMqttNonBlocking();
  mqtt.loop();
  if (millis() - lastDisplayUpdate > cfg.displayIntervalMs) updateDisplay();
  logHealthTimed();
}
