/**
 * 实例：导航显示、env 配置、改密、PM2 重启。
 */
(function (global) {
  const DISPLAY = () => global.__INSTANCE_DISPLAY__ || {};

  function setStatus(el, text, isErr) {
    if (!el) return;
    el.textContent = text || "";
    el.classList.toggle("err", !!isErr);
  }

  async function fetchJson(url, opts) {
    const res = await fetch(url, Object.assign({ credentials: "same-origin" }, opts || {}));
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      throw new Error(data.msg || res.statusText || "请求失败");
    }
    return data;
  }

  function applyDisplayToNav(display) {
    const map = {
      strategy: "show_nav_strategy",
      strategy_records: "show_nav_strategy_records",
      records: "show_nav_records",
      stats: "show_nav_stats",
      options: "show_nav_options",
      risk_policy: "show_nav_risk_policy",
      env_config: "show_nav_env_config",
    };
    document.querySelectorAll(".embed-top-nav [data-embed-tab], .top-nav a[href^='/']").forEach((a) => {
      const tab = a.getAttribute("data-embed-tab") || (a.getAttribute("href") || "").replace(/^\//, "").split("?")[0];
      const key = map[tab];
      if (!key) return;
      const show = display[key] !== false;
      a.classList.toggle("nav-hidden", !show);
      a.style.display = show ? "" : "none";
    });
    global.__INSTANCE_DISPLAY__ = display;
  }

  function pageNavAllowed(tab) {
    const d = DISPLAY();
    const map = {
      strategy: "show_nav_strategy",
      strategy_records: "show_nav_strategy_records",
      records: "show_nav_records",
      stats: "show_nav_stats",
      options: "show_nav_options",
      risk_policy: "show_nav_risk_policy",
      env_config: "show_nav_env_config",
    };
    const key = map[tab];
    if (!key) return true;
    return d[key] !== false;
  }

  async function loadDisplayPrefsForm() {
    const pane = document.querySelector('.embed-tab-pane.is-active-pane') || document;
    const root = pane.querySelector ? pane.querySelector("#display-prefs-form") : document.getElementById("display-prefs-form");
    if (!root) {
      const fallback = document.getElementById("display-prefs-form");
      if (!fallback) return;
      return loadDisplayPrefsFormIn(fallback);
    }
    return loadDisplayPrefsFormIn(root);
  }

  async function loadDisplayPrefsFormIn(root) {
    try {
      const data = await fetchJson("/api/settings/display");
      const display = data.display || {};
      const meta = data.meta || [];
      root.innerHTML = "";
      meta.forEach((group) => {
        const section = document.createElement("div");
        section.className = "display-prefs-group";
        const title = document.createElement("h3");
        title.className = "settings-subcard-title";
        title.textContent = group.group;
        section.appendChild(title);
        const grid = document.createElement("div");
        grid.className = "display-prefs-checks";
        (group.keys || []).forEach((item) => {
          const label = document.createElement("label");
          label.className = "chk-label";
          const cb = document.createElement("input");
          cb.type = "checkbox";
          cb.dataset.prefKey = item.key;
          cb.checked = display[item.key] !== false;
          label.appendChild(cb);
          label.appendChild(document.createTextNode(" " + item.label));
          grid.appendChild(label);
        });
        section.appendChild(grid);
        root.appendChild(section);
      });
    } catch (e) {
      root.innerHTML = '<span class="err">' + (e.message || "加载失败") + "</span>";
    }
  }

  async function saveDisplayPrefs() {
    const status = document.getElementById("display-prefs-status");
    const display = {};
    document.querySelectorAll("#display-prefs-form input[data-pref-key]").forEach((cb) => {
      display[cb.dataset.prefKey] = !!cb.checked;
    });
    try {
      const data = await fetchJson("/api/settings/display", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ display }),
      });
      applyDisplayToNav(data.display || display);
      setStatus(status, "已保存，导航已更新");
    } catch (e) {
      setStatus(status, e.message || "保存失败", true);
    }
  }

  let envSchemaGroups = [];

  function renderEnvField(field) {
    const card = document.createElement("div");
    card.className = "env-field-card";
    const label = document.createElement("label");
    label.className = "env-field-label";
    label.textContent = field.key;
    card.appendChild(label);
    if (field.note) {
      const note = document.createElement("div");
      note.className = "env-field-note muted";
      note.textContent = field.note;
      card.appendChild(note);
    }
    let input;
    if (field.type === "bool") {
      input = document.createElement("select");
      ["true", "false"].forEach((v) => {
        const o = document.createElement("option");
        o.value = v;
        o.textContent = v;
        input.appendChild(o);
      });
      const cur = (field.current || field.default || "false").toLowerCase();
      input.value = cur === "true" || cur === "1" ? "true" : "false";
    } else {
      input = document.createElement("input");
      input.type = field.sensitive ? "password" : "text";
      if (field.sensitive && field.has_value) {
        input.placeholder = field.masked || "留空不修改";
      } else {
        input.value = field.current || field.default || "";
      }
    }
    input.dataset.envKey = field.key;
    input.className = "env-field-input";
    card.appendChild(input);
    const badge = document.createElement("span");
    badge.className = "env-field-badge " + (field.restart_required ? "env-badge-restart" : "env-badge-hot");
    badge.textContent = field.restart_required ? "需重启" : "保存即生效";
    card.appendChild(badge);
    return card;
  }

  async function loadEnvConfig() {
    const pane = document.querySelector('.embed-tab-pane.is-active-pane') || document;
    const grid = pane.querySelector ? pane.querySelector("#env-config-grid") : document.getElementById("env-config-grid");
    const target = grid || document.getElementById("env-config-grid");
    if (!target) return;
    return loadEnvConfigIn(target);
  }

  async function loadEnvConfigIn(grid) {
    grid.innerHTML = '<div class="env-config-loading muted">加载配置中…</div>';
    try {
      const data = await fetchJson("/api/settings/env");
      envSchemaGroups = data.groups || [];
      grid.innerHTML = "";
      envSchemaGroups.forEach((group) => {
        const card = document.createElement("div");
        card.className = "card env-group-card";
        const h = document.createElement("h3");
        h.className = "env-group-title";
        h.textContent = group.title || "其他";
        card.appendChild(h);
        const inner = document.createElement("div");
        inner.className = "env-group-fields";
        (group.fields || []).forEach((field) => inner.appendChild(renderEnvField(field)));
        card.appendChild(inner);
        grid.appendChild(card);
      });
    } catch (e) {
      grid.innerHTML = '<span class="err">' + (e.message || "加载失败") + "</span>";
    }
  }

  function collectEnvValues() {
    const values = {};
    document.querySelectorAll(".env-field-input[data-env-key]").forEach((el) => {
      values[el.dataset.envKey] = el.value;
    });
    return values;
  }

  async function saveEnvConfig(restartAfter) {
    const status = document.getElementById("env-config-status");
    setStatus(status, "保存中…");
    try {
      const data = await fetchJson("/api/settings/env", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ values: collectEnvValues() }),
      });
      const needRestart = restartAfter || data.restart_required;
      if (needRestart) {
        setStatus(status, "已保存，正在重启实例…");
        await restartInstance();
        setStatus(status, "保存并重启完成");
        await loadEnvConfig();
      } else {
        setStatus(status, "已保存（即时生效项已应用）");
        await loadEnvConfig();
      }
    } catch (e) {
      setStatus(status, e.message || "保存失败", true);
    }
  }

  async function restartInstance() {
    await fetchJson("/api/admin/restart", { method: "POST" });
    const deadline = Date.now() + 90000;
    while (Date.now() < deadline) {
      await new Promise((r) => setTimeout(r, 2000));
      try {
        const h = await fetch("/api/admin/health", { credentials: "same-origin" });
        if (h.ok) return;
      } catch (_) {}
    }
    throw new Error("重启后服务未在预期时间内恢复");
  }

  async function savePassword() {
    const status = document.getElementById("pwd-save-status");
    const body = {
      old_password: (document.getElementById("pwd-old") || {}).value || "",
      new_username: (document.getElementById("pwd-new-username") || {}).value || "",
      new_password: (document.getElementById("pwd-new") || {}).value || "",
      confirm_password: (document.getElementById("pwd-confirm") || {}).value || "",
    };
    try {
      const data = await fetchJson("/api/settings/password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (data.restart_required) {
        setStatus(status, "密码已保存，正在重启…");
        await restartInstance();
        setStatus(status, "密码已更新，请用新密码登录");
      } else {
        setStatus(status, "密码已更新");
      }
    } catch (e) {
      setStatus(status, e.message || "保存失败", true);
    }
  }

  function bindEvents() {
    const dSave = document.getElementById("display-prefs-save");
    if (dSave) dSave.addEventListener("click", saveDisplayPrefs);
    const eSave = document.getElementById("env-config-save");
    if (eSave) eSave.addEventListener("click", () => saveEnvConfig(false));
    const eRestart = document.getElementById("env-config-save-restart");
    if (eRestart) eRestart.addEventListener("click", () => saveEnvConfig(true));
    const eReload = document.getElementById("env-config-reload");
    if (eReload) eReload.addEventListener("click", loadEnvConfig);
    const pSave = document.getElementById("pwd-save-btn");
    if (pSave) pSave.addEventListener("click", savePassword);
  }

  function initPage() {
    bindEvents();
    if (document.getElementById("display-prefs-form")) loadDisplayPrefsForm();
    if (document.getElementById("env-config-grid")) loadEnvConfig();
    if (global.__INSTANCE_DISPLAY__) applyDisplayToNav(global.__INSTANCE_DISPLAY__);
  }

  global.InstanceSettingsPrefs = {
    pageNavAllowed,
    applyDisplayToNav,
    loadDisplayPrefsForm,
    loadEnvConfig,
    restartInstance,
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initPage);
  } else {
    initPage();
  }
})(typeof window !== "undefined" ? window : globalThis);
