let currentLicense = null;

function sendMessage(message) {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage(message, (response) => {
      if (chrome.runtime.lastError) {
        resolve({ ok: false, error: chrome.runtime.lastError.message });
        return;
      }

      resolve(response || { ok: false, error: "No response." });
    });
  });
}

function setStatus(text, tone = "neutral") {
  const status = document.getElementById("pageStatus");
  status.textContent = text;
  status.dataset.tone = tone;
}

function formatDateTime(value) {
  if (!value) {
    return "-";
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return new Intl.DateTimeFormat("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit"
  }).format(date);
}

function getDaysRemaining(expiresAt) {
  if (!expiresAt) {
    return null;
  }

  const diff = Date.parse(expiresAt) - Date.now();
  if (!Number.isFinite(diff)) {
    return null;
  }

  return Math.ceil(diff / (24 * 60 * 60 * 1000));
}

function renderLicense(license) {
  const chip = document.getElementById("licenseStatusChip");
  const message = document.getElementById("licenseMessage");
  const planTypeText = document.getElementById("planTypeText");
  const activatedAtText = document.getElementById("activatedAtText");
  const expiresAtText = document.getElementById("expiresAtText");
  const deviceIdText = document.getElementById("deviceIdText");
  const reminder = document.getElementById("licenseReminder");

  const labelMap = {
    active: "已激活",
    expired: "已过期",
    disabled: "已停用",
    invalid: "无效",
    unlicensed: "未激活"
  };

  chip.textContent = labelMap[license.status] || "未知";
  chip.dataset.state = license.status || "unknown";
  message.textContent = license.message || "请先输入激活码。";
  planTypeText.textContent = license.planLabel || "-";
  activatedAtText.textContent = formatDateTime(license.activatedAt);
  expiresAtText.textContent = formatDateTime(license.expiresAt);
  deviceIdText.textContent = license.deviceId || "-";

  const daysRemaining = getDaysRemaining(license.expiresAt);
  if (license.isActive && daysRemaining !== null && daysRemaining <= 7) {
    chip.textContent = "即将到期";
    chip.dataset.state = "warning";
    reminder.hidden = false;
    reminder.textContent = `当前授权还剩 ${daysRemaining} 天到期，请提前续费并激活新码。`;
  } else {
    reminder.hidden = true;
    reminder.textContent = "";
  }
}

async function loadLicense(forceValidate = false) {
  const response = await sendMessage({
    action: forceValidate ? "REFRESH_LICENSE_STATE" : "GET_LICENSE_STATE"
  });

  if (!response.ok) {
    if (response.license) {
      currentLicense = response.license;
      renderLicense(currentLicense);
    }
    setStatus(response.error || "读取授权状态失败。", "error");
    return false;
  }

  currentLicense = response.license;
  renderLicense(currentLicense);
  return true;
}

async function activateLicense() {
  const code = document.getElementById("licenseCodeInput").value.trim();
  if (!code) {
    setStatus("请输入激活码。", "error");
    return;
  }

  const response = await sendMessage({
    action: "ACTIVATE_LICENSE",
    code
  });

  if (!response.ok) {
    setStatus(response.error || "激活失败。", "error");
    if (response.license) {
      currentLicense = response.license;
      renderLicense(currentLicense);
    }
    return;
  }

  currentLicense = response.license;
  renderLicense(currentLicense);
  setStatus(
    currentLicense && currentLicense.reusedExistingLicense
      ? "该激活码已在本机激活过，按首次激活时间计算。"
      : "激活成功。",
    "success"
  );
}

async function copyDeviceId() {
  const deviceId = currentLicense && currentLicense.deviceId;
  if (!deviceId) {
    setStatus("当前没有可复制的设备 ID。", "error");
    return;
  }

  try {
    await navigator.clipboard.writeText(deviceId);
    setStatus("设备 ID 已复制。", "success");
  } catch (_error) {
    setStatus(`设备 ID：${deviceId}`, "success");
  }
}

document.getElementById("activateBtn").addEventListener("click", activateLicense);
document.getElementById("refreshBtn").addEventListener("click", async () => {
  const ok = await loadLicense(true);
  if (ok) {
    setStatus("授权状态已刷新。", "success");
  }
});
document.getElementById("copyDeviceBtn").addEventListener("click", copyDeviceId);
document.getElementById("licenseCodeInput").addEventListener("keydown", (event) => {
  if (event.key === "Enter") {
    activateLicense();
  }
});

loadLicense();
