// src/shared/constants.js
var MESSAGE_SOURCE = "xrpl-wallet-extension";

// src/shared/browser.js
var browserAPI = (() => {
  if (typeof browser !== "undefined" && browser.runtime && browser.runtime.getBrowserInfo) {
    return browser;
  } else if (typeof chrome !== "undefined" && chrome.runtime) {
    return chrome;
  } else if (typeof browser !== "undefined" && browser.runtime) {
    return browser;
  }
  return {
    runtime: void 0,
    storage: void 0,
    tabs: void 0,
    windows: void 0,
    action: void 0,
    browserAction: void 0
  };
})();
var storage = {
  local: {
    get: (keys) => {
      if (!browserAPI.storage || !browserAPI.storage.local) {
        throw new Error("Storage API is not available in this context");
      }
      return new Promise((resolve, reject) => {
        browserAPI.storage.local.get(keys, (result) => {
          const error = browserAPI.runtime.lastError;
          if (error) {
            reject(new Error(error.message || "Storage error"));
          } else {
            resolve(result);
          }
        });
      });
    },
    set: (items) => {
      if (!browserAPI.storage || !browserAPI.storage.local) {
        throw new Error("Storage API is not available in this context");
      }
      return new Promise((resolve, reject) => {
        browserAPI.storage.local.set(items, () => {
          const error = browserAPI.runtime.lastError;
          if (error) {
            reject(new Error(error.message || "Storage error"));
          } else {
            resolve();
          }
        });
      });
    },
    remove: (keys) => {
      if (!browserAPI.storage || !browserAPI.storage.local) {
        throw new Error("Storage API is not available in this context");
      }
      return new Promise((resolve, reject) => {
        browserAPI.storage.local.remove(keys, () => {
          const error = browserAPI.runtime.lastError;
          if (error) {
            reject(new Error(error.message || "Storage error"));
          } else {
            resolve();
          }
        });
      });
    },
    clear: () => {
      if (!browserAPI.storage || !browserAPI.storage.local) {
        throw new Error("Storage API is not available in this context");
      }
      return new Promise((resolve, reject) => {
        browserAPI.storage.local.clear(() => {
          const error = browserAPI.runtime.lastError;
          if (error) {
            reject(new Error(error.message || "Storage error"));
          } else {
            resolve();
          }
        });
      });
    },
    get onChanged() {
      if (!browserAPI.storage) {
        return void 0;
      }
      return browserAPI.storage.onChanged;
    }
  },
  session: {
    get: (keys) => {
      if (!browserAPI.storage) {
        throw new Error("Storage API is not available in this context");
      }
      return new Promise((resolve, reject) => {
        const storageArea = browserAPI.storage.session || browserAPI.storage.local;
        if (!storageArea) {
          reject(new Error("Storage API is not available in this context"));
          return;
        }
        storageArea.get(keys, (result) => {
          const error = browserAPI.runtime.lastError;
          if (error) {
            reject(new Error(error.message || "Storage error"));
          } else {
            resolve(result);
          }
        });
      });
    },
    set: (items) => {
      if (!browserAPI.storage) {
        throw new Error("Storage API is not available in this context");
      }
      return new Promise((resolve, reject) => {
        const storageArea = browserAPI.storage.session || browserAPI.storage.local;
        if (!storageArea) {
          reject(new Error("Storage API is not available in this context"));
          return;
        }
        storageArea.set(items, () => {
          const error = browserAPI.runtime.lastError;
          if (error) {
            reject(new Error(error.message || "Storage error"));
          } else {
            resolve();
          }
        });
      });
    },
    clear: () => {
      if (!browserAPI.storage) {
        throw new Error("Storage API is not available in this context");
      }
      return new Promise((resolve, reject) => {
        const storageArea = browserAPI.storage.session || browserAPI.storage.local;
        if (!storageArea) {
          reject(new Error("Storage API is not available in this context"));
          return;
        }
        storageArea.clear(() => {
          const error = browserAPI.runtime.lastError;
          if (error) {
            reject(new Error(error.message || "Storage error"));
          } else {
            resolve();
          }
        });
      });
    },
    get onChanged() {
      if (!browserAPI.storage) {
        return void 0;
      }
      return browserAPI.storage.session?.onChanged || browserAPI.storage.onChanged;
    }
  }
};
var runtime = {
  get id() {
    if (!browserAPI.runtime) {
      return void 0;
    }
    return browserAPI.runtime.id;
  },
  getURL: (path) => {
    if (!browserAPI.runtime) {
      throw new Error("Runtime API is not available in this context");
    }
    return browserAPI.runtime.getURL(path);
  },
  sendMessage: (message, responseCallback) => {
    if (!browserAPI.runtime) {
      throw new Error("Runtime API is not available in this context");
    }
    return browserAPI.runtime.sendMessage(message, responseCallback);
  },
  get onMessage() {
    if (!browserAPI.runtime) {
      return void 0;
    }
    return browserAPI.runtime.onMessage;
  },
  get onStartup() {
    if (!browserAPI.runtime) {
      return void 0;
    }
    return browserAPI.runtime.onStartup;
  },
  get onInstalled() {
    if (!browserAPI.runtime) {
      return void 0;
    }
    return browserAPI.runtime.onInstalled;
  },
  connect: (connectInfo) => {
    if (!browserAPI.runtime) {
      throw new Error("Runtime API is not available in this context");
    }
    return browserAPI.runtime.connect(connectInfo);
  },
  getPlatformInfo: (callback) => {
    if (!browserAPI.runtime) {
      callback({ os: "unknown", arch: "unknown" });
      return;
    }
    if (browserAPI.runtime.getPlatformInfo) {
      return browserAPI.runtime.getPlatformInfo(callback);
    } else {
      callback({ os: "unknown", arch: "unknown" });
    }
  },
  getManifest: () => {
    if (!browserAPI.runtime) {
      throw new Error("Runtime API is not available in this context");
    }
    return browserAPI.runtime.getManifest();
  },
  get lastError() {
    if (!browserAPI.runtime) {
      return void 0;
    }
    return browserAPI.runtime.lastError;
  },
  openOptionsPage: () => {
    if (!browserAPI.runtime) {
      throw new Error("Runtime API is not available in this context");
    }
    if (browserAPI.runtime.openOptionsPage) {
      browserAPI.runtime.openOptionsPage();
    } else {
      if (browserAPI.tabs) {
        browserAPI.tabs.create({ url: browserAPI.runtime.getURL("options/index.html") });
      } else {
        throw new Error("Tabs API is not available in this context");
      }
    }
  }
};

