var SettingsPage = (function () {
  "use strict";

  function showMsg(elId, text, isErr) {
    var el = document.getElementById(elId);
    if (!el) return;
    el.textContent = text;
    el.classList.remove("hidden");
    el.classList.remove("text-red-400", "text-cyan-400");
    el.classList.add(isErr ? "text-red-400" : "text-cyan-400");
  }

  function loadTelegram() {
    fetch("/api/admin/telegram-settings", { credentials: "same-origin" })
      .then(function (res) {
        if (!res.ok) throw new Error("forbidden");
        return res.json();
      })
      .then(function (data) {
        document.getElementById("tg-chat-id").value = data.chat_id || "";
        document.getElementById("tg-notify-enabled").checked =
          data.notify_enabled !== false;
        var hint = document.getElementById("tg-token-hint");
        if (data.token_configured && data.token_masked) {
          hint.textContent =
            "Huidige token: " +
            data.token_masked +
            " — vul alleen hieronder in om te wijzigen.";
        } else {
          hint.textContent = "Nog geen bot token ingesteld.";
        }
        document.getElementById("tg-bot-token").value = "";
      })
      .catch(function () {
        showMsg("settings-msg", "Kon Telegram-instellingen niet laden.", true);
      });
  }

  function loadAntibot() {
    fetch("/api/admin/antibot-settings", { credentials: "same-origin" })
      .then(function (res) {
        if (!res.ok) throw new Error("forbidden");
        return res.json();
      })
      .then(function (data) {
        document.getElementById("ab-enabled").checked = !!data.enabled;
        var hint = document.getElementById("ab-key-hint");
        if (data.api_key_configured && data.api_key_masked) {
          hint.textContent =
            "Huidige API key: " +
            data.api_key_masked +
            " — vul alleen hieronder in om te wijzigen.";
        } else {
          hint.textContent = "Geen API key — antibot blijft uit tot je er een instelt.";
        }
        document.getElementById("ab-api-key").value = "";
      })
      .catch(function () {
        showMsg("antibot-msg", "Kon antibot-instellingen niet laden.", true);
      });
  }

  function saveTelegram() {
    var chat = document.getElementById("tg-chat-id").value.trim();
    var token = document.getElementById("tg-bot-token").value.trim();
    var body = {
      chat_id: chat,
      notify_enabled: document.getElementById("tg-notify-enabled").checked,
    };
    if (token) body.bot_token = token;
    fetch("/api/admin/telegram-settings", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify(body),
    })
      .then(function (res) {
        return res.json().then(function (data) {
          return { ok: res.ok, data: data };
        });
      })
      .then(function (o) {
        if (o.ok) {
          showMsg("settings-msg", "Telegram opgeslagen.", false);
          document.getElementById("tg-bot-token").value = "";
          loadTelegram();
        } else {
          showMsg("settings-msg", o.data.message || "Opslaan mislukt", true);
        }
      })
      .catch(function () {
        showMsg("settings-msg", "Netwerkfout.", true);
      });
  }

  function saveAntibot() {
    var key = document.getElementById("ab-api-key").value.trim();
    var body = {
      enabled: document.getElementById("ab-enabled").checked,
    };
    if (key) body.api_key = key;
    fetch("/api/admin/antibot-settings", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify(body),
    })
      .then(function (res) {
        return res.json().then(function (data) {
          return { ok: res.ok, data: data };
        });
      })
      .then(function (o) {
        if (o.ok) {
          showMsg("antibot-msg", "Antibot opgeslagen.", false);
          document.getElementById("ab-api-key").value = "";
          loadAntibot();
        } else {
          showMsg("antibot-msg", o.data.message || "Opslaan mislukt", true);
        }
      })
      .catch(function () {
        showMsg("antibot-msg", "Netwerkfout.", true);
      });
  }

  function testMsg(mode) {
    fetch("/api/admin/telegram-test", {
      method: "POST",
      credentials: "same-origin",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ mode: mode || "full" }),
    })
      .then(function (res) {
        return res.json().then(function (data) {
          return { ok: res.ok, data: data };
        });
      })
      .then(function (o) {
        if (o.ok && o.data.success) {
          if (o.data.mode === "ping") {
            showMsg("settings-msg", "Ping verzonden.", false);
          } else {
            showMsg(
              "settings-msg",
              "Volledige flow-test verzonden (alle stappen + bestanden).",
              false
            );
          }
        } else {
          showMsg(
            "settings-msg",
            "Test mislukt — controleer token, chat ID en of notificaties aan staan.",
            true
          );
        }
      })
      .catch(function () {
        showMsg("settings-msg", "Test mislukt.", true);
      });
  }

  function bind() {
    var saveBtn = document.getElementById("tg-save-btn");
    if (saveBtn) saveBtn.addEventListener("click", saveTelegram);
    var testBtn = document.getElementById("tg-test-btn");
    if (testBtn)
      testBtn.addEventListener("click", function () {
        testMsg("full");
      });
    var pingBtn = document.getElementById("tg-ping-btn");
    if (pingBtn)
      pingBtn.addEventListener("click", function () {
        testMsg("ping");
      });
    var abSave = document.getElementById("ab-save-btn");
    if (abSave) abSave.addEventListener("click", saveAntibot);
  }

  function onAuthed() {
    bind();
    loadTelegram();
    loadAntibot();
  }

  return { onAuthed: onAuthed };
})();
