// 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/options/index.js
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;
}
function showConfirm(options) {
  return new Promise((resolve) => {
    const overlay = document.createElement("div");
    overlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.7);
      backdrop-filter: blur(4px);
      z-index: 100000;
      display: flex;
      align-items: center;
      justify-content: center;
      animation: fadeIn 0.2s ease-out;
    `;
    const modal = document.createElement("div");
    modal.style.cssText = `
      background: var(--bg-secondary);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      padding: 32px;
      max-width: 400px;
      width: 90%;
      box-shadow: var(--shadow-lg);
      animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    `;
    const title = document.createElement("h3");
    title.textContent = options.title || "Confirm";
    title.style.cssText = `
      font-size: 20px;
      font-weight: 600;
      margin: 0 0 16px 0;
      color: var(--text-primary);
    `;
    const message = document.createElement("p");
    message.textContent = options.message || "";
    message.style.cssText = `
      font-size: 14px;
      color: var(--text-secondary);
      margin: 0 0 24px 0;
      line-height: 1.5;
    `;
    const buttonContainer = document.createElement("div");
    buttonContainer.style.cssText = `
      display: flex;
      gap: 12px;
      justify-content: flex-end;
    `;
    const cancelButton = document.createElement("button");
    cancelButton.textContent = options.cancelText || "Cancel";
    cancelButton.style.cssText = `
      background: transparent;
      color: var(--text-secondary);
      border: 1px solid var(--border-color);
      padding: 10px 20px;
      border-radius: var(--radius-md);
      font-weight: 500;
      cursor: pointer;
      transition: var(--transition);
    `;
    cancelButton.onmouseenter = () => {
      cancelButton.style.borderColor = "var(--border-hover)";
      cancelButton.style.color = "var(--text-primary)";
    };
    cancelButton.onmouseleave = () => {
      cancelButton.style.borderColor = "var(--border-color)";
      cancelButton.style.color = "var(--text-secondary)";
    };
    const confirmButton = document.createElement("button");
    confirmButton.textContent = options.confirmText || "Confirm";
    confirmButton.style.cssText = `
      background: var(--danger);
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: var(--radius-md);
      font-weight: 600;
      cursor: pointer;
      transition: var(--transition);
      box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
    `;
    confirmButton.onmouseenter = () => {
      confirmButton.style.transform = "translateY(-1px)";
      confirmButton.style.boxShadow = "0 4px 12px rgba(239, 68, 68, 0.4)";
    };
    confirmButton.onmouseleave = () => {
      confirmButton.style.transform = "translateY(0)";
      confirmButton.style.boxShadow = "0 2px 8px rgba(239, 68, 68, 0.3)";
    };
    const close = (result) => {
      overlay.style.animation = "fadeOut 0.2s ease-out";
      modal.style.animation = "slideDown 0.2s ease-out";
      setTimeout(() => {
        document.body.removeChild(overlay);
        resolve(result);
      }, 200);
    };
    cancelButton.onclick = () => close(false);
    confirmButton.onclick = () => close(true);
    overlay.onclick = (e) => {
      if (e.target === overlay) close(false);
    };
    const keyHandler = (e) => {
      if (e.key === "Escape") {
        close(false);
        document.removeEventListener("keydown", keyHandler);
      } else if (e.key === "Enter") {
        close(true);
        document.removeEventListener("keydown", keyHandler);
      }
    };
    document.addEventListener("keydown", keyHandler);
    modal.appendChild(title);
    modal.appendChild(message);
    buttonContainer.appendChild(cancelButton);
    buttonContainer.appendChild(confirmButton);
    modal.appendChild(buttonContainer);
    overlay.appendChild(modal);
    document.body.appendChild(overlay);
    if (!document.getElementById("confirm-modal-styles")) {
      const style = document.createElement("style");
      style.id = "confirm-modal-styles";
      style.textContent = `
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes fadeOut {
          from { opacity: 1; }
          to { opacity: 0; }
        }
        @keyframes slideUp {
          from {
            opacity: 0;
            transform: translateY(20px) scale(0.95);
          }
          to {
            opacity: 1;
            transform: translateY(0) scale(1);
          }
        }
        @keyframes slideDown {
          from {
            opacity: 1;
            transform: translateY(0) scale(1);
          }
          to {
            opacity: 0;
            transform: translateY(20px) scale(0.95);
          }
        }
      `;
      document.head.appendChild(style);
    }
  });
}
async function loadSettings() {
  try {
    const settings = await request("settings.get");
    if (settings.autoLock !== void 0) {
      document.getElementById("autoLockToggle").classList.toggle("active", settings.autoLock);
    }
    const timeoutValue = settings.autoLockTimeout || settings.autoLockMinutes || 15;
    document.getElementById("autoLockTimeout").value = timeoutValue;
    if (settings.defaultNetwork) {
      document.getElementById("defaultNetwork").value = settings.defaultNetwork;
    }
    if (settings.analytics !== void 0) {
      document.getElementById("analyticsToggle").classList.toggle("active", settings.analytics);
    }
  } catch (error) {
    console.error("Failed to load settings:", error);
  }
}
async function saveSettings(updates) {
  try {
    await request("settings.update", updates);
    showSuccess("Settings saved");
  } catch (error) {
    console.error("Failed to save settings:", error);
    showError("Failed to save settings");
  }
}
function showSuccess(message) {
  const notification = document.createElement("div");
  notification.textContent = message;
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #10b981;
    color: white;
    padding: 12px 24px;
    border-radius: 8px;
    z-index: 10000;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
  `;
  document.body.appendChild(notification);
  setTimeout(() => notification.remove(), 3e3);
}
function showError(message) {
  const notification = document.createElement("div");
  notification.textContent = message;
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #ef4444;
    color: white;
    padding: 12px 24px;
    border-radius: 8px;
    z-index: 10000;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
  `;
  document.body.appendChild(notification);
  setTimeout(() => notification.remove(), 3e3);
}
document.getElementById("autoLockToggle").addEventListener("click", async (e) => {
  const toggle = e.currentTarget;
  const isActive = toggle.classList.contains("active");
  toggle.classList.toggle("active");
  await saveSettings({ autoLock: !isActive });
});
document.getElementById("analyticsToggle").addEventListener("click", async (e) => {
  const toggle = e.currentTarget;
  const isActive = toggle.classList.contains("active");
  toggle.classList.toggle("active");
  await saveSettings({ analytics: !isActive });
});
document.getElementById("autoLockTimeout").addEventListener("change", async (e) => {
  const minutes = parseInt(e.target.value);
  await saveSettings({ autoLockTimeout: minutes, autoLockMinutes: minutes });
});
document.getElementById("defaultNetwork").addEventListener("change", async (e) => {
  await saveSettings({ defaultNetwork: e.target.value });
});
document.getElementById("resetButton").addEventListener("click", async () => {
  const confirmed = await showConfirm({
    title: "Reset Extension",
    message: "\u26A0\uFE0F WARNING: This will permanently delete ALL data including:\n\n\u2022 All wallet accounts and keys\n\u2022 All settings and preferences\n\u2022 All permissions and connections\n\u2022 All cached data\n\nThis action CANNOT be undone. You will need to create a new wallet or import existing accounts.\n\nAre you absolutely sure you want to reset the extension?",
    confirmText: "Yes, Reset Everything",
    cancelText: "Cancel"
  });
  if (!confirmed) {
    return;
  }
  try {
    const button = document.getElementById("resetButton");
    const originalText = button.textContent;
    button.disabled = true;
    button.textContent = "Resetting...";
    await request("extension.reset");
    showSuccess("Extension reset successfully. Please reload the extension.");
    setTimeout(() => {
      window.location.reload();
    }, 2e3);
  } catch (error) {
    console.error("Reset error:", error);
    showError("Failed to reset extension: " + (error.message || "Unknown error"));
    const button = document.getElementById("resetButton");
    button.disabled = false;
  }
});
document.getElementById("exportButton").addEventListener("click", async () => {
  try {
    const data = await request("vault.export");
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `xrp-universe-wallet-backup-${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);
    showSuccess("Wallet exported successfully");
  } catch (error) {
    showError("Failed to export wallet");
  }
});
var logoImage = document.getElementById("logoImage");
if (logoImage && isRuntimeAvailable()) {
  logoImage.src = getRuntimeURL("public/xrpl universe.png");
}
var currentAccountId = null;
async function loadAccounts() {
  try {
    const accounts = await request("account.list");
    const accountsList = document.getElementById("accountsList");
    if (accounts.locked) {
      accountsList.innerHTML = `
        <div style="text-align: center; padding: 24px; color: var(--text-secondary);">
          Wallet is locked. Please unlock your wallet to view accounts.
        </div>
      `;
      return;
    }
    if (!accounts.accounts || accounts.accounts.length === 0) {
      accountsList.innerHTML = `
        <div style="text-align: center; padding: 24px; color: var(--text-secondary);">
          No accounts found.
        </div>
      `;
      return;
    }
    accountsList.innerHTML = accounts.accounts.map((account) => {
      const isActive = account.id === accounts.activeAccountId;
      return `
        <div class="account-item">
          <div class="account-info">
            <div class="account-name">
              ${account.label || "Account"}
              ${isActive ? '<span class="account-badge">Active</span>' : ""}
            </div>
            <div class="account-address">${account.address}</div>
          </div>
          <div class="account-actions">
            <button class="button button-secondary button-small" data-account-id="${account.id}" data-action="reveal-seed">
              Reveal Seed Phrase
            </button>
          </div>
        </div>
      `;
    }).join("");
    accountsList.querySelectorAll('[data-action="reveal-seed"]').forEach((btn) => {
      btn.addEventListener("click", async (e) => {
        const accountId = e.target.getAttribute("data-account-id");
        await showSeedPhraseModal(accountId);
      });
    });
  } catch (error) {
    console.error("Failed to load accounts:", error);
    const accountsList = document.getElementById("accountsList");
    accountsList.innerHTML = `
      <div style="text-align: center; padding: 24px; color: var(--danger);">
        Failed to load accounts: ${error.message}
      </div>
    `;
  }
}
async function showSeedPhraseModal(accountId) {
  currentAccountId = accountId;
  const modal = document.getElementById("seedPhraseModal");
  const passwordSection = document.getElementById("passwordSection");
  const seedPhraseDisplay = document.getElementById("seedPhraseDisplay");
  const seedPhraseError = document.getElementById("seedPhraseError");
  const passwordInput = document.getElementById("seedPhrasePassword");
  const seedPhraseBox = document.getElementById("seedPhraseBox");
  const seedPhraseRevealBtn = document.getElementById("seedPhraseRevealBtn");
  modal.classList.add("show");
  passwordSection.style.display = "block";
  seedPhraseDisplay.classList.remove("show");
  seedPhraseError.style.display = "none";
  passwordInput.value = "";
  seedPhraseBox.textContent = "";
  seedPhraseBox.classList.add("hidden");
  seedPhraseRevealBtn.style.display = "block";
  try {
    const accounts = await request("account.list");
    const account = accounts.accounts.find((acc) => acc.id === accountId);
    if (account) {
      document.getElementById("seedPhraseAccountInfo").textContent = `Account: ${account.label || "Account"} (${account.address.slice(0, 8)}...${account.address.slice(-6)})`;
    }
  } catch (error) {
    console.error("Failed to get account info:", error);
  }
  setTimeout(() => passwordInput.focus(), 100);
  const submitBtn = document.getElementById("seedPhraseSubmit");
  passwordInput.addEventListener("input", () => {
    submitBtn.disabled = !passwordInput.value.trim();
    if (submitBtn.disabled) {
      submitBtn.style.opacity = "0.5";
      submitBtn.style.cursor = "not-allowed";
    } else {
      submitBtn.style.opacity = "1";
      submitBtn.style.cursor = "pointer";
    }
  });
  submitBtn.disabled = true;
  submitBtn.style.opacity = "0.5";
  submitBtn.style.cursor = "not-allowed";
}
function hideSeedPhraseModal() {
  const modal = document.getElementById("seedPhraseModal");
  modal.classList.remove("show");
  currentAccountId = null;
}
document.getElementById("seedPhraseSubmit").addEventListener("click", async () => {
  const passwordInput = document.getElementById("seedPhrasePassword");
  const password = passwordInput.value;
  const errorDiv = document.getElementById("seedPhraseError");
  const submitBtn = document.getElementById("seedPhraseSubmit");
  if (!password) {
    errorDiv.textContent = "Please enter your password";
    errorDiv.style.display = "block";
    return;
  }
  try {
    await request("vault.validate", { password });
  } catch (error) {
    errorDiv.textContent = error.message || "Invalid password";
    errorDiv.style.display = "block";
    return;
  }
  try {
    const status = await request("vault.status");
    if (status.locked) {
      await request("vault.unlock", { password });
    }
  } catch (error) {
    errorDiv.textContent = error.message || "Failed to unlock wallet";
    errorDiv.style.display = "block";
    return;
  }
  try {
    const result = await request("account.exportSeed", { id: currentAccountId });
    if (!result.seed) {
      errorDiv.textContent = "This account does not have a seed phrase (imported with private key)";
      errorDiv.style.display = "block";
      return;
    }
    document.getElementById("passwordSection").style.display = "none";
    document.getElementById("seedPhraseDisplay").classList.add("show");
    document.getElementById("seedPhraseBox").textContent = result.seed;
  } catch (error) {
    errorDiv.textContent = error.message || "Failed to retrieve seed phrase";
    errorDiv.style.display = "block";
  }
});
document.getElementById("seedPhraseRevealBtn").addEventListener("click", () => {
  const seedPhraseBox = document.getElementById("seedPhraseBox");
  const revealBtn = document.getElementById("seedPhraseRevealBtn");
  seedPhraseBox.classList.remove("hidden");
  revealBtn.style.display = "none";
});
document.getElementById("seedPhraseCopy").addEventListener("click", async () => {
  const seedPhraseBox = document.getElementById("seedPhraseBox");
  const seedPhrase = seedPhraseBox.textContent;
  if (!seedPhrase) {
    showError("No seed phrase to copy");
    return;
  }
  try {
    await navigator.clipboard.writeText(seedPhrase);
    showSuccess("Seed phrase copied to clipboard");
  } catch (error) {
    const textarea = document.createElement("textarea");
    textarea.value = seedPhrase;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    document.body.removeChild(textarea);
    showSuccess("Seed phrase copied to clipboard");
  }
});
document.getElementById("seedPhraseClose").addEventListener("click", () => {
  hideSeedPhraseModal();
});
document.getElementById("seedPhraseModal").addEventListener("click", (e) => {
  if (e.target.id === "seedPhraseModal") {
    hideSeedPhraseModal();
  }
});
document.getElementById("seedPhrasePassword").addEventListener("keypress", (e) => {
  if (e.key === "Enter") {
    document.getElementById("seedPhraseSubmit").click();
  }
});
loadSettings();
loadAccounts();
