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

function send(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 });
    });
  });
}

function activeTab() {
  return new Promise((resolve) => {
    chrome.tabs.query({ active: true, currentWindow: true }, ([tab]) => resolve(tab));
  });
}

function shorten(value) {
  return value ? `${value.slice(0, 6)}...${value.slice(-4)}` : "Not connected";
}

function riskLabel(risk) {
  if (risk === "critical") return "Suspicious";
  if (risk === "high") return "High risk";
  if (risk === "medium") return "Warning";
  if (risk === "low") return "Safe";
  return "Scanning";
}

function renderLayers(result) {
  const layers = $("#layers");
  layers.replaceChildren();
  const source = Array.isArray(result?.layers) && result.layers.length
    ? result.layers
    : ["L1", "L2", "L3", "L4", "L5", "L6", "L7"].map((layer) => ({ layer, passed: true }));

  for (let index = 0; index < 7; index += 1) {
    const item = source[index] || { layer: `L${index + 1}`, passed: true };
    const node = document.createElement("div");
    node.className = `layer ${item.passed !== false ? "on" : ""}`;
    node.textContent = `L${index + 1}`;
    node.title = `${item.layer || `L${index + 1}`} · ${item.risk || "safe"}`;
    layers.appendChild(node);
  }
}

function renderRecent(history = []) {
  const recent = $("#recent");
  recent.replaceChildren();
  const items = Array.isArray(history) && history.length ? history.slice(-4).reverse() : [];
  if (!items.length) {
    const empty = document.createElement("li");
    empty.textContent = "No scans yet.";
    recent.appendChild(empty);
    return;
  }

  for (const item of items) {
    const row = document.createElement("li");
    const host = (() => {
      try {
        return new URL(item.url || "").hostname.replace(/^www\./, "");
      } catch {
        return "Current page";
      }
    })();
    row.textContent = `${host} · ${riskLabel(item.risk)} · ${Number.isFinite(Number(item.riskPercent)) ? `${item.riskPercent}% risk` : "review"}`;
    recent.appendChild(row);
  }
}

function render(result) {
  const riskPercent = Number.isFinite(Number(result?.riskPercent)) ? result.riskPercent : "--";
  document.body.dataset.risk = result?.risk || "waiting";
  $("#score").textContent = riskPercent === "--" ? "--" : `${Math.max(0, 100 - Number(riskPercent))}`;
  $("#risk").lastElementChild.textContent = riskLabel(result?.risk);
  $("#decision").textContent = result?.trustProfile?.label
    ? `${result.trustProfile.label} verified. Non-custodial interface; wallet confirmation still applies.`
    : result?.explanation || "Automatic read-only protection is active.";
  $("#route-status").textContent = result?.trustProfile?.label ? "Verified" : "Review";

  const ai = result?.ai;
  $("#ai-text").textContent = ai?.text || "Ask for a plain-language explanation of the latest scan.";
  $("#ai-mode").textContent = ai ? "Security Copilot ready." : "";
  renderLayers(result);
}

function renderWallet(data = {}) {
  const wallet = data.connectedWallet || {};
  const hasWallet = Boolean(wallet.address);
  $("#onboarding").classList.toggle("hidden", hasWallet);
  $("#dashboard").classList.toggle("hidden", !hasWallet);
  $("#wallet-address").textContent = shorten(wallet.address);
  $("#wallet-label").textContent = wallet.chainId ? `Wallet connected · Chain ${wallet.chainId}` : "Wallet connected";
}

function renderBuild(data = {}) {
  const integrity = data.integrityStatus || {};
  const fingerprint = data.buildFingerprint || {};
  const message = integrity.valid === false
    ? "Official UTXO verification failed. Premium features are disabled."
    : `UTXO Guard verified build${fingerprint.version ? ` · v${fingerprint.version}` : ""}.`;
  $("#build-status").textContent = message;
  $("#advanced-build-status").textContent = `${message} Build ID: ${fingerprint.buildId || "official-extension-build"}`;
}

function renderLicense(data = {}) {
  const license = data?.licenseState || {};
  const tier = String(license.tier || data?.licenseTier || "free").toLowerCase();
  const isValid = Boolean(license.valid);
  const savedKey = data?.licenseKey || "";

  document.body.dataset.license = isValid ? "paid" : "free";
  $("#license-badge").lastElementChild
    ? ($("#license-badge").lastElementChild.textContent = isValid ? "Premium" : "Free")
    : ($("#license-badge").textContent = isValid ? "Premium" : "Free");

  if (savedKey) {
    $("#license").value = savedKey;
  }

  $("#save-status").textContent = isValid
    ? `Premium active for this wallet and browser. ${tier.toUpperCase()} access.`
    : license.message || "Free protection is active. Advanced activation is optional.";
}

async function loadState() {
  const response = await send({ type: "UTXO_GET_STATE" });
  if (!response.ok) return;
  renderWallet(response.data || {});
  renderLicense(response.data || {});
  renderBuild(response.data || {});
  if (response.data?.lastAnalysis) render(response.data.lastAnalysis);
  renderRecent(response.data?.analysisHistory || []);
}

