"use strict";

(() => {
  const configuredBase = String(globalThis.YILIAN_CLOUD_CONFIG?.apiBaseUrl || "").replace(/\/$/, "");
  const apiBase = location.protocol === "chrome-extension:"
    ? (configuredBase || "http://127.0.0.1:8001/api")
    : `${location.origin}/api`;
  const overlay = document.createElement("div");
  overlay.id = "systemUpdateNotice";
  overlay.className = "system-update-overlay";
  overlay.hidden = true;
  overlay.setAttribute("role", "alertdialog");
  overlay.setAttribute("aria-live", "assertive");
  overlay.innerHTML = `<section class="system-update-card">
    <div class="system-update-icon" aria-hidden="true">↻</div>
    <div class="system-update-copy">
      <h2 id="systemUpdateTitle">程序即将更新</h2>
      <p id="systemUpdateMessage">程序 30 秒后开始更新，请保存当前操作内容。</p>
      <div class="system-update-progress"><i id="systemUpdateProgress"></i></div>
      <strong id="systemUpdateCountdown">30 秒</strong>
    </div>
  </section>`;
  document.body.appendChild(overlay);

  const title = overlay.querySelector("#systemUpdateTitle");
  const message = overlay.querySelector("#systemUpdateMessage");
  const countdown = overlay.querySelector("#systemUpdateCountdown");
  const progress = overlay.querySelector("#systemUpdateProgress");
  let observedUpdate = false;
  let startsAt = 0;
  let reloadScheduled = false;

  function show() {
    overlay.hidden = false;
    document.body.classList.add("system-update-active");
  }

  function renderCountdown() {
    if (!startsAt) return;
    const remaining = Math.max(0, Math.ceil(startsAt - Date.now() / 1000));
    const elapsed = Math.min(30, Math.max(0, 30 - remaining));
    progress.style.width = `${Math.round((elapsed / 30) * 100)}%`;
    if (remaining > 0) {
      countdown.textContent = `${remaining} 秒`;
      return;
    }
    title.textContent = "程序正在更新";
    message.textContent = "服务正在重启，请保持页面打开，完成后会自动刷新。";
    countdown.textContent = "请稍候…";
  }

  function applyStatus(status) {
    const state = String(status?.state || "idle");
    if (state === "scheduled") {
      observedUpdate = true;
      startsAt = Number(status.startsAt || 0);
      title.textContent = "程序即将更新";
      message.textContent = status.message || "程序 30 秒后开始更新，请保存当前操作内容。";
      show();
      renderCountdown();
      return;
    }
    if (state === "complete" && observedUpdate) {
      startsAt = 0;
      title.textContent = "程序更新完成";
      message.textContent = status.message || "新版本已启动，页面即将自动刷新。";
      countdown.textContent = "正在刷新…";
      progress.style.width = "100%";
      show();
      if (!reloadScheduled) {
        reloadScheduled = true;
        setTimeout(() => location.reload(), 1500);
      }
      return;
    }
    if (state === "failed") {
      startsAt = 0;
      title.textContent = "程序更新未完成";
      message.textContent = status.message || "系统已停止本次更新，请联系管理员检查。";
      countdown.textContent = "当前页面暂不刷新";
      progress.style.width = "100%";
      show();
    }
  }

  async function poll() {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 2500);
    try {
      const response = await fetch(`${apiBase}/system/update-status`, {
        cache: "no-store",
        signal: controller.signal,
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const payload = await response.json();
      applyStatus(payload?.data || {});
    } catch {
      if (observedUpdate) {
        title.textContent = "程序正在更新";
        message.textContent = "服务正在重启，请保持页面打开，完成后会自动刷新。";
        countdown.textContent = "请稍候…";
        show();
      }
    } finally {
      clearTimeout(timeout);
    }
  }

  setInterval(renderCountdown, 250);
  setInterval(poll, 2000);
  poll();
})();