// src/shared/runtime.js
function extractErrorMessage(error) {
  if (!error) return "Unknown error";
  try {
    if (error.message !== void 0 && error.message !== null) {
      const msg = String(error.message);
      if (msg && msg.trim()) {
        return msg;
      }
    }
  } catch (e) {
  }
  if (typeof error === "string") {
    return error;
  }
  try {
    if (error.code !== void 0) {
      return `Error code: ${error.code}`;
    }
    if (error.name !== void 0) {
      return `Error: ${error.name}`;
    }
  } catch (e) {
  }
  if (error.toString && typeof error.toString === "function") {
    try {
      const str = error.toString();
      if (str && str !== "[object Object]" && str !== "[object Error]" && str !== "Error" && str.length > 10) {
        return str;
      }
    } catch (e) {
    }
  }
  try {
    const extracted = {};
    const props = ["message", "code", "name", "stack", "description"];
    let foundAny = false;
    for (const prop of props) {
      try {
        if (error[prop] !== void 0) {
          extracted[prop] = String(error[prop]);
          foundAny = true;
        }
      } catch (e) {
      }
    }
    if (foundAny) {
      if (extracted.message) {
        return extracted.message;
      }
      return JSON.stringify(extracted);
    }
  } catch (e) {
  }
  const errorType = error.constructor?.name || typeof error;
  return `Browser Runtime Error (${errorType}) - Unable to extract message. Check runtime.lastError.message directly.`;
}
function sendMessage(message, timeoutMs = 3e4) {
  return new Promise((resolve, reject) => {
    try {
      if (!isRuntimeAvailable()) {
        reject(new Error("Extension context invalidated. Please reload the page."));
        return;
      }
      if (!runtime || typeof runtime.sendMessage !== "function") {
        reject(new Error("Extension context invalidated. Please reload the page."));
        return;
      }
      let timeoutId = null;
      let responded = false;
      let callbackFired = false;
      const cleanup = () => {
        if (timeoutId) {
          clearTimeout(timeoutId);
          timeoutId = null;
        }
        responded = true;
      };
      timeoutId = setTimeout(() => {
        if (!responded && !callbackFired) {
          cleanup();
          console.error("[XRP Universe Runtime] Message timeout:", {
            method: message.method,
            id: message.id,
            timeoutMs,
            callbackFired
          });
          reject(new Error(`Extension did not respond within ${timeoutMs}ms. Please try again or reload the page.`));
        } else if (!responded && callbackFired) {
          console.warn("[XRP Universe Runtime] Timeout fired but callback already fired, waiting a bit longer:", {
            method: message.method,
            id: message.id
          });
        }
      }, timeoutMs);
      const wakeUpTimeout = message.method === "provider.connect" ? 100 : 50;
      ensureServiceWorkerActive(wakeUpTimeout).catch(() => {
        console.warn("[XRP Universe Runtime] Service worker wake-up failed, but continuing");
      });
      console.log("[XRP Universe Runtime] Sending message via runtime.sendMessage:", {
        method: message.method,
        id: message.id,
        runtimeId: runtime.id
      });
      runtime.sendMessage(message, (response) => {
        callbackFired = true;
        const callbackTime = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
        console.log("[Content] <- BG callback", message.id, callbackTime);
        let lastErrorMsg = null;
        let errorType = "none";
        if (runtime.lastError) {
          try {
            lastErrorMsg = runtime.lastError.message || null;
            errorType = typeof runtime.lastError;
          } catch (e) {
            lastErrorMsg = extractErrorMessage(runtime.lastError);
            errorType = "extracted";
          }
          const directMsg = (() => {
            try {
              return runtime.lastError?.message || null;
            } catch (e) {
              return null;
            }
          })();
          const errorString = lastErrorMsg || directMsg || "UNKNOWN ERROR - Unable to extract message";
          const directMsgString = directMsg || "NO MESSAGE PROPERTY";
          console.error(
            "[XRP Universe Runtime] Immediate error in sendMessage callback:",
            `method: ${message.method}, id: ${message.id}, error: ${errorString}, errorMessageDirect: ${directMsgString}, errorType: ${errorType}, timestamp: ${(/* @__PURE__ */ new Date()).toISOString()}`
          );
        }
        console.log("[XRP Universe Runtime] runtime.sendMessage callback invoked:", {
          method: message.method,
          id: message.id,
          hasResponse: !!response,
          responseValue: response,
          responseKeys: response ? Object.keys(response) : [],
          hasError: !!runtime.lastError,
          errorMessage: lastErrorMsg || runtime.lastError?.message || "none",
          responseType: response ? typeof response : "null",
          responded
        });
        if (responded) {
          console.log("[XRP Universe Runtime] Callback fired but already responded (timeout), ignoring");
          return;
        }
        cleanup();
        try {
          if (runtime.lastError) {
            let errorMsg = null;
            try {
              errorMsg = runtime.lastError.message || null;
            } catch (e) {
              errorMsg = extractErrorMessage(runtime.lastError);
            }
            if (!errorMsg) {
              errorMsg = extractErrorMessage(runtime.lastError);
            }
            const directMsg = (() => {
              try {
                return runtime.lastError?.message || null;
              } catch (e) {
                return null;
              }
            })();
            const errorString = errorMsg || directMsg || "UNKNOWN ERROR - Unable to extract message";
            const directMsgString = directMsg || "NO MESSAGE PROPERTY";
            const errorTypeString = (() => {
              try {
                return typeof runtime.lastError;
              } catch (e) {
                return "unknown";
              }
            })();
            console.error(
              "[XRP Universe Runtime] runtime.lastError detected:",
              `method: ${message.method}, id: ${message.id}, error: ${errorString}, errorMessageDirect: ${directMsgString}, errorType: ${errorTypeString}, timestamp: ${(/* @__PURE__ */ new Date()).toISOString()}`
            );
            if (errorMsg.includes("Extension context invalidated") || errorMsg.includes("message port closed") || errorMsg.includes("Receiving end does not exist") || errorMsg.includes("No SW") || errorMsg.includes("Could not establish connection") || errorMsg.includes("The message port closed") || errorMsg.includes("Could not establish connection. Receiving end does not exist") || errorMsg.includes("message channel closed") || errorMsg.includes("A listener indicated an asynchronous response")) {
              reject(new Error("Extension context invalidated. Please reload the page."));
              return;
            }
            reject(new Error(errorMsg || "Runtime error"));
            return;
          }
          if (!response) {
            console.error("[XRP Universe Runtime] No response received:", {
              method: message.method,
              id: message.id,
              hasLastError: !!runtime.lastError,
              responseValue: response,
              responseType: typeof response
            });
            reject(new Error("No response from extension. The extension may not be responding. Please check if the extension service worker is running."));
            return;
          }
          console.log("[XRP Universe Runtime] Resolving promise with response:", {
            method: message.method,
            id: message.id,
            responseOk: response?.ok,
            hasResult: !!response?.result,
            hasError: !!response?.error
          });
          resolve(response);
        } catch (error) {
          reject(new Error("Extension context invalidated. Please reload the page."));
        }
      });
    } catch (error) {
      reject(new Error("Extension context invalidated. Please reload the page."));
    }
  });
}
function getRuntimeURL(path) {
  try {
    if (!runtime?.getURL) {
      throw new Error("Extension runtime is not available");
    }
    return runtime.getURL(path);
  } catch (error) {
    console.error("Failed to get runtime URL:", error);
    return path;
  }
}
async function ensureServiceWorkerActive(timeoutMs = 3e3) {
  if (!isRuntimeAvailable()) {
    return false;
  }
  try {
    const wakeUpPromises = [
      storage.local.set({ "wakeUp": Date.now() }).catch(() => {
      }),
      storage.session.set({ "wakeUp": Date.now() }).catch(() => {
      })
    ];
    await Promise.allSettled(wakeUpPromises);
    try {
      await new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
          resolve(false);
        }, timeoutMs);
        runtime.sendMessage(
          { source: MESSAGE_SOURCE, method: "ping", id: "wakeup-check" },
          (response) => {
            clearTimeout(timeout);
            if (runtime.lastError) {
              resolve(false);
            } else {
              resolve(true);
            }
          }
        );
      });
    } catch (error) {
      console.warn("[XRP Universe] Service worker ping failed, but continuing:", extractErrorMessage(error));
    }
    return true;
  } catch (error) {
    console.warn("[XRP Universe] Service worker wake-up failed:", extractErrorMessage(error));
    return false;
  }
}
function isRuntimeAvailable() {
  try {
    if (!runtime) {
      return false;
    }
    if (!runtime.id) {
      return false;
    }
    if (typeof runtime.sendMessage !== "function") {
      return false;
    }
    return true;
  } catch (error) {
    return false;
  }
}

