// 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/add-account/index.js
async function request(method, params = {}) {
  if (!isRuntimeAvailable()) {
    throw new Error("Extension context invalidated. Please reload the page.");
  }
  const response = await sendMessage({ source: MESSAGE_SOURCE, method, params });
  if (!response || !response.ok) {
    throw new Error(response?.error || "Request failed");
  }
  return response.result;
}
function showError(message) {
  const errorEl = document.getElementById("error");
  if (errorEl) {
    errorEl.textContent = message;
    errorEl.classList.add("show");
    setTimeout(() => {
      errorEl.classList.remove("show");
    }, 5e3);
  }
}
function hideError() {
  const errorEl = document.getElementById("error");
  if (errorEl) {
    errorEl.classList.remove("show");
  }
}
function setLoading(loading) {
  const btn = document.getElementById("createBtn");
  if (!btn) return;
  if (loading) {
    btn.disabled = true;
    const originalText = btn.textContent;
    btn.dataset.originalText = originalText;
    btn.innerHTML = `<span class="loading"></span>Creating...`;
  } else {
    btn.disabled = false;
    if (btn.dataset.originalText) {
      btn.textContent = btn.dataset.originalText;
    }
  }
}
var logoImage = document.getElementById("logoImage");
if (logoImage && isRuntimeAvailable()) {
  logoImage.src = getRuntimeURL("public/xrpl universe.png");
}
document.getElementById("createAccountForm")?.addEventListener("submit", async (e) => {
  e.preventDefault();
  hideError();
  const labelInput = document.getElementById("accountLabel");
  const label = labelInput?.value.trim() || `Account ${Date.now()}`;
  try {
    setLoading(true);
    const vaultStatus = await request("vault.status");
    if (vaultStatus.locked) {
      showError("Wallet is locked. Please unlock your wallet first.");
      setLoading(false);
      return;
    }
    const activeAccount = await request("account.getActive");
    let keyType = activeAccount?.keyType;
    if (!keyType || keyType !== "secp256k1" && keyType !== "ed25519") {
      keyType = "secp256k1";
    }
    await request("account.create", {
      label,
      keyType
    });
    window.close();
  } catch (error) {
    showError(error.message || "Failed to create account. Please try again.");
    setLoading(false);
  }
});
document.getElementById("cancelBtn")?.addEventListener("click", () => {
  window.close();
});
(async () => {
  try {
    const vaultStatus = await request("vault.status");
    if (!vaultStatus.exists) {
      showError("No wallet found. Please create or import a wallet first.");
      document.getElementById("createBtn").disabled = true;
    } else if (vaultStatus.locked) {
      showError("Wallet is locked. Please unlock your wallet first.");
      document.getElementById("createBtn").disabled = true;
    }
  } catch (error) {
    showError("Failed to check wallet status. Please try again.");
    console.error("Failed to check vault status:", error);
  }
})();
