"use strict";

const $ = id => document.getElementById(id);
const statusNode = $("status");
const STATUS_LABELS = {
  waiting: "等待中",
  collecting: "采集中",
  success: "成功",
  partial_success: "部分成功",
  failed: "失败"
};
let accountState = { accounts: [], activeAccountId: "", activeAccount: null };
let accountBusy = false;

function setStatus(message, type = "") {
  statusNode.textContent = message;
  statusNode.className = type;
}

async function message(payload) {
  const response = await chrome.runtime.sendMessage(payload);
  if (!response?.ok) throw new Error(response?.error || "扩展后台没有响应");
  return response;
}

function activeAccount() {
  return accountState.accounts.find(account => account.id === accountState.activeAccountId) || accountState.activeAccount || null;
}

function accountLabel(account) {
  const name = account.displayName || account.username || account.dataAccount || "未命名账号";
  return account.username && account.username !== name ? `${name}（${account.username}）` : name;
}

function showLoginForm(show = true, username = "") {
  $("loginForm").classList.toggle("hidden", !show);
  if (!show) return;
  $("loginUsername").value = username || "";
  $("loginPassword").value = "";
  setTimeout(() => (username ? $("loginPassword") : $("loginUsername")).focus(), 0);
}

function renderAccountState() {
  const accounts = Array.isArray(accountState.accounts) ? accountState.accounts : [];
  const active = activeAccount();
  $("noAccount").classList.toggle("hidden", accounts.length > 0);
  $("accountControls").classList.toggle("hidden", accounts.length === 0);
  $("accountStateText").textContent = active
    ? `${accountLabel(active)} · ${active.status === "active" ? "已登录" : "登录已过期"}`
    : "未登录";
  if (!accounts.length) {
    showLoginForm(true);
    return;
  }
  const accountSelect = $("accountSelect");
  accountSelect.innerHTML = "";
  accounts.forEach(account => {
    const option = document.createElement("option");
    option.value = account.id;
    option.textContent = `${accountLabel(account)}${account.status === "active" ? "" : "（需重新登录）"}`;
    option.selected = account.id === accountState.activeAccountId;
    accountSelect.appendChild(option);
  });
  const storeSelect = $("storeSelect");
  storeSelect.innerHTML = "";
  const stores = Array.isArray(active?.stores) ? active.stores : [];
  if (!stores.length) {
    const option = document.createElement("option");
    option.value = "";
    option.textContent = "没有已授权店铺";
    storeSelect.appendChild(option);
  } else {
    stores.forEach(store => {
      const option = document.createElement("option");
      option.value = store.id;
      const region = store.region === "europe" ? "欧洲站" : store.region === "americas" ? "美洲站" : store.region;
      option.textContent = `${store.name || store.id}${region ? ` · ${region}` : ""}`;
      option.selected = store.id === active.storeId;
      storeSelect.appendChild(option);
    });
  }
  storeSelect.disabled = !stores.length || active?.status !== "active" || accountBusy;
  accountSelect.disabled = accountBusy;
  $("removeAccount").disabled = accountBusy;
  $("accountHint").textContent = active?.status !== "active"
    ? "会话已失效，请使用相同账号重新登录"
    : stores.length ? "新任务固定保存到当前店铺" : "请先在系统内给该账号授权店铺";
  if (active?.status !== "active") showLoginForm(true, active.username);
}

async function refreshAccounts() {
  const response = await message({ type: "GET_EXTENSION_ACCOUNTS" });
  accountState = {
    accounts: Array.isArray(response.accounts) ? response.accounts : [],
    activeAccountId: response.activeAccountId || "",
    activeAccount: response.activeAccount || null
  };
  renderAccountState();
}

function renderCounts(counts = {}) {
  $("taskCounts").innerHTML = Object.entries(STATUS_LABELS).map(([status, label]) => (
    `<div class="count"><b>${Number(counts[status] || 0)}</b><small>${label}</small></div>`
  )).join("");
}

function taskRow(task) {
  const row = document.createElement("div");
  row.className = "task-row";
  const main = document.createElement("div");
  main.className = "task-main";
  const title = document.createElement("div");
  title.className = "task-title";
  const asin = document.createElement("span");
  asin.textContent = task.asin || "未知 ASIN";
  const badge = document.createElement("span");
  badge.className = `badge ${task.status || ""}`;
  badge.textContent = task.errorCode === "USER_CANCELLED" ? "已停止" : (STATUS_LABELS[task.status] || task.status || "未知");
  title.append(asin, badge);
  const meta = document.createElement("div");
  meta.className = "task-meta";
  meta.textContent = `${task.site || ""} · 尝试 ${Number(task.attempts || 0)} 次`;
  main.append(title, meta);
  if (task.error) {
    const error = document.createElement("div");
    error.className = "task-error";
    error.textContent = task.error;
    main.appendChild(error);
  }
  row.appendChild(main);
  if (task.status === "failed" && task.errorCode !== "USER_CANCELLED") {
    const retry = document.createElement("button");
    retry.className = "retry-one";
    retry.textContent = "重试";
    retry.addEventListener("click", async () => {
      retry.disabled = true;
      try {
        await message({ type: "RETRY_CAPTURE_TASK", taskId: task.id });
        setStatus(`${task.asin} 已重新进入等待队列`, "success");
        await refreshTasks();
      } catch (error) { setStatus(error.message, "error"); }
      finally { retry.disabled = false; }
    });
    row.appendChild(retry);
  }
  return row;
}

