var __defProp = Object.defineProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};

// node_modules/@jspm/core/nodelibs/browser/process.js
var process_exports = {};
__export(process_exports, {
  _debugEnd: () => _debugEnd,
  _debugProcess: () => _debugProcess,
  _events: () => _events,
  _eventsCount: () => _eventsCount,
  _exiting: () => _exiting,
  _fatalExceptions: () => _fatalExceptions,
  _getActiveHandles: () => _getActiveHandles,
  _getActiveRequests: () => _getActiveRequests,
  _kill: () => _kill,
  _linkedBinding: () => _linkedBinding,
  _maxListeners: () => _maxListeners,
  _preload_modules: () => _preload_modules,
  _rawDebug: () => _rawDebug,
  _startProfilerIdleNotifier: () => _startProfilerIdleNotifier,
  _stopProfilerIdleNotifier: () => _stopProfilerIdleNotifier,
  _tickCallback: () => _tickCallback,
  abort: () => abort,
  addListener: () => addListener,
  allowedNodeEnvironmentFlags: () => allowedNodeEnvironmentFlags,
  arch: () => arch,
  argv: () => argv,
  argv0: () => argv0,
  assert: () => assert,
  binding: () => binding,
  browser: () => browser2,
  chdir: () => chdir,
  config: () => config,
  cpuUsage: () => cpuUsage,
  cwd: () => cwd,
  debugPort: () => debugPort,
  default: () => process,
  dlopen: () => dlopen,
  domain: () => domain,
  emit: () => emit,
  emitWarning: () => emitWarning,
  env: () => env,
  execArgv: () => execArgv,
  execPath: () => execPath,
  exit: () => exit,
  features: () => features,
  hasUncaughtExceptionCaptureCallback: () => hasUncaughtExceptionCaptureCallback,
  hrtime: () => hrtime,
  kill: () => kill,
  listeners: () => listeners,
  memoryUsage: () => memoryUsage,
  moduleLoadList: () => moduleLoadList,
  nextTick: () => nextTick,
  off: () => off,
  on: () => on,
  once: () => once,
  openStdin: () => openStdin,
  pid: () => pid,
  platform: () => platform,
  ppid: () => ppid,
  prependListener: () => prependListener,
  prependOnceListener: () => prependOnceListener,
  reallyExit: () => reallyExit,
  release: () => release,
  removeAllListeners: () => removeAllListeners,
  removeListener: () => removeListener,
  resourceUsage: () => resourceUsage,
  setSourceMapsEnabled: () => setSourceMapsEnabled,
  setUncaughtExceptionCaptureCallback: () => setUncaughtExceptionCaptureCallback,
  stderr: () => stderr,
  stdin: () => stdin,
  stdout: () => stdout,
  title: () => title,
  umask: () => umask,
  uptime: () => uptime,
  version: () => version,
  versions: () => versions
});
function unimplemented(name) {
  throw new Error("Node.js process " + name + " is not supported by JSPM core outside of Node.js");
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
  if (!draining || !currentQueue)
    return;
  draining = false;
  if (currentQueue.length) {
    queue = currentQueue.concat(queue);
  } else {
    queueIndex = -1;
  }
  if (queue.length)
    drainQueue();
}
function drainQueue() {
  if (draining)
    return;
  var timeout = setTimeout(cleanUpNextTick, 0);
  draining = true;
  var len = queue.length;
  while (len) {
    currentQueue = queue;
    queue = [];
    while (++queueIndex < len) {
      if (currentQueue)
        currentQueue[queueIndex].run();
    }
    queueIndex = -1;
    len = queue.length;
  }
  currentQueue = null;
  draining = false;
  clearTimeout(timeout);
}
function nextTick(fun) {
  var args = new Array(arguments.length - 1);
  if (arguments.length > 1) {
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
  }
  queue.push(new Item(fun, args));
  if (queue.length === 1 && !draining)
    setTimeout(drainQueue, 0);
}
function Item(fun, array) {
  this.fun = fun;
  this.array = array;
}
Item.prototype.run = function() {
  this.fun.apply(null, this.array);
};
var title = "browser";
var arch = "x64";
var platform = "browser";
var env = {
  PATH: "/usr/bin",
  LANG: typeof navigator !== "undefined" ? navigator.language + ".UTF-8" : void 0,
  PWD: "/",
  HOME: "/home",
  TMP: "/tmp"
};
var argv = ["/usr/bin/node"];
var execArgv = [];
var version = "v16.8.0";
var versions = {};
var emitWarning = function(message, type) {
  console.warn((type ? type + ": " : "") + message);
};
var binding = function(name) {
  unimplemented("binding");
};
var umask = function(mask) {
  return 0;
};
var cwd = function() {
  return "/";
};
var chdir = function(dir) {
};
var release = {
  name: "node",
  sourceUrl: "",
  headersUrl: "",
  libUrl: ""
};
function noop() {
}
var browser2 = true;
var _rawDebug = noop;
var moduleLoadList = [];
function _linkedBinding(name) {
  unimplemented("_linkedBinding");
}
var domain = {};
var _exiting = false;
var config = {};
function dlopen(name) {
  unimplemented("dlopen");
}
function _getActiveRequests() {
  return [];
}
function _getActiveHandles() {
  return [];
}
var reallyExit = noop;
var _kill = noop;
var cpuUsage = function() {
  return {};
};
var resourceUsage = cpuUsage;
var memoryUsage = cpuUsage;
var kill = noop;
var exit = noop;
var openStdin = noop;
var allowedNodeEnvironmentFlags = {};
function assert(condition, message) {
  if (!condition) throw new Error(message || "assertion error");
}
var features = {
  inspector: false,
  debug: false,
  uv: false,
  ipv6: false,
  tls_alpn: false,
  tls_sni: false,
  tls_ocsp: false,
  tls: false,
  cached_builtins: true
};
var _fatalExceptions = noop;
var setUncaughtExceptionCaptureCallback = noop;
function hasUncaughtExceptionCaptureCallback() {
  return false;
}
var _tickCallback = noop;
var _debugProcess = noop;
var _debugEnd = noop;
var _startProfilerIdleNotifier = noop;
var _stopProfilerIdleNotifier = noop;
var stdout = void 0;
var stderr = void 0;
var stdin = void 0;
var abort = noop;
var pid = 2;
var ppid = 1;
var execPath = "/bin/usr/node";
var debugPort = 9229;
var argv0 = "node";
var _preload_modules = [];
var setSourceMapsEnabled = noop;
var _performance = {
  now: typeof performance !== "undefined" ? performance.now.bind(performance) : void 0,
  timing: typeof performance !== "undefined" ? performance.timing : void 0
};
if (_performance.now === void 0) {
  nowOffset = Date.now();
  if (_performance.timing && _performance.timing.navigationStart) {
    nowOffset = _performance.timing.navigationStart;
  }
  _performance.now = () => Date.now() - nowOffset;
}
var nowOffset;
function uptime() {
  return _performance.now() / 1e3;
}
var nanoPerSec = 1e9;
function hrtime(previousTimestamp) {
  var baseNow = Math.floor((Date.now() - _performance.now()) * 1e-3);
  var clocktime = _performance.now() * 1e-3;
  var seconds = Math.floor(clocktime) + baseNow;
  var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0];
    nanoseconds = nanoseconds - previousTimestamp[1];
    if (nanoseconds < 0) {
      seconds--;
      nanoseconds += nanoPerSec;
    }
  }
  return [seconds, nanoseconds];
}
hrtime.bigint = function(time) {
  var diff = hrtime(time);
  if (typeof BigInt === "undefined") {
    return diff[0] * nanoPerSec + diff[1];
  }
  return BigInt(diff[0] * nanoPerSec) + BigInt(diff[1]);
};
var _maxListeners = 10;
var _events = {};
var _eventsCount = 0;
function on() {
  return process;
}
var addListener = on;
var once = on;
var off = on;
var removeListener = on;
var removeAllListeners = on;
var emit = noop;
var prependListener = on;
var prependOnceListener = on;
function listeners(name) {
  return [];
}
var process = {
  version,
  versions,
  arch,
  platform,
  browser: browser2,
  release,
  _rawDebug,
  moduleLoadList,
  binding,
  _linkedBinding,
  _events,
  _eventsCount,
  _maxListeners,
  on,
  addListener,
  once,
  off,
  removeListener,
  removeAllListeners,
  emit,
  prependListener,
  prependOnceListener,
  listeners,
  domain,
  _exiting,
  config,
  dlopen,
  uptime,
  _getActiveRequests,
  _getActiveHandles,
  reallyExit,
  _kill,
  cpuUsage,
  resourceUsage,
  memoryUsage,
  kill,
  exit,
  openStdin,
  allowedNodeEnvironmentFlags,
  assert,
  features,
  _fatalExceptions,
  setUncaughtExceptionCaptureCallback,
  hasUncaughtExceptionCaptureCallback,
  emitWarning,
  nextTick,
  _tickCallback,
  _debugProcess,
  _debugEnd,
  _startProfilerIdleNotifier,
  _stopProfilerIdleNotifier,
  stdout,
  stdin,
  stderr,
  abort,
  umask,
  chdir,
  cwd,
  env,
  title,
  argv,
  execArgv,
  pid,
  ppid,
  execPath,
  debugPort,
  hrtime,
  argv0,
  _preload_modules,
  setSourceMapsEnabled
};

