const PRIORITY_COLUMNS = [
  "name",
  "phone",
  "website",
  "email",
  "category",
  "reviewCount",
  "averageRating",
  "googleMapsUrl",
  "query",
  "updatedAt",
  "facebook",
  "instagram",
  "linkedin",
  "youtube",
  "whatsapp",
  "twitter",
  "address",
  "country",
  "state",
  "city",
  "zipCode",
  "plusCode",
  "locatedIn",
  "businessStatus",
  "hours",
  "openingHours",
  "monday",
  "tuesday",
  "wednesday",
  "thursday",
  "friday",
  "saturday",
  "sunday"
];
const HIDDEN_COLUMNS = new Set([
  "placeID",
  "placeId",
  "cID",
  "cid",
  "latitude",
  "longitude",
  "googleMapsUrl",
  "sourceHref",
  "source",
  "rating"
]);

let currentLeads = [];
let currentLicense = null;
const EXPORT_BRAND = "智枢获客系统";
const DEFAULT_QUERY_LABEL = "未分类关键词";

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 normalizeText(value) {
  return String(value || "").replace(/\s+/g, " ").trim();
}

function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = filename;
  anchor.click();
  URL.revokeObjectURL(url);
}

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 formatColumns(leads, options = {}) {
  const { excludeColumns = [] } = options;
  const excluded = new Set(excludeColumns);
  const keys = new Set(PRIORITY_COLUMNS);
  leads.forEach((lead) => {
    Object.keys(lead).forEach((key) => {
      if (!HIDDEN_COLUMNS.has(key) && !excluded.has(key)) {
        keys.add(key);
      }
    });
  });

  const ordered = PRIORITY_COLUMNS.filter((key) => keys.has(key) && !HIDDEN_COLUMNS.has(key) && !excluded.has(key));
  const remaining = [...keys].filter((key) => !PRIORITY_COLUMNS.includes(key) && !excluded.has(key)).sort();
  return [...ordered, ...remaining];
}

