(() => {
  function addDebug(text) {
    let box = document.getElementById("account-api-debug");
    if (!box) {
      box = document.createElement("pre");
      box.id = "account-api-debug";
      box.style.whiteSpace = "pre-wrap";
      box.style.marginTop = "1rem";
      box.style.color = "#ffd2d2";
      box.style.fontSize = "12px";
      const hero = document.querySelector(".account-hero-card") || document.body;
      hero.appendChild(box);
    }
    box.textContent = text;
  }

  function replaceText(root, from, to) {
    const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
    const nodes = [];
    while (walker.nextNode()) nodes.push(walker.currentNode);
    for (const node of nodes) {
      if (node.nodeValue.includes(from)) node.nodeValue = node.nodeValue.replaceAll(from, to);
    }
  }

  document.addEventListener("DOMContentLoaded", async () => {
    try {
      const res = await fetch("/api/account", {
        credentials: "same-origin",
        headers: { "Accept": "application/json" },
      });

      const text = await res.text();
      addDebug(`HTTP ${res.status}\n${text}`);

      if (!res.ok) return;

      const data = JSON.parse(text);
      const email = data.email || {};
      const addr = email.address || email.email || "";
      const verified = Boolean(email.verified || email.verified_at || email.email_verified_at);
      const bbReady = Boolean(data.bb && (data.bb.ready || data.bb.created));

      const hero = document.querySelector(".account-hero-card") || document.body;

      if (data.user?.username) {
        const title = document.querySelector("#account-title");
        if (title) title.textContent = data.user.username;
      }

      if (addr) replaceText(hero, "No email address set", addr);
      if (verified) replaceText(hero, "VERIFICATION NEEDED", "VERIFIED");
      if (bbReady) replaceText(hero, "BB PASSWORD NEEDED", "BB ACCOUNT READY");
    } catch (err) {
      addDebug(String(err && err.stack || err));
    }
  });
})();