// 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");
      }
    }
  }
};
var tabs = {
  query: (queryInfo, callback) => {
    if (!browserAPI.tabs) {
      throw new Error("Tabs API is not available in this context");
    }
    return browserAPI.tabs.query(queryInfo, callback);
  },
  get: (tabId, callback) => {
    if (!browserAPI.tabs) {
      throw new Error("Tabs API is not available in this context");
    }
    return browserAPI.tabs.get(tabId, callback);
  },
  create: (createProperties, callback) => {
    if (!browserAPI.tabs) {
      throw new Error("Tabs API is not available in this context");
    }
    return browserAPI.tabs.create(createProperties, callback);
  },
  sendMessage: (tabId, message, responseCallback) => {
    if (!browserAPI.tabs) {
      throw new Error("Tabs API is not available in this context");
    }
    return browserAPI.tabs.sendMessage(tabId, message, responseCallback);
  },
  get onUpdated() {
    if (!browserAPI.tabs) {
      return void 0;
    }
    return browserAPI.tabs.onUpdated;
  }
};

// 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."));
    }
  });
}
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/nft/index.js
var FRONTEND_URL = typeof process_exports !== "undefined" && "http://localhost:3000" ? "http://localhost:3000" : "http://localhost:3000";
async function request(method, params = {}) {
  if (!isRuntimeAvailable()) {
    throw new Error("Extension context invalidated. Please reload the extension.");
  }
  const response = await sendMessage({ source: MESSAGE_SOURCE, method, params });
  if (!response || !response.ok) {
    throw new Error(response?.error || "Request failed");
  }
  return response.result;
}
var activeAccount = null;
var selectedNft = null;
var nfts = [];
function formatAddress(address) {
  if (!address) return "-";
  return `${address.slice(0, 6)}...${address.slice(-4)}`;
}
function formatTokenId(tokenId) {
  if (!tokenId) return "-";
  return `${tokenId.slice(0, 8)}...${tokenId.slice(-6)}`;
}
function showLoading() {
  document.getElementById("loadingState").style.display = "flex";
  document.getElementById("errorState").style.display = "none";
  document.getElementById("emptyState").style.display = "none";
  document.getElementById("nftGrid").style.display = "none";
  document.getElementById("statsBar").style.display = "none";
}
function showError(message) {
  document.getElementById("loadingState").style.display = "none";
  document.getElementById("errorState").style.display = "block";
  document.getElementById("emptyState").style.display = "none";
  document.getElementById("nftGrid").style.display = "none";
  document.getElementById("statsBar").style.display = "none";
  document.getElementById("errorMessage").textContent = message || "Failed to load NFTs";
}
function showEmpty() {
  document.getElementById("loadingState").style.display = "none";
  document.getElementById("errorState").style.display = "none";
  document.getElementById("emptyState").style.display = "block";
  document.getElementById("nftGrid").style.display = "none";
  document.getElementById("statsBar").style.display = "none";
}
function showNfts(items) {
  document.getElementById("loadingState").style.display = "none";
  document.getElementById("errorState").style.display = "none";
  document.getElementById("emptyState").style.display = "none";
  document.getElementById("nftGrid").style.display = "grid";
  document.getElementById("statsBar").style.display = "flex";
  nfts = items || [];
  document.getElementById("totalNfts").textContent = nfts.length;
  renderGrid(nfts);
}
async function loadNfts() {
  try {
    showLoading();
    const accounts = await request("account.list");
    if (accounts.locked) {
      showError("Wallet is locked. Please unlock your wallet first.");
      return;
    }
    activeAccount = accounts.accounts.find((entry) => entry.id === accounts.activeAccountId) || accounts.accounts[0];
    if (!activeAccount) {
      showError("No active account found.");
      return;
    }
    document.getElementById("accountBadge").textContent = formatAddress(activeAccount.address);
    const nftData = await request("nft.list", { address: activeAccount.address });
    const items = nftData.items || [];
    if (items.length === 0) {
      showEmpty();
    } else {
      showNfts(items);
    }
  } catch (error) {
    console.error("Failed to load NFTs:", error);
    showError(error.message || "Failed to load NFTs. Please try again.");
  }
}
function renderGrid(items) {
  const grid = document.getElementById("nftGrid");
  grid.innerHTML = "";
  items.forEach((item) => {
    const card = document.createElement("div");
    card.className = "nft-card";
    const name = item.meta?.name || item.meta?.name || `NFT ${formatTokenId(item.NFTokenID)}`;
    const image = item.image || item.meta?.image;
    card.innerHTML = `
      <div class="nft-image-container">
        ${image ? `<img src="${image}" alt="${name}" class="nft-image" onerror="this.parentElement.innerHTML='<div class=\\'nft-placeholder\\'>\u{1F5BC}\uFE0F</div>'">` : `<div class="nft-placeholder">\u{1F5BC}\uFE0F</div>`}
      </div>
      <div class="nft-info">
        <div class="nft-name">${name}</div>
        <div class="nft-id">${formatTokenId(item.NFTokenID)}</div>
      </div>
    `;
    card.addEventListener("click", () => showNftDetails(item));
    grid.appendChild(card);
  });
}
function showNftDetails(item) {
  selectedNft = item;
  const modal = document.getElementById("nftModal");
  const modalBody = document.getElementById("modalBody");
  const modalTitle = document.getElementById("modalTitle");
  const name = item.meta?.name || item.meta?.name || `NFT ${formatTokenId(item.NFTokenID)}`;
  const image = item.image || item.meta?.image;
  const description = item.meta?.description || item.meta?.description || "No description available";
  modalTitle.textContent = name;
  modalBody.innerHTML = `
    ${image ? `<img src="${image}" alt="${name}" class="modal-image" onerror="this.style.display='none'">` : `<div class="modal-image" style="display: flex; align-items: center; justify-content: center; font-size: 64px; color: var(--text-tertiary);">\u{1F5BC}\uFE0F</div>`}
    <div class="modal-details">
      <div class="detail-row">
        <span class="detail-label">Name</span>
        <span class="detail-value">${name}</span>
      </div>
      <div class="detail-row">
        <span class="detail-label">Token ID</span>
        <span class="detail-value">${item.NFTokenID}</span>
      </div>
      <div class="detail-row">
        <span class="detail-label">Issuer</span>
        <span class="detail-value">${formatAddress(item.Issuer)}</span>
      </div>
      <div class="detail-row">
        <span class="detail-label">Owner</span>
        <span class="detail-value">${formatAddress(activeAccount?.address)}</span>
      </div>
      ${item.URI ? `
      <div class="detail-row">
        <span class="detail-label">URI</span>
        <span class="detail-value">${item.URI.length > 40 ? formatTokenId(item.URI) : item.URI}</span>
      </div>
      ` : ""}
      ${description && description !== "No description available" ? `
      <div class="detail-row">
        <span class="detail-label">Description</span>
        <span class="detail-value" style="text-align: left; font-family: var(--font-sans); max-width: 100%;">${description}</span>
      </div>
      ` : ""}
    </div>
    <div class="modal-actions">
      <button class="btn btn-secondary" id="viewOnExplorer">View on Explorer</button>
      <button class="btn btn-secondary" id="copyTokenId">Copy Token ID</button>
    </div>
  `;
  document.getElementById("viewOnExplorer").addEventListener("click", () => {
    const network = "testnet";
    const explorerUrl = network === "mainnet" ? `https://xrpscan.com/nft/${item.NFTokenID}` : `https://testnet.xrpscan.com/nft/${item.NFTokenID}`;
    tabs.create({ url: explorerUrl });
  });
  document.getElementById("copyTokenId").addEventListener("click", async () => {
    try {
      await navigator.clipboard.writeText(item.NFTokenID);
      const btn = document.getElementById("copyTokenId");
      const originalText = btn.textContent;
      btn.textContent = "Copied!";
      setTimeout(() => {
        btn.textContent = originalText;
      }, 2e3);
    } catch (error) {
      console.error("Failed to copy:", error);
    }
  });
  modal.classList.add("active");
}
function closeModal() {
  const modal = document.getElementById("nftModal");
  modal.classList.remove("active");
}
document.getElementById("backBtn").addEventListener("click", () => {
  window.close();
});
document.getElementById("marketplaceBtn").addEventListener("click", () => {
  tabs.create({ url: `${FRONTEND_URL}/collections` });
});
document.getElementById("emptyMarketplaceBtn").addEventListener("click", () => {
  tabs.create({ url: `${FRONTEND_URL}/collections` });
});
document.getElementById("retryBtn").addEventListener("click", () => {
  loadNfts();
});
document.getElementById("modalClose").addEventListener("click", closeModal);
document.getElementById("nftModal").addEventListener("click", (e) => {
  if (e.target.id === "nftModal") {
    closeModal();
  }
});
document.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    closeModal();
  }
});
loadNfts();
