const $ = (id) => document.getElementById(id);
const registerForm = $("registerForm");
const paymentForm = $("paymentForm");
const registerBtn = $("registerBtn");
const quoteBtn = $("quoteBtn");
const statusDiv = $("status");

const DEFAULT_BACKEND = "http://127.0.0.1:5000"; // For local dev, but we should probably use the vercel one or let the user config it? Wait, let's hardcode localhost for dev, but the prompt says the backend is hosted at https://chrome-hostinger.vercel.app/. I will use the vercel one.

const BACKEND = "https://chrome-hostinger.vercel.app";

function showStatus(msg, isError = false) {
  statusDiv.textContent = msg;
  statusDiv.className = isError ? "error" : "success";
}

async function req(path, body) {
  try {
    const res = await fetch(`${BACKEND}${path}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || "Request failed");
    return data;
  } catch (err) {
    showStatus(err.message, true);
    throw err;
  }
}

async function getPaymentDetailsFromPage() {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tab && tab.id) {
      chrome.tabs.sendMessage(tab.id, { action: "getPaymentDetails" }, (response) => {
        if (chrome.runtime.lastError) {
          // Content script not loaded or not on a supported page
          return;
        }
        if (response) {
          if (response.address) $("payAddress").value = response.address;
          if (response.amount) $("payAmount").value = response.amount;
        }
      });
    }
  } catch (err) {
    console.error("Failed to fetch details from page:", err);
  }
}

async function init() {
  const saved = await chrome.storage.local.get("uid");
  if (saved.uid) {
    registerForm.classList.add("hidden");
    paymentForm.classList.remove("hidden");
    getPaymentDetailsFromPage();
  } else {
    registerForm.classList.remove("hidden");
    paymentForm.classList.add("hidden");
  }
}

registerBtn.addEventListener("click", async () => {
  registerBtn.disabled = true;
  showStatus("Registering KYC details...");
  try {
    const data = await req("/register", {
      name: $("regName").value || "Test User",
      phone: $("regPhone").value || "+2541111111111",
      dob: $("regDob").value || "01/01/1990",
      address: $("regAddress").value || "Nairobi",
      id_type: $("regIdType").value || "national_id",
      id_number: $("regIdNumber").value || "12345678"
    });
    await chrome.storage.local.set({ uid: data.uid });
    showStatus("Registered successfully!");
    setTimeout(init, 1000);
  } finally {
    registerBtn.disabled = false;
  }
});

quoteBtn.addEventListener("click", async () => {
  quoteBtn.disabled = true;
  showStatus("Initiating payment...");
  try {
    const saved = await chrome.storage.local.get("uid");
    const data = await req("/quote", {
      uid: saved.uid,
      usdc_amount: parseFloat($("payAmount").value),
      hostinger_address: $("payAddress").value
    });
    showStatus(`Payment initiated! Please check your phone to approve ${data.amount_fiat} MWK (KES for sandbox).`);
  } finally {
    quoteBtn.disabled = false;
  }
});

init();
