const localAddress = "http://127.0.0.1:43121/";
const root = document.documentElement;
const gateTitle = document.querySelector("#gate-title");
const gateDescription = document.querySelector("#gate-description");
const statusCode = document.querySelector("#status-code");
const noBypass = document.querySelector("#no-bypass");
const reasonValue = document.querySelector("#reason-value");
const browserValue = document.querySelector("#browser-value");
const supportedValue = document.querySelector("#supported-value");
const retryButton = document.querySelector("#retry-button");
const copyButton = document.querySelector("#copy-button");

function browserLabel(fullVersionList) {
  const known = fullVersionList?.find(({ brand }) =>
    brand === "Google Chrome" || brand === "Microsoft Edge");
  return known ? `${known.brand} ${known.version.split(".")[0]}` : "无法可靠识别";
}

function supportedLabel(supportedBrowsers) {
  if (!Array.isArray(supportedBrowsers) || supportedBrowsers.length === 0) return "等待发布记录";
  return supportedBrowsers.map(({ brand, major }) => `${brand} ${major}`).join(" / ");
}

function showBlocked(reason, supportedBrowsers, fullVersionList) {
  root.dataset.supportStatus = "blocked";
  gateTitle.textContent = "当前浏览器无法使用 Dada";
  gateDescription.textContent = "本次 P0-A 发布仅支持当前这台 Windows 电脑上、已经完成验收的 Chrome 或 Edge 版本。当前环境无法可靠通过支持检查，因此不会加载任何产品功能。";
  statusCode.hidden = false;
  noBypass.hidden = false;
  reasonValue.classList.add("danger");
  reasonValue.textContent = reason;
  browserValue.textContent = browserLabel(fullVersionList);
  supportedValue.textContent = supportedLabel(supportedBrowsers);
}

async function checkSupport() {
  root.dataset.supportStatus = "checking";
  reasonValue.textContent = "identity_unavailable";
  browserValue.textContent = "正在检测";

  const userAgentData = navigator.userAgentData;
  if (!userAgentData || typeof userAgentData.getHighEntropyValues !== "function") {
    showBlocked("identity_unavailable", [], []);
    return;
  }

  try {
    const entropy = await userAgentData.getHighEntropyValues(["fullVersionList", "platform"]);
    const body = {
      brands: userAgentData.brands ?? [],
      full_version_list: entropy.fullVersionList ?? [],
      platform: entropy.platform ?? "",
    };
    const response = await fetch("/api/v1/support/check", {
      body: JSON.stringify(body),
      credentials: "same-origin",
      headers: { "Content-Type": "application/json" },
      method: "POST",
    });
    const result = await response.json();
    if (response.ok && result.status === "supported") {
      root.dataset.supportStatus = "supported";
      gateTitle.textContent = "浏览器支持检查已通过";
      gateDescription.textContent = "当前浏览器已通过 Dada 支持检查。";
      statusCode.hidden = true;
      noBypass.hidden = true;
      reasonValue.classList.remove("danger");
      reasonValue.textContent = "supported";
      browserValue.textContent = `${result.browser.brand} ${result.browser.major}`;
      supportedValue.textContent = supportedLabel(result.supported_browsers);
      window.dispatchEvent(new CustomEvent("dada:support-ready"));
      window.location.replace(window.location.pathname.startsWith("/admin") ? "/admin" : "/app");
      return;
    }
    showBlocked(
      result.error?.details?.reason ?? "identity_unavailable",
      result.error?.details?.supported_browsers ?? [],
      body.full_version_list,
    );
  } catch {
    showBlocked("identity_unavailable", [], []);
  }
}

retryButton.addEventListener("click", () => void checkSupport());
copyButton.addEventListener("click", async () => {
  try {
    await navigator.clipboard.writeText(localAddress);
    copyButton.textContent = "已复制本机地址";
  } catch {
    copyButton.textContent = localAddress;
  }
});

void checkSupport();