async function refreshTasks() {
  try {
    const response = await message({ type: "GET_CAPTURE_TASKS" });
    renderCounts(response.counts);
    $("cacheCount").textContent = `缓存 ${Number(response.cacheSize || 0)}`;
    const list = $("taskList");
    list.innerHTML = "";
    const tasks = Array.isArray(response.tasks) ? response.tasks.slice(0, 12) : [];
    if (!tasks.length) {
      const empty = document.createElement("div");
      empty.className = "empty";
      empty.textContent = "暂无当前账号的采集任务";
      list.appendChild(empty);
    } else tasks.forEach(task => list.appendChild(taskRow(task)));
  } catch (error) { setStatus(error.message, "error"); }
}

$("showLogin").addEventListener("click", () => showLoginForm(true));
$("cancelLogin").addEventListener("click", () => showLoginForm(false));

$("loginForm").addEventListener("submit", async event => {
  event.preventDefault();
  if (accountBusy) return;
  accountBusy = true;
  $("loginAccount").disabled = true;
  try {
    await message({
      type: "LOGIN_EXTENSION_ACCOUNT",
      username: $("loginUsername").value.trim(),
      password: $("loginPassword").value
    });
    $("loginPassword").value = "";
    showLoginForm(false);
    await refreshAccounts();
    await refreshTasks();
    const active = activeAccount();
    setStatus(active?.stores?.length ? "账号已添加，采集将进入当前选择的店铺" : "账号已添加，但还没有可用店铺", active?.stores?.length ? "success" : "");
  } catch (error) {
    setStatus(error.message, "error");
  } finally {
    accountBusy = false;
    $("loginAccount").disabled = false;
    renderAccountState();
  }
});

$("accountSelect").addEventListener("change", async event => {
  if (accountBusy) return;
  accountBusy = true;
  try {
    await message({ type: "SWITCH_EXTENSION_ACCOUNT", accountId: event.target.value });
    await refreshAccounts();
    await refreshTasks();
    setStatus("采集账号已切换，后续任务会进入该账号当前店铺", "success");
  } catch (error) {
    await refreshAccounts().catch(() => {});
    setStatus(error.message, "error");
  } finally {
    accountBusy = false;
    renderAccountState();
  }
});

$("storeSelect").addEventListener("change", async event => {
  if (accountBusy || !event.target.value) return;
  accountBusy = true;
  try {
    await message({ type: "SELECT_EXTENSION_STORE", storeId: event.target.value });
    await refreshAccounts();
    setStatus("采集店铺已切换，后续任务会固定写入该店铺", "success");
  } catch (error) {
    await refreshAccounts().catch(() => {});
    setStatus(error.message, "error");
  } finally {
    accountBusy = false;
    renderAccountState();
  }
});

$("removeAccount").addEventListener("click", async () => {
  const active = activeAccount();
  if (!active || accountBusy) return;
  if (!confirm(`确定从插件中移除“${accountLabel(active)}”吗？\n不会删除易联系统中的账号和产品数据。`)) return;
  accountBusy = true;
  try {
    await message({ type: "REMOVE_EXTENSION_ACCOUNT", accountId: active.id });
    await refreshAccounts();
    await refreshTasks();
    setStatus("账号已从插件移除", "success");
  } catch (error) {
    setStatus(error.message, "error");
  } finally {
    accountBusy = false;
    renderAccountState();
  }
});

$("retryFailed").addEventListener("click", async event => {
  event.currentTarget.disabled = true;
  try {
    const response = await message({ type: "RETRY_FAILED_CAPTURE_TASKS" });
    setStatus(response.retried ? `已重新提交 ${response.retried} 个失败任务` : "当前账号没有失败任务", response.retried ? "success" : "");
    await refreshTasks();
  } catch (error) { setStatus(error.message, "error"); }
  finally { event.currentTarget.disabled = false; }
});

$("clearCache").addEventListener("click", async event => {
  event.currentTarget.disabled = true;
  try {
    await message({ type: "CLEAR_CAPTURE_CACHE" });
    setStatus("商品详情缓存已清除", "success");
    await refreshTasks();
  } catch (error) { setStatus(error.message, "error"); }
  finally { event.currentTarget.disabled = false; }
});

$("openDashboard").addEventListener("click", () => {
  chrome.runtime.sendMessage({ type: "OPEN_DASHBOARD" });
  window.close();
});

Promise.all([refreshAccounts(), refreshTasks()]).catch(error => setStatus(error.message, "error"));
const refreshTimer = setInterval(refreshTasks, 1200);
window.addEventListener("unload", () => clearInterval(refreshTimer));
