import type { WalletStatus } from "./types";

const byId = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
const form = byId<HTMLFormElement>("import-form");
const imageInput = byId<HTMLInputElement>("wallet-image");
const passwordInput = byId<HTMLInputElement>("image-password");
const importButton = byId<HTMLButtonElement>("import-button");
const notice = byId<HTMLParagraphElement>("notice");

void send("status").then((status) => {
  const walletStatus = status as WalletStatus;
  byId("selected-network").textContent = walletStatus.networkName;
}).catch((error) => {
  notice.textContent = errorText(error);
});

function bytesToBase64(bytes: Uint8Array): string {
  let binary = "";
  const chunkSize = 0x8000;
  for (let offset = 0; offset < bytes.length; offset += chunkSize) {
    binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
  }
  return btoa(binary);
}

function errorText(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}

async function send(type: string, values: Record<string, unknown> = {}) {
  const response = await chrome.runtime.sendMessage({ type, ...values });
  if (!response?.ok) throw new Error(response?.error ?? "Wallet request failed.");
  return response.result;
}

imageInput.addEventListener("change", () => {
  byId("image-file-name").textContent =
    imageInput.files?.[0]?.name ?? "Choose wallet image";
  notice.textContent = "";
});

byId("reveal-password").addEventListener("click", (event) => {
  const button = event.currentTarget as HTMLButtonElement;
  const showing = passwordInput.type === "text";
  passwordInput.type = showing ? "password" : "text";
  button.textContent = showing ? "Show" : "Hide";
});

form.addEventListener("submit", (event) => {
  event.preventDefault();
  void (async () => {
    const file = imageInput.files?.[0];
    if (!file) throw new Error("Choose a wallet image.");
    if (!passwordInput.value.trim()) throw new Error("Enter the wallet image encryption key.");

    notice.textContent = "";
    importButton.disabled = true;
    importButton.textContent = "Importing wallet...";

    const imageBase64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
    const status = await send("import-wallet-image", {
      imageBase64,
      imagePassword: passwordInput.value,
      password: passwordInput.value
    }) as WalletStatus;

    passwordInput.value = "";
    byId("imported-address").textContent = status.address ?? "Imported wallet";
    byId("import-panel").hidden = true;
    byId("success-panel").hidden = false;
  })().catch((error) => {
    notice.textContent = errorText(error);
    importButton.disabled = false;
    importButton.textContent = "Import wallet";
  });
});

byId("close-page").addEventListener("click", () => window.close());