function escapeHtml(value) {
  return String(value || "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function isExternalLinkColumn(column) {
  return [
    "website",
    "googleMapsUrl",
    "facebook",
    "instagram",
    "linkedin",
    "youtube",
    "whatsapp",
    "twitter"
  ].includes(column);
}

function appendTextCellContent(td, value, column) {
  if (column === "address" && value.length > 60) {
    td.classList.add("is-collapsible");
    const text = document.createElement("div");
    text.className = "dashboard__cell-text dashboard__cell-text--collapsed";
    text.textContent = value;
    text.title = value;

    const toggle = document.createElement("button");
    toggle.type = "button";
    toggle.className = "dashboard__cell-toggle";
    toggle.textContent = "展开";
    toggle.addEventListener("click", () => {
      const expanded = text.classList.toggle("dashboard__cell-text--collapsed");
      toggle.textContent = expanded ? "展开" : "收起";
    });

    td.appendChild(text);
    td.appendChild(toggle);
    return;
  }

  td.textContent = value;
}

function renderEmptyState(title, description) {
  const groups = document.getElementById("resultsContainer");
  const wrap = document.getElementById("emptyTableWrap");
  const table = document.getElementById("resultsTable");
  groups.innerHTML = "";
  wrap.hidden = false;
  table.innerHTML = `
    <thead><tr><th>${escapeHtml(title)}</th></tr></thead>
    <tbody><tr><td>${escapeHtml(description)}</td></tr></tbody>
  `;
}

function createResultsTable(leads) {
  const table = document.createElement("table");
  table.className = "dashboard__table";

  const columns = formatColumns(leads, { excludeColumns: ["query"] });
  const thead = document.createElement("thead");
  const headerRow = document.createElement("tr");

  columns.forEach((column) => {
    const th = document.createElement("th");
    th.textContent = column;
    th.dataset.column = column;
    headerRow.appendChild(th);
  });

  thead.appendChild(headerRow);
  table.appendChild(thead);

  const tbody = document.createElement("tbody");

  leads.forEach((lead) => {
    const tr = document.createElement("tr");

    columns.forEach((column) => {
      const td = document.createElement("td");
      const value = normalizeText(lead[column]);
      td.dataset.column = column;

      if (isExternalLinkColumn(column)) {
        if (value) {
          const link = document.createElement("a");
          link.href = value;
          link.target = "_blank";
          link.rel = "noreferrer";
          link.textContent = value;
          td.appendChild(link);
        }
      } else {
        appendTextCellContent(td, value, column);
      }

      tr.appendChild(td);
    });

  tbody.appendChild(tr);
  });

  table.appendChild(tbody);
  return table;
}

function normalizeQueryLabel(value) {
  return normalizeText(value) || DEFAULT_QUERY_LABEL;
}

function compareLeadTimeDesc(left, right) {
  const leftTime = Date.parse(left?.updatedAt || 0);
  const rightTime = Date.parse(right?.updatedAt || 0);
  return (Number.isFinite(rightTime) ? rightTime : 0) - (Number.isFinite(leftTime) ? leftTime : 0);
}

function buildLeadGroups(leads) {
  const groups = new Map();

  leads.forEach((lead) => {
    const query = normalizeQueryLabel(lead.query);
    if (!groups.has(query)) {
      groups.set(query, []);
    }

    groups.get(query).push(lead);
  });

  return [...groups.entries()]
    .map(([query, items]) => ({
      query,
      leads: [...items].sort(compareLeadTimeDesc)
    }))
    .sort((left, right) => {
      const leftLatest = Date.parse(left.leads[0]?.updatedAt || 0);
      const rightLatest = Date.parse(right.leads[0]?.updatedAt || 0);
      return (Number.isFinite(rightLatest) ? rightLatest : 0) - (Number.isFinite(leftLatest) ? leftLatest : 0);
    });
}

function renderTableGroups(leads) {
  const groupsContainer = document.getElementById("resultsContainer");
  const emptyWrap = document.getElementById("emptyTableWrap");
  groupsContainer.innerHTML = "";
  emptyWrap.hidden = true;

  if (!leads.length) {
    renderEmptyState("暂无数据", "请先在搜索页运行采集。");
    return;
  }

  buildLeadGroups(leads).forEach((group) => {
    const section = document.createElement("section");
    section.className = "dashboard__group";

    const header = document.createElement("div");
    header.className = "dashboard__group-head";

    const title = document.createElement("h2");
    title.className = "dashboard__group-title";
    title.textContent = group.query;

    const meta = document.createElement("div");
    meta.className = "dashboard__group-meta";
    meta.textContent = `共 ${group.leads.length} 条`;

    header.appendChild(title);
    header.appendChild(meta);

    const tableWrap = document.createElement("div");
    tableWrap.className = "dashboard__group-table-wrap";
    tableWrap.appendChild(createResultsTable(group.leads));

    section.appendChild(header);
    section.appendChild(tableWrap);
    groupsContainer.appendChild(section);
  });
}

function buildExportGroups(leads = currentLeads) {
  return buildLeadGroups(leads).map((group) => {
    const columns = formatColumns(group.leads, { excludeColumns: ["query"] });
    const rows = group.leads.map((lead) => {
      const row = {};
      columns.forEach((column) => {
        row[column] = normalizeText(lead[column]);
      });
      return row;
    });

    return {
      query: group.query,
      columns,
      rows
    };
  });
}

function sanitizeSheetName(value, fallback) {
  const invalid = /[\\/?*\[\]:]/g;
  const cleaned = normalizeText(value).replace(invalid, " ").trim();
  return (cleaned || fallback).slice(0, 31);
}

function getUniqueSheetName(existingNames, value, fallback = "Sheet") {
  const base = sanitizeSheetName(value, fallback) || fallback;
  let nextName = base;
  let index = 2;

  while (existingNames.has(nextName)) {
    const suffix = `-${index}`;
    nextName = `${base.slice(0, Math.max(31 - suffix.length, 1))}${suffix}`;
    index += 1;
  }

  existingNames.add(nextName);
  return nextName;
}

function setBanner(title, text, hidden = false) {
  const banner = document.getElementById("licenseBanner");
  const bannerTitle = document.getElementById("licenseBannerTitle");
  const bannerText = document.getElementById("licenseBannerText");

  banner.hidden = hidden;
  bannerTitle.textContent = title;
  bannerText.textContent = text;
}

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

function setActionAvailability(license) {
  const locked = !license || !license.isActive;
  document.getElementById("downloadCsvBtn").disabled = locked;
  document.getElementById("downloadXlsxBtn").disabled = locked;
  document.getElementById("clearBtn").disabled = locked;
}

function updateSummary() {
  const summary = document.getElementById("summaryText");

  if (!currentLicense || !currentLicense.isActive) {
    summary.textContent = (currentLicense && currentLicense.message) || "授权状态不可用。";
    return;
  }

  const planText = currentLicense.planLabel ? `，当前套餐：${currentLicense.planLabel}` : "";
  const groupCount = buildLeadGroups(currentLeads).length;
  summary.textContent = `当前共 ${currentLeads.length} 条本地采集记录，分为 ${groupCount} 个关键词表格${planText}。CSV 导出为单文件，XLSX 导出为多表。`;
}

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

  if (!response.ok) {
    currentLicense = response.license || null;
    setActionAvailability(currentLicense);
    setBanner("授权状态异常", response.error || "无法读取授权状态。");
    updateSummary();
    renderEmptyState("授权不可用", (currentLicense && currentLicense.message) || "无法读取授权状态，请返回插件弹窗重新激活。");
    return null;
  }

  currentLicense = response.license || null;
  setActionAvailability(currentLicense);

  if (!currentLicense || !currentLicense.isActive) {
    setBanner("插件未激活", (currentLicense && currentLicense.message) || "请先激活插件。");
    updateSummary();
    renderEmptyState("授权不可用", (currentLicense && currentLicense.message) || "请先激活插件。");
    return currentLicense;
  }

  const daysRemaining = getDaysRemaining(currentLicense.expiresAt);
  if (daysRemaining !== null && daysRemaining <= 7) {
    setBanner("授权即将到期", `当前授权还剩 ${daysRemaining} 天到期，请提前续费并激活新码。`);
    updateSummary();
    return currentLicense;
  }

  const expiresText = currentLicense.expiresAt ? `，到期时间：${formatDateTime(currentLicense.expiresAt)}` : "";
  setBanner("授权状态", `当前授权有效${expiresText}。`, true);
  updateSummary();
  return currentLicense;
}

