class P2PModalUI {
  modal = null;
  overlay = null;
  connectedPeers = /* @__PURE__ */ new Map();
  constructor() {
    this.createModal();
  }
  createModal() {
    this.overlay = document.createElement("div");
    this.overlay.className = "p2p-modal-overlay";
    this.overlay.style.cssText = `
      display: none;
      position: fixed;
      inset: 0;
      background: rgba(0, 0, 0, 0.7);
      z-index: 1000;
      align-items: center;
      justify-content: center;
    `;
    this.modal = document.createElement("div");
    this.modal.className = "p2p-modal";
    this.modal.style.cssText = `
      width: 90%;
      max-width: 650px;
      max-height: 90vh;
      background: var(--bg-sidebar, #222220);
      border: 1px solid var(--border, #3a3a36);
      border-radius: 12px;
      overflow: hidden;
      display: flex;
      flex-direction: column;
    `;
    this.overlay.appendChild(this.modal);
    document.body.appendChild(this.overlay);
    this.overlay.addEventListener("click", (e) => {
      if (e.target === this.overlay) this.hide();
    });
    this.render();
  }
  async render() {
    if (!this.modal) return;
    await this.loadConnectionHistory();
    let identityHtml = '<div class="p2p-loading">\u52A0\u8F7D\u4E2D...</div>';
    let identityData = { name: "\u672A\u77E5", did: "\u672A\u77E5", cid: "\u672A\u77E5" };
    try {
      const irohResp = await fetch("/api/iroh/init", { method: "POST" });
      const irohData = await irohResp.json();
      if (irohData.cid) {
        identityData = {
          name: irohData.name || irohData.name?.split("-").slice(-1)[0] || "Bolloon",
          did: irohData.did || "\u672A\u77E5",
          cid: irohData.cid || "\u672A\u77E5",
          nodeId: irohData.irohNodeId ? irohData.irohNodeId.substring(0, 20) + "..." : "\u672A\u77E5"
        };
      } else {
        const resp = await fetch("/api/identity");
        identityData = await resp.json();
        identityData.cid = identityData.cid || "\u672A\u521D\u59CB\u5316";
        identityData.nodeId = identityData.nodeId || "\u672A\u77E5";
      }
      identityHtml = `
        <div class="p2p-section">
          <h3>\u8EAB\u4EFD\u4FE1\u606F</h3>
          <div class="p2p-info-row">
            <span class="label">\u540D\u79F0:</span>
            <span class="value">${this.escapeHtml(identityData.name || "\u672A\u77E5")}</span>
          </div>
          <div class="p2p-info-row">
            <span class="label">CID:</span>
            <span class="value mono">${this.escapeHtml(identityData.cid || "\u672A\u77E5")}</span>
          </div>
          <div class="p2p-info-row">
            <span class="label">DID:</span>
            <span class="value mono">${this.escapeHtml(identityData.did || "\u672A\u77E5")}</span>
          </div>
          <div class="p2p-info-row">
            <span class="label">Node ID:</span>
            <span class="value mono">${this.escapeHtml(identityData.nodeId || "\u672A\u77E5")}</span>
          </div>
          <div class="p2p-actions">
            <button class="p2p-btn-secondary" id="p2p-copy-cid-btn">\u590D\u5236 CID</button>
            <button class="p2p-btn-secondary" id="p2p-copy-did-btn">\u590D\u5236 DID</button>
            <button class="p2p-btn-secondary" id="p2p-copy-nodeid-btn">\u590D\u5236 Node ID</button>
          </div>
        </div>
      `;
    } catch {
      identityHtml = '<div class="p2p-error">\u65E0\u6CD5\u52A0\u8F7D\u8EAB\u4EFD\u4FE1\u606F</div>';
    }
    this.modal.innerHTML = `
      <div class="p2p-header">
        <h2>P2P \u7F51\u7EDC</h2>
        <button class="p2p-close" id="p2p-close-btn">\xD7</button>
      </div>
      <div class="p2p-tabs">
        <button class="p2p-tab active" data-tab="identity">\u8EAB\u4EFD</button>
        <button class="p2p-tab" data-tab="connect">\u8FDE\u63A5</button>
        <button class="p2p-tab" data-tab="messages">\u6D88\u606F</button>
      </div>
      <div class="p2p-content">
        <div class="p2p-tab-content active" data-tab="identity">
          ${identityHtml}
        </div>
        <div class="p2p-tab-content" data-tab="connect">
          <div class="p2p-section">
            <h3>\u8FDE\u63A5\u5230\u8282\u70B9</h3>
            <div class="p2p-connect-form">
              <input type="text" id="p2p-connect-input" placeholder="\u8F93\u5165\u8282\u70B9 ID \u6216 CID">
              <button class="p2p-btn-primary" id="p2p-connect-btn">\u8FDE\u63A5</button>
            </div>
            <div id="p2p-connect-result" class="p2p-result"></div>
          </div>
          <div class="p2p-section">
            <h3>\u5DF2\u8FDE\u63A5\u7684\u8282\u70B9</h3>
            <div id="p2p-connected-peers" class="p2p-connected-peers">
              \u6682\u65E0\u8FDE\u63A5
            </div>
          </div>
        </div>
        <div class="p2p-tab-content" data-tab="messages">
          <div class="p2p-section">
            <h3>\u6536\u5230\u7684\u6D88\u606F</h3>
            <div id="p2p-messages-list" class="p2p-messages">
              \u6682\u65E0\u6D88\u606F
            </div>
          </div>
        </div>
      </div>
    `;
    this.bindEvents();
  }
  bindEvents() {
    if (!this.modal) return;
    const closeBtn = this.modal.querySelector("#p2p-close-btn");
    closeBtn?.addEventListener("click", () => this.hide());
    this.modal.querySelectorAll(".p2p-tab").forEach((tab) => {
      tab.addEventListener("click", (e) => {
        const target = e.target;
        const tabName = target.dataset.tab;
        if (tabName) this.switchTab(tabName);
      });
    });
    const copyCidBtn = this.modal.querySelector("#p2p-copy-cid-btn");
    copyCidBtn?.addEventListener("click", async () => {
      try {
        const irohResp = await fetch("/api/iroh/init", { method: "POST" });
        const data = await irohResp.json();
        if (data.cid) {
          await navigator.clipboard.writeText(data.cid);
          this.showToast("CID \u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F");
        }
      } catch (e) {
        console.error("\u590D\u5236\u5931\u8D25:", e);
      }
    });
    const copyDidBtn = this.modal.querySelector("#p2p-copy-did-btn");
    copyDidBtn?.addEventListener("click", async () => {
      try {
        const irohResp = await fetch("/api/iroh/init", { method: "POST" });
        const data = await irohResp.json();
        if (data.did) {
          await navigator.clipboard.writeText(data.did);
          this.showToast("DID \u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F");
        }
      } catch (e) {
        console.error("\u590D\u5236\u5931\u8D25:", e);
      }
    });
    const copyNodeIdBtn = this.modal.querySelector("#p2p-copy-nodeid-btn");
    copyNodeIdBtn?.addEventListener("click", async () => {
      try {
        const irohResp = await fetch("/api/iroh/init", { method: "POST" });
        const data = await irohResp.json();
        if (data.irohNodeId) {
          await navigator.clipboard.writeText(data.irohNodeId);
          this.showToast("Node ID \u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F");
        }
      } catch (e) {
        console.error("\u590D\u5236\u5931\u8D25:", e);
      }
    });
    const connectBtn = this.modal.querySelector("#p2p-connect-btn");
    connectBtn?.addEventListener("click", () => this.handleConnect());
  }
  switchTab(tabName) {
    if (!this.modal) return;
    this.modal.querySelectorAll(".p2p-tab").forEach((tab) => {
      tab.classList.toggle("active", tab.getAttribute("data-tab") === tabName);
    });
    this.modal.querySelectorAll(".p2p-tab-content").forEach((content) => {
      content.classList.toggle("active", content.getAttribute("data-tab") === tabName);
    });
  }
  async handleConnect() {
    const input = document.getElementById("p2p-connect-input");
    const result = document.getElementById("p2p-connect-result");
    if (!input || !result) return;
    const cid = input.value.trim();
    if (!cid) return;
    result.innerHTML = '<div class="p2p-loading">\u8FDE\u63A5\u4E2D...</div>';
    result.className = "p2p-result";
    try {
      const resp = await fetch("/api/iroh/connect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ cid })
      });
      const data = await resp.json();
      if (data.ok) {
        result.innerHTML = `<div class="p2p-success">\u8FDE\u63A5\u6210\u529F\uFF01\u8282\u70B9: ${this.escapeHtml(data.nodeName || cid.substring(0, 16))}...</div>`;
        result.className = "p2p-result success";
        input.value = "";
        try {
          await fetch("/api/p2p/history", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              cid,
              // 输入的 CID 或 Node ID
              irohNodeId: data.targetNodeId,
              did: data.targetNodeId,
              // 用 Node ID 作为 DID
              name: data.nodeName || cid.substring(0, 16)
            })
          });
        } catch (e) {
          console.error("\u4FDD\u5B58\u8FDE\u63A5\u5931\u8D25:", e);
        }
      } else {
        result.innerHTML = `<div class="p2p-error">${this.escapeHtml(data.error || "\u8FDE\u63A5\u5931\u8D25")}</div>`;
        result.className = "p2p-result error";
      }
    } catch (e) {
      const msg = e instanceof Error ? e.message : "\u8FDE\u63A5\u5931\u8D25";
      result.innerHTML = `<div class="p2p-error">${this.escapeHtml(msg)}</div>`;
      result.className = "p2p-result error";
    }
  }
  async loadConnectionHistory() {
    try {
      const resp = await fetch("/api/p2p/history");
      const history = await resp.json();
      this.connectedPeers.clear();
      for (const entry of history) {
        this.connectedPeers.set(entry.irohNodeId || entry.did, {
          nodeId: entry.irohNodeId || entry.did,
          name: entry.name || "Unknown",
          time: entry.lastConnectedAt || Date.now()
        });
      }
      this.updateConnectedPeersDisplay();
    } catch (e) {
      console.error("\u52A0\u8F7D\u8FDE\u63A5\u5386\u53F2\u5931\u8D25:", e);
    }
  }
  updateConnectedPeersDisplay() {
    const container = document.getElementById("p2p-connected-peers");
    if (!container) return;
    if (this.connectedPeers.size === 0) {
      container.innerHTML = '<div class="p2p-empty">\u6682\u65E0\u8FDE\u63A5</div>';
      return;
    }
    let html = "";
    for (const [nodeId, info] of this.connectedPeers) {
      const shortId = nodeId.substring(0, 16) + "...";
      const time = new Date(info.time).toLocaleTimeString();
      html += `
        <div class="p2p-peer-item">
          <span class="p2p-peer-name">${this.escapeHtml(info.name || shortId)}</span>
          <span class="p2p-peer-id">${shortId}</span>
          <span class="p2p-peer-time">${time}</span>
        </div>
      `;
    }
    container.innerHTML = html;
  }
  escapeHtml(str) {
    const div = document.createElement("div");
    div.textContent = str;
    return div.innerHTML;
  }
  showToast(message) {
    const toast = document.createElement("div");
    toast.className = "p2p-toast";
    toast.textContent = message;
    toast.style.cssText = `
      position: fixed;
      bottom: 24px;
      left: 50%;
      transform: translateX(-50%);
      padding: 12px 24px;
      background: var(--bg-sidebar, #222220);
      border: 1px solid var(--accent, #c4d640);
      border-radius: 8px;
      color: var(--text, #d8d8c8);
      font-size: 14px;
      z-index: 2000;
    `;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 2e3);
  }
  show() {
    if (this.overlay) {
      this.overlay.style.display = "flex";
      this.render();
    }
  }
  hide() {
    if (this.overlay) {
      this.overlay.style.display = "none";
    }
  }
}
const style = document.createElement("style");
style.textContent = `
  .p2p-modal-overlay { display: none; }
  .p2p-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid var(--border, #3a3a36);
  }
  .p2p-header h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--text, #d8d8c8);
  }
  .p2p-close {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background: var(--bg-active, #333330);
    border: 1px solid var(--border, #3a3a36);
    color: var(--text-muted, #606058);
    font-size: 20px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .p2p-close:hover {
    background: var(--error-bg, rgba(239, 68, 68, 0.1));
    border-color: var(--error, #ef4444);
    color: var(--error, #ef4444);
  }
  .p2p-tabs {
    display: flex;
    gap: 4px;
    padding: 12px 20px;
    border-bottom: 1px solid var(--border, #3a3a36);
  }
  .p2p-tab {
    padding: 8px 16px;
    background: transparent;
    border: none;
    border-radius: 6px;
    color: var(--text-secondary, #909088);
    font-size: 14px;
    cursor: pointer;
  }
  .p2p-tab:hover {
    background: var(--bg-hover, #2a2a26);
    color: var(--text, #d8d8c8);
  }
  .p2p-tab.active {
    background: var(--bg-active, #333330);
    color: var(--accent, #c4d640);
  }
  .p2p-content {
    padding: 20px;
    overflow-y: auto;
    flex: 1;
  }
  .p2p-tab-content { display: none; }
  .p2p-tab-content.active { display: block; }
  .p2p-section { margin-bottom: 20px; }
  .p2p-section h3 {
    margin: 0 0 12px 0;
    font-size: 14px;
    color: var(--text-secondary, #909088);
    font-weight: 500;
  }
  .p2p-info-row {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 0;
    border-bottom: 1px solid var(--border, #3a3a36);
  }
  .p2p-info-row .label {
    min-width: 60px;
    font-size: 13px;
    color: var(--text-secondary, #909088);
  }
  .p2p-info-row .value {
    flex: 1;
    font-size: 13px;
    color: var(--text, #d8d8c8);
  }
  .p2p-info-row .value.mono {
    font-family: 'JetBrains Mono', monospace;
    font-size: 12px;
    word-break: break-all;
  }
  .p2p-btn-primary {
    width: 100%;
    padding: 12px;
    background: var(--accent, #c4d640);
    color: var(--bg, #1a1a18);
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    margin-top: 12px;
  }
  .p2p-btn-primary:hover { opacity: 0.9; }
  .p2p-connect-form { display: flex; gap: 8px; }
  .p2p-connect-form input {
    flex: 1;
    padding: 12px;
    background: var(--bg, #1a1a18);
    border: 1px solid var(--border, #3a3a36);
    border-radius: 8px;
    color: var(--text, #d8d8c8);
    font-size: 14px;
    font-family: 'JetBrains Mono', monospace;
  }
  .p2p-connect-form input:focus {
    outline: none;
    border-color: var(--accent, #c4d640);
  }
  .p2p-result {
    margin-top: 12px;
    padding: 12px;
    border-radius: 8px;
    font-size: 14px;
  }
  .p2p-result.success {
    background: var(--success-bg, rgba(34, 197, 94, 0.1));
    border: 1px solid var(--success, #22c55e);
    color: var(--success, #22c55e);
  }
  .p2p-result.error {
    background: var(--error-bg, rgba(239, 68, 68, 0.1));
    border: 1px solid var(--error, #ef4444);
    color: var(--error, #ef4444);
  }
  .p2p-messages {
    background: var(--bg, #1a1a18);
    border: 1px solid var(--border, #3a3a36);
    border-radius: 8px;
    padding: 16px;
    color: var(--text-muted, #606058);
    font-size: 14px;
    text-align: center;
  }
  .p2p-loading, .p2p-error {
    padding: 20px;
    text-align: center;
    color: var(--text-muted, #606058);
  }
  .p2p-error { color: var(--error, #ef4444); }
  .p2p-connected-peers {
    background: var(--bg, #1a1a18);
    border: 1px solid var(--border, #3a3a36);
    border-radius: 8px;
    overflow: hidden;
  }
  .p2p-connected-peers .p2p-empty {
    padding: 16px;
    text-align: center;
    color: var(--text-muted, #606058);
    font-size: 14px;
  }
  .p2p-peer-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    border-bottom: 1px solid var(--border, #3a3a36);
  }
  .p2p-peer-item:last-child { border-bottom: none; }
  .p2p-peer-name {
    font-size: 14px;
    color: var(--text, #d8d8c8);
    min-width: 80px;
  }
  .p2p-peer-id {
    flex: 1;
    font-family: 'JetBrains Mono', monospace;
    font-size: 12px;
    color: var(--text-secondary, #909088);
  }
  .p2p-peer-time {
    font-size: 12px;
    color: var(--text-muted, #606058);
  }
`;
document.head.appendChild(style);
const p2pModal = new P2PModalUI();
window.p2pModal = p2pModal;
window.showP2PModal = () => p2pModal.show();
window.hideP2PModal = () => p2pModal.hide();
console.log("[P2P Modal] \u5DF2\u521D\u59CB\u5316");