async function analyzeCurrentPage() {
  $("#decision").textContent = "Scanning silently...";
  const tab = await activeTab();
  if (!tab?.id || !tab.url) {
    $("#decision").textContent = "No active page available.";
    return;
  }

  try {
    chrome.tabs.sendMessage(tab.id, { type: "UTXO_FORCE_ANALYZE" }, async () => {
      if (chrome.runtime.lastError) {
        const response = await send({
          type: "UTXO_ANALYZE_PAGE",
          url: tab.url,
          pageText: tab.title || tab.url,
          action: "browse",
          language: navigator.language || "en",
        });
        if (response.ok) render(response.result);
        await loadState();
        return;
      }
      window.setTimeout(loadState, 900);
    });
  } catch {
    const response = await send({
      type: "UTXO_ANALYZE_PAGE",
      url: tab.url,
      pageText: tab.title || tab.url,
      action: "browse",
      language: navigator.language || "en",
    });
    if (response.ok) render(response.result);
  }
}

async function connectWallet() {
  $("#connect-wallet").textContent = "Connecting...";
  const tab = await activeTab();
  const response = await send({ type: "UTXO_CONNECT_WALLET", tabId: tab?.id, origin: tab?.url || "" });
  $("#connect-wallet").textContent = "Connect Wallet";
  if (!response.ok) {
    $("#decision").textContent = response.error || "Open a Web3 page with an injected wallet, then try again.";
    return;
  }
  await loadState();
  await analyzeCurrentPage();
}

async function checkAi() {
  $("#ai-text").textContent = "Preparing answer...";
  const response = await send({ type: "UTXO_CHECK_AI" });
  if (response.ok) {
    $("#ai-text").textContent = response.ai.text;
    $("#ai-mode").textContent = "Security Copilot ready.";
  } else {
    $("#ai-text").textContent = "AI explanation is unavailable right now. Local scoring remains active.";
    $("#ai-mode").textContent = "";
  }
}

function permissionsUrl(tabUrl) {
  try {
    const url = new URL(tabUrl || "");
    const isVestigeIndex =
      /(^|\.)vestigeindex\.com$/i.test(url.hostname) ||
      url.hostname === "localhost" ||
      url.hostname === "127.0.0.1";

    if (isVestigeIndex) {
      return `${url.origin}/utxo-permissions`;
    }
  } catch {
    // Fall through to production.
  }

  return "https://www.vestigeindex.com/utxo-permissions";
}

function upgradeUrl(tabUrl, plan = "pro", source = "utxo-guard-extension") {
  try {
    const url = new URL(tabUrl || "");
    const isVestigeIndex =
      /(^|\.)vestigeindex\.com$/i.test(url.hostname) ||
      url.hostname === "localhost" ||
      url.hostname === "127.0.0.1";
    const origin = isVestigeIndex ? url.origin : "https://www.vestigeindex.com";
    return `${origin}/utxo/upgrade?plan=${encodeURIComponent(plan)}&return=${encodeURIComponent(source)}`;
  } catch {
    return `https://www.vestigeindex.com/utxo/upgrade?plan=${encodeURIComponent(plan)}&return=${encodeURIComponent(source)}`;
  }
}

async function openPermissions() {
  const tab = await activeTab();
  chrome.tabs.create({ url: permissionsUrl(tab?.url || "") });
}

async function openUpgrade() {
  const tab = await activeTab();
  chrome.tabs.create({ url: upgradeUrl(tab?.url || "") });
}

async function saveLicense() {
  const licenseKey = $("#license").value.trim();
  $("#save-status").textContent = "Activating premium on this device...";
  const state = await send({ type: "UTXO_GET_STATE" });
  const walletAddress = state?.data?.connectedWallet?.address || "";
  const response = await send({
    type: "UTXO_SAVE_LICENSE",
    licenseKey,
    licenseTier: licenseKey ? "pro" : "free",
    walletAddress,
  });
  if (response.ok) {
    if (response.license?.linkedWalletMismatch) {
      $("#save-status").textContent = "License already linked to another wallet.";
      return;
    }
    renderLicense({
      licenseKey,
      licenseTier: response.license?.tier || "free",
      licenseState: response.license,
      licenseVerifiedAt: response.licenseVerifiedAt,
    });
    await loadState();
  } else {
    $("#save-status").textContent = "Could not activate premium access.";
  }
}

$("#connect-wallet").addEventListener("click", connectWallet);
$("#analyze").addEventListener("click", analyzeCurrentPage);
$("#check-ai").addEventListener("click", checkAi);
$("#open-permissions").addEventListener("click", openPermissions);
$("#upgrade-vestige").addEventListener("click", openUpgrade);
$("#save-license").addEventListener("click", saveLicense);
$("#settings-toggle").addEventListener("click", () => {
  document.body.dataset.view = "settings";
});
$("#settings-back").addEventListener("click", () => {
  document.body.dataset.view = "main";
});

loadState().then(() => {
  const hasWallet = !$("#dashboard").classList.contains("hidden");
  if (hasWallet) void analyzeCurrentPage();
});