async function loadLeads() {
  const response = await sendMessage({ action: "GET_LEADS" });
  if (!response.ok) {
    if (response.license) {
      currentLicense = response.license;
      setActionAvailability(currentLicense);
      setBanner("授权不可用", currentLicense.message || response.error || "无法读取授权状态。");
    }
    document.getElementById("summaryText").textContent = response.error || "读取数据失败。";
    renderEmptyState("读取失败", response.error || "无法读取本地采集数据。");
    return;
  }

  currentLeads = response.leads || [];
  updateSummary();
  renderTableGroups(currentLeads);
}

function buildExportRows() {
  return buildLeadGroups(currentLeads).flatMap((group) => {
    const columns = formatColumns(group.leads);
    return group.leads.map((lead) => {
      const row = {};
      columns.forEach((column) => {
        row[column] = normalizeText(lead[column]);
      });
      return row;
    });
  });
}

function escapeCsvValue(value) {
  return `"${String(value || "").replace(/"/g, '""')}"`;
}

function getFileTimestamp() {
  const now = new Date();
  const parts = [
    now.getFullYear(),
    String(now.getMonth() + 1).padStart(2, "0"),
    String(now.getDate()).padStart(2, "0"),
    "_",
    String(now.getHours()).padStart(2, "0"),
    String(now.getMinutes()).padStart(2, "0"),
    String(now.getSeconds()).padStart(2, "0")
  ];

  return parts.join("");
}

