const $ = (sel) => document.querySelector(sel);

function escapeHTML(str) {
  const div = document.createElement("div");
  div.textContent = str;
  return div.innerHTML;
}

const views = {
  login: $("#login-view"),
  dashboard: $("#dashboard-view"),
};

function showView(name) {
  for (const [k, el] of Object.entries(views)) {
    el.classList.toggle("active", k === name);
  }
}

const REGION_BOTS = {
  nyc: "SlotSharkUS_Bot",
  fra: "SlotShark_Bot",
};

const REGION_LABELS = {
  nyc: "US",
  fra: "EU",
};

function detectClosestRegion() {
  const offset = new Date().getTimezoneOffset();
  // UTC offset in minutes: negative = east of UTC. Europe is roughly -120 to 0, Americas are +180 to +480
  return offset <= 0 ? "fra" : "nyc";
}

async function getRegion() {
  const data = await chrome.storage.local.get("slotshark.region");
  if (data["slotshark.region"]) return data["slotshark.region"];
  const detected = detectClosestRegion();
  await chrome.storage.local.set({ "slotshark.region": detected });
  return detected;
}

function setActiveRegion(region) {
  document.querySelectorAll(".region-btn").forEach((btn) =>
    btn.classList.toggle("active", btn.dataset.region === region)
  );
  const bot = REGION_BOTS[region] || REGION_BOTS.nyc;
  $("#get-code-btn").href = `https://t.me/${bot}?start=login`;
  const badge = $("#region-badge");
  if (badge) badge.textContent = REGION_LABELS[region] || region.toUpperCase();
}

document.querySelectorAll(".region-btn").forEach((btn) => {
  btn.addEventListener("click", async () => {
    const region = btn.dataset.region;
    await chrome.storage.local.set({ "slotshark.region": region });
    setActiveRegion(region);
    const keyName = `slotshark.apiKey.${region}`;
    const data = await chrome.storage.local.get(keyName);
    if (data[keyName]) {
      loadDashboard();
    } else {
      showView("login");
    }
  });
});

async function migrateAuthKeys() {
  const data = await chrome.storage.local.get(["apiKey", "slotshark.apiKey.nyc"]);
  if (data.apiKey && !data["slotshark.apiKey.nyc"]) {
    await chrome.storage.local.set({
      "slotshark.apiKey.nyc": data.apiKey,
      "slotshark.region": "nyc",
    });
    await chrome.storage.local.remove("apiKey");
  }
}

function apiCall(method, path, body) {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage(
      { type: "API_CALL", method, path, body },
      (response) => resolve(response)
    );
  });
}

$("#login-btn").addEventListener("click", async () => {
  const code = $("#auth-code").value.trim();
  if (!code) {
    $("#login-error").textContent = "Enter the code from Telegram";
    return;
  }

  $("#login-error").textContent = "";
  $("#login-success").textContent = "";
  $("#login-btn").disabled = true;
  $("#login-btn").textContent = "Authenticating...";

  const resp = await apiCall("POST", "/auth/telegram", { code });

  $("#login-btn").disabled = false;
  $("#login-btn").textContent = "Login";

  if (resp.error) {
    $("#login-error").textContent = resp.error;
    return;
  }

  if (resp.data?.success) {
    const region = await getRegion();
    await chrome.storage.local.set({
      [`slotshark.apiKey.${region}`]: resp.data.apiKey,
      userId: resp.data.userId,
    });
    $("#login-success").textContent = "Authenticated!";
    setTimeout(() => loadDashboard(), 500);
  } else {
    $("#login-error").textContent = resp.data?.error || "Authentication failed";
  }
});

let _popupPresets = [];
let _popupActivePresetId = null;

async function loadPresetPicker() {
  const data = await chrome.storage.local.get(["slotshark.presets", "slotshark.activePreset"]);
  _popupPresets = data["slotshark.presets"] || [];
  _popupActivePresetId = data["slotshark.activePreset"] || null;
  updatePresetPickerDisplay();
}

function updatePresetPickerDisplay() {
  const active = _popupPresets.find((p) => p.id === _popupActivePresetId) || _popupPresets[0];
  if (active) {
    $("#preset-picker-emoji").textContent = active.emoji;
    $("#preset-picker-label").textContent = active.label;
  } else {
    $("#preset-picker-emoji").textContent = "\u2699\uFE0F";
    $("#preset-picker-label").textContent = "No preset";
  }
}

function renderPresetDropdown() {
  const dd = $("#preset-dropdown");
  if (_popupPresets.length === 0) {
    dd.innerHTML = '<div class="preset-dropdown-empty">No presets — create one in Settings</div>';
    return;
  }
  dd.innerHTML = _popupPresets.map((p) => {
    const isActive = p.id === _popupActivePresetId || (!_popupActivePresetId && p === _popupPresets[0]);
    return `<button class="preset-dropdown-item${isActive ? " active" : ""}" data-id="${escapeHTML(p.id)}">
      <span class="dd-emoji">${escapeHTML(p.emoji)}</span>
      <span class="dd-label">${escapeHTML(p.label)}</span>
      ${isActive ? '<span class="dd-check">\u2713</span>' : ""}
    </button>`;
  }).join("");

  dd.querySelectorAll(".preset-dropdown-item").forEach((btn) => {
    btn.addEventListener("click", async () => {
      _popupActivePresetId = btn.dataset.id;
      await chrome.storage.local.set({ "slotshark.activePreset": _popupActivePresetId });
      updatePresetPickerDisplay();
      dd.style.display = "none";
    });
  });
}