// src/onboarding/index.js
(function setupGlobalErrorHandler() {
  const originalConsoleError = console.error;
  console.error = function(...args) {
    const message = args.join(" ");
    if (message.includes("Vault already exists") || message.includes("already exists")) {
      return;
    }
    originalConsoleError.apply(console, args);
  };
  const handleVaultExistsError = () => {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", handleVaultExistsError);
      return;
    }
    const steps2 = ["step-welcome", "step-password", "step-seed", "step-confirm", "step-success", "step-import-type", "step-import-secret", "step-import-password"];
    steps2.forEach((step) => {
      const element = document.getElementById(step);
      if (element) {
        element.classList.toggle("hidden", step !== "step-welcome");
      }
    });
    const errorEl = document.getElementById("welcomeError");
    if (errorEl) {
      errorEl.textContent = "A wallet already exists. Please use the Import option to add accounts to your existing wallet.";
      errorEl.classList.add("show");
      setTimeout(() => {
        errorEl.classList.remove("show");
      }, 1e4);
    }
  };
  const isVaultExistsError = (error) => {
    if (!error) return false;
    const errorMessage = (error?.message || "").toLowerCase();
    const errorString = String(error).toLowerCase();
    const errorName = (error?.name || "").toLowerCase();
    const fullErrorText = `${errorMessage} ${errorString} ${errorName}`;
    const patterns = [
      "vault already exists",
      "already exists",
      "vault already"
    ];
    for (const pattern of patterns) {
      if (errorMessage.includes(pattern) || errorString.includes(pattern) || fullErrorText.includes(pattern)) {
        return true;
      }
    }
    if (error.cause) {
      return isVaultExistsError(error.cause);
    }
    if (fullErrorText.includes("error") && fullErrorText.includes("vault") && fullErrorText.includes("already")) {
      return true;
    }
    if (errorString.match(/error:\s*error:\s*vault.*already/i)) {
      return true;
    }
    return false;
  };
  window.addEventListener("unhandledrejection", (event) => {
    const error = event.reason;
    if (isVaultExistsError(error)) {
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
      const originalError = console.error;
      console.error = function() {
      };
      setTimeout(() => {
        try {
          handleVaultExistsError();
          setTimeout(() => {
            console.error = originalError;
          }, 100);
        } catch (e) {
          console.debug("Error handler error:", e);
          console.error = originalError;
        }
      }, 0);
      return;
    }
  }, true);
  window.addEventListener("error", (event) => {
    if (isVaultExistsError(event.error || new Error(event.message))) {
      event.preventDefault();
      setTimeout(() => {
        try {
          handleVaultExistsError();
        } catch (e) {
          console.debug("Error handler error:", e);
        }
      }, 0);
    }
  }, true);
})();
async function request(method, params = {}) {
  if (!isRuntimeAvailable()) {
    throw new Error("Extension context invalidated. Please reload the page.");
  }
  try {
    const response = await sendMessage({ source: MESSAGE_SOURCE, method, params });
    if (!response || !response.ok) {
      const errorMsg = response?.error || "Request failed";
      const err = new Error(errorMsg);
      const errorStr = String(errorMsg).toLowerCase();
      if (errorStr.includes("vault already exists") || errorStr.includes("already exists") || errorStr.includes("vault already")) {
        try {
          if (typeof handleVaultExistsErrorSync === "function") {
            handleVaultExistsErrorSync();
          }
        } catch (e) {
        }
        throw err;
      }
      throw err;
    }
    return response.result;
  } catch (error) {
    const errorMessage = error?.message || String(error) || "";
    const errorStr = errorMessage.toLowerCase();
    if (errorStr.includes("vault already exists") || errorStr.includes("already exists") || errorStr.includes("vault already")) {
      try {
        if (typeof handleVaultExistsErrorSync === "function") {
          handleVaultExistsErrorSync();
        }
      } catch (e) {
      }
      throw error;
    }
    throw error;
  }
}
function handleVaultExistsErrorSync() {
  if (document.readyState !== "loading") {
    const steps2 = ["step-welcome", "step-password", "step-seed", "step-confirm", "step-success", "step-import-type", "step-import-secret", "step-import-password"];
    steps2.forEach((step) => {
      const element = document.getElementById(step);
      if (element) {
        element.classList.toggle("hidden", step !== "step-welcome");
      }
    });
    const errorEl = document.getElementById("welcomeError");
    if (errorEl) {
      errorEl.textContent = "A wallet already exists. Please use the Import option to add accounts to your existing wallet.";
      errorEl.classList.add("show");
    }
  } else {
    document.addEventListener("DOMContentLoaded", handleVaultExistsErrorSync, { once: true });
  }
}
var steps = [
  "step-welcome",
  "step-password",
  "step-seed",
  "step-confirm",
  "step-success",
  "step-import-type",
  "step-import-secret",
  "step-import-password"
];
var password = "";
var seedId = "";
var seedValue = "";
var importMode = "seed";
var isLoading = false;
function showStep(id) {
  steps.forEach((step) => {
    const element = document.getElementById(step);
    if (element) {
      element.classList.toggle("hidden", step !== id);
    }
  });
}
function showError(elementId, message) {
  const errorEl = document.getElementById(elementId);
  if (errorEl) {
    errorEl.textContent = message;
    errorEl.classList.add("show");
    setTimeout(() => {
      errorEl.classList.remove("show");
    }, 5e3);
  }
}
function hideError(elementId) {
  const errorEl = document.getElementById(elementId);
  if (errorEl) {
    errorEl.classList.remove("show");
  }
}
function setLoading(buttonId, loading) {
  const button = document.getElementById(buttonId);
  if (!button) return;
  if (loading) {
    button.disabled = true;
    const originalText = button.textContent;
    button.dataset.originalText = originalText;
    button.innerHTML = `<span class="loading"></span>${originalText}`;
  } else {
    button.disabled = false;
    if (button.dataset.originalText) {
      button.textContent = button.dataset.originalText;
    }
  }
  isLoading = loading;
}
async function checkVaultStatus() {
  try {
    const status = await request("vault.status").catch((err) => {
      console.error("Failed to check vault status:", err);
      return null;
    });
    if (status && status.exists) {
      const warningEl = document.getElementById("existingVaultWarning");
      const infoEl = document.getElementById("newWalletInfo");
      if (warningEl) warningEl.style.display = "block";
      if (infoEl) infoEl.style.display = "none";
      const createBtn = document.getElementById("startCreate");
      if (createBtn) {
        createBtn.disabled = true;
        createBtn.textContent = "Wallet Already Exists";
        createBtn.title = "You already have a wallet. Use Import to add accounts.";
      }
    }
  } catch (error) {
    console.error("Failed to check vault status:", error);
  }
}
document.getElementById("startCreate")?.addEventListener("click", async () => {
  hideError("welcomeError");
  try {
    const status = await request("vault.status");
    if (status.exists) {
      showError("welcomeError", "A wallet already exists. Please use the Import option to add accounts to your existing wallet, or close this window to use your existing wallet.");
      return;
    }
  } catch (error) {
    showError("welcomeError", "Failed to check wallet status. Please try again.");
    console.error("Vault status check failed:", error);
    return;
  }
  showStep("step-password");
  document.getElementById("password").value = "";
  document.getElementById("passwordConfirm").value = "";
  document.getElementById("passwordAck").checked = false;
  hideError("passwordError");
});
document.getElementById("startImport")?.addEventListener("click", () => {
  showStep("step-import-type");
});
document.getElementById("passwordBack")?.addEventListener("click", () => {
  showStep("step-welcome");
  hideError("passwordError");
});
document.getElementById("passwordNext")?.addEventListener("click", async () => {
  if (isLoading) return;
  const pass = document.getElementById("password").value;
  const confirm = document.getElementById("passwordConfirm").value;
  const ack = document.getElementById("passwordAck").checked;
  hideError("passwordError");
  if (!pass || pass.length < 8) {
    showError("passwordError", "Password must be at least 8 characters long.");
    return;
  }
  if (pass !== confirm) {
    showError("passwordError", "Passwords do not match.");
    return;
  }
  if (!ack) {
    showError("passwordError", "Please acknowledge that the password cannot be recovered.");
    return;
  }
  try {
    setLoading("passwordNext", true);
    password = pass;
    try {
      const status = await request("vault.status");
      if (status && status.exists) {
        throw new Error("Vault already exists. Please use the Import option to add accounts to your existing wallet.");
      }
    } catch (statusError) {
      if (statusError.message.includes("already exists") || statusError.message.includes("Vault already exists")) {
        showStep("step-welcome");
        showError("welcomeError", "A wallet already exists. Please use the Import option to add accounts to your existing wallet.");
        setLoading("passwordNext", false);
        return;
      }
    }
    await request("onboarding.initVault", { password });
    const seed = await request("onboarding.generateSeed");
    seedId = seed.id;
    seedValue = seed.seed;
    document.getElementById("seedValue").textContent = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
    showStep("step-seed");
  } catch (error) {
    let errorMessage = error.message || "Failed to initialize wallet. Please try again.";
    if (errorMessage.includes("Vault already exists") || errorMessage.includes("already exists")) {
      errorMessage = "A wallet already exists. Please use the Import option to add accounts to your existing wallet.";
      showStep("step-welcome");
      showError("welcomeError", errorMessage);
    } else {
      showError("passwordError", errorMessage);
    }
  } finally {
    setLoading("passwordNext", false);
  }
});
var seedRevealed = false;
document.getElementById("seedReveal")?.addEventListener("click", () => {
  if (!seedRevealed && seedValue) {
    document.getElementById("seedValue").textContent = seedValue;
    seedRevealed = true;
    const button = document.getElementById("seedReveal");
    if (button) {
      button.textContent = "Hide Phrase";
    }
  } else {
    document.getElementById("seedValue").textContent = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
    seedRevealed = false;
    const button = document.getElementById("seedReveal");
    if (button) {
      button.textContent = "Reveal Phrase";
    }
  }
});
document.getElementById("seedNext")?.addEventListener("click", () => {
  if (!seedRevealed) {
    showError("confirmError", "Please reveal and write down your recovery phrase first.");
    return;
  }
  showStep("step-confirm");
  document.getElementById("seedConfirm").value = "";
  hideError("confirmError");
});
document.getElementById("confirmBack")?.addEventListener("click", () => {
  showStep("step-seed");
  hideError("confirmError");
});
document.getElementById("confirmNext")?.addEventListener("click", async () => {
  if (isLoading) return;
  const confirm = document.getElementById("seedConfirm").value.trim();
  hideError("confirmError");
  if (!confirm) {
    showError("confirmError", "Please enter your recovery phrase.");
    return;
  }
  if (confirm !== seedValue) {
    showError("confirmError", "Recovery phrase does not match. Please try again.");
    return;
  }
  try {
    setLoading("confirmNext", true);
    const result = await request("onboarding.confirmSeed", { id: seedId });
    document.getElementById("successAddress").textContent = result.address || "Unknown";
    showStep("step-success");
  } catch (error) {
    showError("confirmError", error.message || "Failed to confirm seed. Please try again.");
  } finally {
    setLoading("confirmNext", false);
  }
});
document.getElementById("goWallet")?.addEventListener("click", () => {
  window.close();
});
document.getElementById("importSeed")?.addEventListener("click", () => {
  importMode = "seed";
  document.getElementById("importSecretSubtitle").textContent = "Enter your seed phrase or secret key";
  document.getElementById("importValueLabel").textContent = "Seed / Secret";
  document.getElementById("importValue").placeholder = "Enter your seed phrase or secret key";
  showStep("step-import-secret");
  document.getElementById("importValue").value = "";
  hideError("importSecretError");
});
document.getElementById("importKey")?.addEventListener("click", () => {
  importMode = "private";
  document.getElementById("importSecretSubtitle").textContent = "Enter your private key";
  document.getElementById("importValueLabel").textContent = "Private Key";
  document.getElementById("importValue").placeholder = "Enter your private key";
  showStep("step-import-secret");
  document.getElementById("importValue").value = "";
  hideError("importSecretError");
});
document.getElementById("importBack")?.addEventListener("click", () => {
  showStep("step-import-type");
  hideError("importSecretError");
});
document.getElementById("importNext")?.addEventListener("click", async () => {
  const secret = document.getElementById("importValue").value.trim();
  hideError("importSecretError");
  if (!secret) {
    showError("importSecretError", "Please enter your " + (importMode === "seed" ? "seed phrase or secret key" : "private key") + ".");
    return;
  }
  let vaultExists = false;
  try {
    const status = await request("vault.status");
    vaultExists = status.exists;
  } catch (error) {
    console.error("Failed to check vault status:", error);
  }
  const titleEl = document.getElementById("importPasswordTitle");
  const subtitleEl = document.getElementById("importPasswordSubtitle");
  const labelEl = document.getElementById("importPasswordLabel");
  const confirmGroup = document.getElementById("importPasswordConfirmGroup");
  const ackGroup = document.getElementById("importAckGroup");
  if (vaultExists) {
    if (titleEl) titleEl.textContent = "Unlock Wallet";
    if (subtitleEl) subtitleEl.textContent = "Enter your existing wallet password to unlock and import this account.";
    if (labelEl) labelEl.textContent = "Wallet Password";
    if (confirmGroup) confirmGroup.style.display = "none";
    if (ackGroup) ackGroup.style.display = "none";
  } else {
    if (titleEl) titleEl.textContent = "Create Password";
    if (subtitleEl) subtitleEl.textContent = "This password encrypts your wallet. It cannot be recovered.";
    if (labelEl) labelEl.textContent = "Password (minimum 8 characters)";
    if (confirmGroup) confirmGroup.style.display = "block";
    if (ackGroup) ackGroup.style.display = "flex";
  }
  showStep("step-import-password");
  document.getElementById("importPassword").value = "";
  document.getElementById("importPasswordConfirm").value = "";
  document.getElementById("importAck").checked = false;
  hideError("importPasswordError");
});
document.getElementById("importPasswordBack")?.addEventListener("click", () => {
  showStep("step-import-secret");
  hideError("importPasswordError");
});
document.getElementById("importFinish")?.addEventListener("click", async () => {
  if (isLoading) return;
  const secret = document.getElementById("importValue").value.trim();
  const pass = document.getElementById("importPassword").value;
  const confirm = document.getElementById("importPasswordConfirm").value;
  const ack = document.getElementById("importAck").checked;
  hideError("importPasswordError");
  let vaultExists = false;
  try {
    const status = await request("vault.status");
    vaultExists = status.exists;
  } catch (error) {
    console.error("Failed to check vault status:", error);
  }
  if (!secret) {
    showError("importPasswordError", "Secret is required.");
    return;
  }
  if (!pass) {
    showError("importPasswordError", "Password is required.");
    return;
  }
  if (!vaultExists) {
    if (pass.length < 8) {
      showError("importPasswordError", "Password must be at least 8 characters long.");
      return;
    }
    if (pass !== confirm) {
      showError("importPasswordError", "Passwords do not match.");
      return;
    }
    if (!ack) {
      showError("importPasswordError", "Please acknowledge that the password cannot be recovered.");
      return;
    }
  }
  try {
    setLoading("importFinish", true);
    if (importMode === "seed") {
      await request("onboarding.importSeed", { seed: secret, password: pass });
    } else {
      await request("onboarding.importPrivateKey", {
        privateKey: secret,
        password: pass
      });
    }
    try {
      const account = await request("account.getActive");
      document.getElementById("successAddress").textContent = account?.address || "Imported";
    } catch {
      document.getElementById("successAddress").textContent = "Imported";
    }
    const successTitle = document.querySelector("#step-success h2");
    if (successTitle) {
      successTitle.textContent = "\u2705 Account Imported";
    }
    const successSubtitle = document.querySelector("#step-success .subtitle");
    if (successSubtitle) {
      successSubtitle.textContent = "Your account has been successfully imported!";
    }
    showStep("step-success");
  } catch (error) {
    let errorMessage = error.message || "Failed to import wallet. Please check your secret and try again.";
    const errorLower = errorMessage.toLowerCase();
    if (errorMessage.includes("Vault not initialized")) {
      errorMessage = "Please unlock your existing wallet first, or create a new wallet.";
    } else if (errorMessage.includes("Invalid password") || errorLower.includes("password") && (errorLower.includes("incorrect") || errorLower.includes("invalid") || errorLower.includes("decrypt") || errorLower.includes("failed"))) {
      errorMessage = "Invalid password. Please check your password and try again.";
    } else if (errorMessage.includes("Invalid secret") || errorMessage.includes("Invalid private key") || errorLower.includes("invalid") && (errorLower.includes("seed") || errorLower.includes("secret") || errorLower.includes("key"))) {
      errorMessage = "Invalid secret or private key. Please check and try again.";
    } else if (errorLower.includes("invalid")) {
      if (vaultExists) {
        errorMessage = "Invalid password. Please check your password and try again.";
      } else {
        errorMessage = "Invalid secret or private key. Please check and try again.";
      }
    }
    showError("importPasswordError", errorMessage);
  } finally {
    setLoading("importFinish", false);
  }
});
var logoImage = document.getElementById("logoImage");
if (logoImage && isRuntimeAvailable()) {
  logoImage.src = getRuntimeURL("public/xrpl universe.png");
}
function handleURLParameters() {
  const urlParams = new URLSearchParams(window.location.search);
  const mode = urlParams.get("mode");
  if (mode === "import") {
    showStep("step-import-type");
  } else {
    showStep("step-welcome");
    checkVaultStatus();
  }
}
handleURLParameters();
document.getElementById("password")?.addEventListener("keypress", (e) => {
  if (e.key === "Enter") {
    document.getElementById("passwordNext")?.click();
  }
});
document.getElementById("passwordConfirm")?.addEventListener("keypress", (e) => {
  if (e.key === "Enter") {
    document.getElementById("passwordNext")?.click();
  }
});
document.getElementById("importPassword")?.addEventListener("keypress", (e) => {
  if (e.key === "Enter") {
    document.getElementById("importFinish")?.click();
  }
});
document.getElementById("importPasswordConfirm")?.addEventListener("keypress", (e) => {
  if (e.key === "Enter") {
    document.getElementById("importFinish")?.click();
  }
});
