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("popupStatus");
  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));
}

async function openLicensePage() {
  await sendMessage({ action: "OPEN_LICENSE_PAGE" });
}

function renderLicenseState(license) {
  const badge = document.getElementById("licenseBadge");
  const message = document.getElementById("licenseMessage");
  const meta = document.getElementById("licenseMeta");
  const activateButton = document.getElementById("activateLicenseBtn");
  const startCollectionButton = document.getElementById("startCollectionBtn");
  const openResultsButton = document.getElementById("openResultsBtn");

  if (!license) {
    badge.textContent = "未知";
    badge.dataset.state = "unknown";
    message.textContent = "未能读取授权状态。";
    meta.textContent = "";
    activateButton.disabled = false;
    startCollectionButton.disabled = true;
    openResultsButton.disabled = true;
    return;
  }

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

  badge.textContent = badgeTextMap[license.status] || "未知";
  badge.dataset.state = license.status || "unknown";
  message.textContent = license.message || "请先输入激活码。";

  const metaParts = [];
  if (license.planLabel) {
    metaParts.push(`套餐：${license.planLabel}`);
  }
  if (license.expiresAt) {
    metaParts.push(`到期：${formatDateTime(license.expiresAt)}`);
  }
  meta.textContent = metaParts.join(" | ");

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

  activateButton.disabled = !license.isConfigured;
  startCollectionButton.disabled = !license.isActive;
  openResultsButton.disabled = !license.isActive;
}

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

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

  currentLicense = response.license || null;
  renderLicenseState(currentLicense);
  return currentLicense;
}

async function ensureLicenseActive() {
  const license = await loadLicenseState();
  if (!license || !license.isActive) {
    setStatus((license && license.message) || "插件未激活，请先输入激活码。", "error");
    await openLicensePage();
    return false;
  }

  return true;
}

async function activateLicense() {
  const code = document.getElementById("licenseInput").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;
      renderLicenseState(currentLicense);
    }
    return;
  }

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

async function openMaps() {
  const query = document.getElementById("searchInput").value.trim();
  if (!query) {
    setStatus("请输入搜索关键词。", "error");
    return;
  }

  const response = await sendMessage({
    action: "OPEN_SEARCH",
    query
  });

  if (!response.ok) {
    setStatus(response.error || "打开失败。", "error");
    return;
  }

  setStatus("已打开 Google Maps 搜索页。", "success");
  window.close();
}

async function startCollection() {
  if (!(await ensureLicenseActive())) {
    return;
  }

  const query = document.getElementById("searchInput").value.trim();
  if (!query) {
    setStatus("请输入搜索关键词。", "error");
    return;
  }

  const response = await sendMessage({
    action: "START_COLLECTION_JOB",
    query,
    enrichEmail: true
  });

  if (!response.ok) {
    setStatus(response.error || "启动采集失败。", "error");
    return;
  }

  setStatus("已启动自动采集，正在打开 Google Maps。", "success");
  window.close();
}

async function openResults() {
  if (!(await ensureLicenseActive())) {
    return;
  }

  const response = await sendMessage({ action: "OPEN_DASHBOARD" });
  if (!response.ok) {
    setStatus(response.error || "打开结果页失败。请确认 Chrome 当前加载的是包含 dashboard.html 的扩展目录。", "error");
    return;
  }

  setStatus("已打开结果页。", "success");
  window.close();
}

document.getElementById("activateLicenseBtn").addEventListener("click", activateLicense);
document.getElementById("refreshLicenseBtn").addEventListener("click", async () => {
  const license = await loadLicenseState(true);
  if (license) {
    setStatus("授权状态已刷新。", "success");
  }
});
document.getElementById("openLicensePageBtn").addEventListener("click", openLicensePage);
document.getElementById("startCollectionBtn").addEventListener("click", startCollection);
document.getElementById("openMapsBtn").addEventListener("click", openMaps);
document.getElementById("openResultsBtn").addEventListener("click", openResults);
document.getElementById("searchInput").addEventListener("keydown", (event) => {
  if (event.key === "Enter") {
    startCollection();
  }
});
document.getElementById("licenseInput").addEventListener("keydown", (event) => {
  if (event.key === "Enter") {
    activateLicense();
  }
});

loadLicenseState();