$("#preset-picker-btn").addEventListener("click", (e) => {
  e.stopPropagation();
  const dd = $("#preset-dropdown");
  if (dd.style.display === "none") {
    renderPresetDropdown();
    dd.style.display = "block";
  } else {
    dd.style.display = "none";
  }
});

document.addEventListener("click", (e) => {
  const dd = $("#preset-dropdown");
  if (dd && !dd.contains(e.target) && e.target !== $("#preset-picker-btn")) {
    dd.style.display = "none";
  }
});

function renderDashboard({ displayName, walletResults, activeCount, totalCount }) {
  $("#dash-user").textContent = displayName || "";
  const countEl = $("#wallet-count-link");
  if (totalCount != null) {
    countEl.textContent = `${activeCount ?? 0}/${totalCount} wallets`;
  }
  const listEl = $("#wallet-list");
  if (!walletResults || walletResults.length === 0) {
    listEl.innerHTML =
      '<div style="color:#666; font-size:12px;">No active wallets. Add wallets in Settings.</div>';
    return;
  }
  listEl.innerHTML = walletResults
    .map(
      (r) => `
      <div class="wallet-card">
        <div class="wallet-pubkey">${escapeHTML(r.pubkey)}</div>
        <div class="wallet-balance">${escapeHTML(r.balanceText)}</div>
        <div class="wallet-status">${r.active ? "Ready to Trade" : "Not Initialized"}</div>
      </div>
    `
    )
    .join("");
}

async function loadDashboard() {
  showView("dashboard");
  loadPresetPicker();

  const cached = (await chrome.storage.local.get("slotshark.dashCache"))["slotshark.dashCache"];
  if (cached) renderDashboard(cached);

  const meResp = await apiCall("GET", "/auth/me");
  if (meResp.error || !meResp.data?.success) {
    const region = await getRegion();
    await chrome.storage.local.remove([`slotshark.apiKey.${region}`, "userId", "slotshark.dashCache"]);
    showView("login");
    $("#login-error").textContent = "Session expired — please login again";
    return;
  }

  const { userId, tgUsername, isAdmin, wallets } = meResp.data;
  const displayName = isAdmin ? `@${tgUsername || userId} (admin)` : `@${tgUsername || userId}`;

  const activeWalletsData = (await chrome.storage.local.get("slotshark.activeWallets"))["slotshark.activeWallets"] || [];
  // Only wallets with nonces deployed can actually trade. Filter un-set-up
  // wallets out of the active set so they don't display as "Ready to Trade"
  // or get included in trade fan-out by content scripts.
  const readyPks = new Set((wallets || []).filter((w) => (w.nonceCount || 0) >= 3).map((w) => w.pubkey));
  const serverEnabled = (wallets || []).filter((w) => w.extensionEnabled && (w.nonceCount || 0) >= 3).map((w) => w.pubkey);
  const reconciled = Array.from(new Set([
    ...activeWalletsData.filter((pk) => readyPks.has(pk)),
    ...serverEnabled,
  ]));
  if (reconciled.length !== activeWalletsData.length || reconciled.some((pk, i) => activeWalletsData[i] !== pk)) {
    try { await chrome.storage.local.set({ "slotshark.activeWallets": reconciled }); } catch {}
  }
  const activeWallets = (wallets || []).filter((w) => reconciled.includes(w.pubkey));

  const totalCount = (wallets || []).length;
  const activeCount = activeWallets.length;

  if (activeWallets.length === 0) {
    const dashData = { displayName, walletResults: [], activeCount, totalCount };
    renderDashboard(dashData);
    chrome.storage.local.set({ "slotshark.dashCache": dashData });
    return;
  }

  if (!cached) {
    renderDashboard({ displayName, walletResults: activeWallets.map((w) => ({ pubkey: w.pubkey, balanceText: "...", active: w.active })), activeCount, totalCount });
  }

  const walletResults = await Promise.all(
    activeWallets.map(async (w) => {
      const balResp = await apiCall("GET", `/wallet/${w.pubkey}/balance`);
      const balanceText = balResp.data?.success
        ? `${balResp.data.balanceSol.toFixed(4)} SOL`
        : "Error";
      return { pubkey: w.pubkey, balanceText, active: w.active };
    })
  );

  const dashData = { displayName, walletResults, activeCount, totalCount };
  renderDashboard(dashData);
  chrome.storage.local.set({ "slotshark.dashCache": dashData });
}

$("#refresh-btn").addEventListener("click", () => loadDashboard());

$("#settings-btn").addEventListener("click", () => {
  chrome.tabs.create({ url: chrome.runtime.getURL("settings.html") });
});

$("#wallet-count-link").addEventListener("click", () => {
  chrome.tabs.create({ url: chrome.runtime.getURL("settings.html#wallets") });
});

$("#logout-btn").addEventListener("click", async () => {
  const region = await getRegion();
  await chrome.storage.local.remove([`slotshark.apiKey.${region}`, "slotshark.dashCache"]);
  showView("login");
});

(async () => {
  await migrateAuthKeys();
  const region = await getRegion();
  setActiveRegion(region);
  const keyName = `slotshark.apiKey.${region}`;
  const data = await chrome.storage.local.get(keyName);
  if (data[keyName]) {
    loadDashboard();
  } else {
    showView("login");
  }
})();