function sanitizeFilenamePart(value, fallback = "关键词") {
  const cleaned = normalizeText(value)
    .replace(/[\\/:*?"<>|]/g, " ")
    .replace(/\s+/g, " ")
    .trim();

  return cleaned || fallback;
}

function ensureActiveForExport() {
  if (!currentLicense || !currentLicense.isActive) {
    window.alert((currentLicense && currentLicense.message) || "插件未激活，请先回到弹窗输入激活码。");
    return false;
  }

  return true;
}

function downloadCsv() {
  if (!ensureActiveForExport()) {
    return;
  }

  if (!currentLeads.length) {
    window.alert("当前没有可导出的数据。");
    return;
  }

  const rows = buildExportRows();
  const columns = formatColumns(currentLeads);
  const csvChunks = [];
  csvChunks.push(escapeCsvValue(`${EXPORT_BRAND} - 全部结果`));
  csvChunks.push("");
  csvChunks.push(columns.join(","));
  rows.forEach((row) => {
    csvChunks.push(columns.map((column) => escapeCsvValue(row[column])).join(","));
  });

  downloadBlob(
    new Blob(["\uFEFF", csvChunks.join("\n")], { type: "text/csv;charset=utf-8" }),
    `${EXPORT_BRAND}-全部结果-${getFileTimestamp()}.csv`
  );
}

function downloadXlsx() {
  if (!ensureActiveForExport()) {
    return;
  }

  if (!currentLeads.length) {
    window.alert("当前没有可导出的数据。");
    return;
  }

  const exportGroups = buildExportGroups();
  const workbook = XLSX.utils.book_new();
  const usedSheetNames = new Set();

  exportGroups.forEach((group, index) => {
    const worksheet = XLSX.utils.aoa_to_sheet([[`${EXPORT_BRAND} - ${group.query}`], []]);
    XLSX.utils.sheet_add_json(worksheet, group.rows, {
      origin: "A3",
      header: group.columns
    });
    worksheet["!merges"] = [
      {
        s: { r: 0, c: 0 },
        e: { r: 0, c: Math.max(group.columns.length - 1, 0) }
      }
    ];
    worksheet.A1.s = {
      font: { bold: true, sz: 16, color: { rgb: "1F7A4C" } },
      alignment: { horizontal: "center", vertical: "center" }
    };

    const sheetName = getUniqueSheetName(usedSheetNames, group.query, `关键词${index + 1}`);
    XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
  });

  XLSX.writeFile(workbook, `${EXPORT_BRAND}-${getFileTimestamp()}.xlsx`);
}

async function clearLeads() {
  if (!ensureActiveForExport()) {
    return;
  }

  const confirmed = window.confirm("确认清空当前全部本地数据吗？");
  if (!confirmed) {
    return;
  }

  const response = await sendMessage({ action: "CLEAR_LEADS" });
  if (!response.ok) {
    window.alert(response.error || "清空失败。");
    return;
  }

  await loadLeads();
}

async function refreshDashboard(forceValidate = false) {
  const license = await loadLicenseState(forceValidate);
  if (!license || !license.isActive) {
    currentLeads = [];
    return;
  }

  await loadLeads();
}

document.getElementById("refreshBtn").addEventListener("click", () => refreshDashboard(true));
document.getElementById("licenseBtn").addEventListener("click", openLicensePage);
document.getElementById("licenseBannerBtn").addEventListener("click", openLicensePage);
document.getElementById("downloadCsvBtn").addEventListener("click", downloadCsv);
document.getElementById("downloadXlsxBtn").addEventListener("click", downloadXlsx);
document.getElementById("clearBtn").addEventListener("click", clearLeads);

refreshDashboard();
