(() => {
  "use strict";

  // ---- Niguro account on the new tab (avatar top-right + menu) ----
  // The session is niguro.com's own SSO cookie; the host reads it, validates it
  // (account.get) or clears it (account.logout). Nothing is stored by Pako.

  const bridge = window.chrome && window.chrome.webview ? window.chrome.webview : null;

  let acc = null; // {email, name, nicename, avatar, baseUrl} | null

  function ask(type) {
    if (bridge) bridge.postMessage({ type });
  }
  function post(msg) {
    if (bridge) bridge.postMessage(msg);
  }

  // ---- Lucide-style stroke icons (no emoji) ----
  const IC = {
    user: '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
    logIn: '<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/>',
    building: '<rect x="4" y="2" width="16" height="20" rx="2"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01M16 6h.01M12 6h.01M12 10h.01M12 14h.01M16 10h.01M16 14h.01M8 10h.01M8 14h.01"/>',
    pen: '<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
    bell: '<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>',
    cog: '<circle cx="12" cy="12" r="3"/><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/>',
    bookmark: '<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>',
    logout: '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>',
    external: '<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>',
    arrowRight: '<path d="M5 12h14"/><path d="M12 5l7 7-7 7"/>',
    building2: '<path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4M10 10h4M10 14h4M10 18h4"/>',
    plusCircle: '<circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/>',
    circleDollar: '<circle cx="12" cy="12" r="10"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 0 0 4H8"/><path d="M12 6v12"/>',
    flame: '<path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/>',
    search: '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>',
    layoutDashboard: '<rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/>',
    // Niguro service icons (lucide, same set niguro.com uses)
    newspaper: '<path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2"/><path d="M18 14h-8"/><path d="M15 18h-5"/><path d="M10 6h8v4h-8V6Z"/>',
    rss: '<path d="M4 11a9 9 0 0 1 9 9"/><path d="M4 4a16 16 0 0 1 16 16"/><circle cx="5" cy="19" r="1"/>',
    coffee: '<path d="M10 2v2"/><path d="M14 2v2"/><path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1"/><path d="M6 2v2"/>',
    trendingUp: '<polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/>',
    activity: '<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>',
    cloudSun: '<path d="M12 2v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="M20 12h2"/><path d="m19.07 4.93-1.41 1.41"/><path d="M15.947 12.65a4 4 0 0 0-5.925-4.128"/><path d="M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z"/>',
    fuel: '<line x1="3" y1="22" x2="15" y2="22"/><line x1="4" y1="9" x2="14" y2="9"/><path d="M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18"/><path d="M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 2 2a2 2 0 0 0 2-2V9.83a2 2 0 0 0-.59-1.42L18 5"/>',
    gem: '<path d="M6 3h12l4 6-10 13L2 9Z"/><path d="M11 3 8 9l4 13 4-13-3-6"/><path d="M2 9h20"/>',
    sparkles: '<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/>',
    calendarDays: '<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/><path d="M8 14h.01"/><path d="M12 14h.01"/><path d="M16 14h.01"/><path d="M8 18h.01"/><path d="M12 18h.01"/><path d="M16 18h.01"/>',
    usersRound: '<path d="M18 21a8 8 0 0 0-16 0"/><circle cx="10" cy="8" r="5"/><path d="M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3"/>',
    compass: '<circle cx="12" cy="12" r="10"/><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"/>',
    radio: '<path d="M4.9 19.1C1 15.2 1 8.8 4.9 4.9"/><path d="M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5"/><circle cx="12" cy="12" r="2"/><path d="M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5"/><path d="M19.1 4.9C23 8.8 23 15.2 19.1 19.1"/>',
  };
  function icon(name, cls) {
    return '<svg class="acc-ic ' + (cls || "") + '" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + (IC[name] || IC.external) + "</svg>";
  }
  function esc(s) {
    return String(s == null ? "" : s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
  }
  function initial(s) {
    const t = String(s || "?").trim();
    return t ? t[0].toUpperCase() : "?";
  }

  // ---- Styles ----
  const css = document.createElement("style");
  css.textContent = `
.acc-fixed { position: fixed; top: 18px; right: 18px; z-index: 170; font-family: inherit; }
.acc-btn { width: 36px; height: 36px; border-radius: 50%; border: 1px solid var(--border, rgba(128,140,132,.35));
  background: var(--card-solid, #fff); color: #5c6b5f; cursor: pointer; display: flex;
  align-items: center; justify-content: center; padding: 0; box-shadow: 0 1px 4px rgba(0,0,0,.12); transition: transform .12s; }
.acc-btn:hover { transform: scale(1.05); }
.acc-btn img { width: 34px; height: 34px; border-radius: 50%; object-fit: cover; display: block; }
.acc-btn .acc-ic { width: 18px; height: 18px; }
.acc-menu { position: fixed; top: 60px; right: 18px; width: 224px; z-index: 180;
  background: var(--card-solid, #fff); border: 1px solid var(--border, rgba(128,140,132,.3));
  border-radius: 12px; box-shadow: 0 12px 34px rgba(0,0,0,.22); padding: 6px; color: var(--fg, #161a16); }
.acc-head { display: flex; gap: 10px; align-items: center; padding: 10px 10px 12px; border-bottom: 1px solid var(--border, rgba(128,140,132,.2)); margin-bottom: 6px; cursor: pointer; text-decoration: none; color: inherit; }
.acc-head img { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; flex-shrink: 0; }
.acc-head .acc-av { width: 40px; height: 40px; border-radius: 50%; flex-shrink: 0; display: flex; align-items: center; justify-content: center;
  background: color-mix(in srgb, var(--accent,#04B430) 18%, transparent); color: var(--accent, #04B430); font-size: 17px; font-weight: 700; }
.acc-head .acc-av svg { width: 18px; height: 18px; }
.acc-head .acc-name { font-size: 13.5px; font-weight: 700; line-height: 1.25; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.acc-head .acc-handle { font-size: 12px; color: var(--muted, #5c6b5f); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.acc-row { display: flex; align-items: center; gap: 12px; width: 100%; text-align: left; padding: 8px 12px;
  border: 0; background: transparent; color: var(--fg, #161a16); font-size: 14px; font-family: inherit;
  border-radius: 8px; cursor: pointer; text-decoration: none; box-sizing: border-box; }
.acc-row .acc-ic.acc-orange { color: #f97316; }
.acc-row:hover .acc-ic.acc-orange { color: #f97316; }
.acc-row:hover { background: var(--hover, rgba(4,180,48,.08)); }
.acc-row .acc-ic { color: var(--muted, #5c6b5f); flex-shrink: 0; }
.acc-row:hover .acc-ic { color: var(--accent, #04B430); }
.acc-row.acc-danger { color: #e5484d; }
.acc-row.acc-danger .acc-ic { color: #e5484d; }
.acc-row.acc-danger:hover { background: rgba(229,72,77,.1); }
.acc-sep { height: 1px; background: var(--border, rgba(128,140,132,.2)); margin: 5px 4px; }
.acc-note { text-align: center; padding: 2px 10px 4px; font-size: 12px; color: var(--muted, #5c6b5f); line-height: 1.45; }
.acc-btns { display: flex; align-items: center; gap: 8px; }
.acc-svc-menu { position: fixed; top: 60px; right: 18px; width: 356px; z-index: 180;
  background: var(--card-solid, #fff); border: 1px solid var(--border, rgba(128,140,132,.3));
  border-radius: 20px; box-shadow: 0 12px 34px rgba(0,0,0,.22); padding: 12px; color: var(--fg, #161a16); }
.acc-svc-head { font-size: 13px; font-weight: 700; color: var(--muted, #5c6b5f); letter-spacing: .02em; padding: 2px 4px 10px; }
.acc-svc-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px 4px; max-height: 296px; overflow-y: auto; padding-right: 2px; }
.acc-svc-tile { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 8px 4px 6px;
  border-radius: 12px; text-decoration: none; color: var(--fg, #161a16); }
.acc-svc-tile:hover { background: var(--hover, rgba(4,180,48,.08)); }
.acc-svc-c { width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
  background: color-mix(in srgb, var(--accent,#04B430) 13%, transparent); color: var(--accent, #04B430); }
.acc-svc-c .acc-ic { width: 20px; height: 20px; }
.acc-svc-l { font-size: 11.5px; line-height: 1.2; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
.acc-svc-foot { display: flex; align-items: center; justify-content: space-between; margin-top: 8px; padding: 9px 12px;
  border-top: 1px solid var(--border, rgba(128,140,132,.2)); font-size: 13px; font-weight: 600; color: var(--fg, #161a16);
  text-decoration: none; border-radius: 10px; }
.acc-svc-foot:hover { background: var(--hover, rgba(4,180,48,.08)); }
.acc-svc-foot .acc-ic { color: var(--accent, #04B430); }
.acc-hidden { display: none !important; }
/* Smooth open: fade + tiny rise, plays whenever the menu becomes visible. */
@keyframes accPop { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }
.acc-menu, .acc-svc-menu { animation: accPop 0.15s ease-out; }
/* Wallpaper in LIGHT mode: the tray + menus keep the exact day-mode look
   (solid white card, dark text/icons) — only dark+wallpaper keeps the dark card. */
html:not([data-theme="dark"]) body.art .acc-fixed {
  --fg: #161a16;
  --muted: #5c6b5f;
  --card-solid: #ffffff;
  --border: rgba(128, 140, 132, 0.3);
  --hover: rgba(4, 180, 48, 0.08);
  color: #161a16;
}
`;
  document.head.appendChild(css);

  // ---- Build UI ----
  const holder = document.createElement("div");
  holder.className = "acc-fixed";
  holder.innerHTML =
    '<div class="acc-btns">' +
      '<button id="accSvcBtn" class="acc-btn" title="Niguro services" aria-label="Services">' + icon("layoutDashboard") + "</button>" +
      '<button id="accBtn" class="acc-btn" title="Sign in to Niguro" aria-label="Account">' + icon("user") + "</button>" +
    "</div>" +
    '<div id="accSvcMenu" class="acc-svc-menu acc-hidden"></div>' +
    '<div id="accMenu" class="acc-menu acc-hidden"></div>';
  document.body.appendChild(holder);

  const accBtn = holder.querySelector("#accBtn");
  const accMenu = holder.querySelector("#accMenu");
  const accSvcBtn = holder.querySelector("#accSvcBtn");
  const accSvcMenu = holder.querySelector("#accSvcMenu");

  // ---- Niguro services (hardcoded main services, lucide icons like niguro.com) ----
  const SERVICES_BASE = "https://www.niguro.com";
  const SERVICES = [
    { ic: "search", label: "Search", url: "/search" },
    { ic: "newspaper", label: "News", url: "/news" },
    { ic: "rss", label: "Stories", url: "/stories" },
    { ic: "coffee", label: "Cafe", url: "/cafe" },
    { ic: "trendingUp", label: "Trends", url: "/trends" },
    { ic: "activity", label: "Cricket", url: "/cricket" },
    { ic: "cloudSun", label: "Weather", url: "/weather" },
    { ic: "fuel", label: "Fuel Prices", url: "/fuel-prices" },
    { ic: "gem", label: "Gold & Silver", url: "/gold" },
    { ic: "sparkles", label: "Horoscope", url: "/horoscope" },
    { ic: "calendarDays", label: "Nepali Calendar", url: "/miti" },
    { ic: "sparkles", label: "Bhotu AI", url: "/bhotu" },
    { ic: "usersRound", label: "Communities", url: "/communities" },
    { ic: "compass", label: "Explore", url: "/explore" },
    { ic: "radio", label: "Radio", url: "/radio" },
  ];

  function renderSvcMenu() {
    const tiles = SERVICES.map((s) =>
      '<a class="acc-svc-tile" href="' + esc(SERVICES_BASE + s.url) + '">' +
        '<span class="acc-svc-c">' + icon(s.ic) + "</span>" +
        '<span class="acc-svc-l">' + esc(s.label) + "</span></a>"
    ).join("");
    accSvcMenu.innerHTML =
      '<div class="acc-svc-head">Niguro Services</div>' +
      '<div class="acc-svc-grid">' + tiles + "</div>" +
      '<a class="acc-svc-foot" href="' + esc(SERVICES_BASE + "/all") + '">View all services' + icon("arrowRight") + "</a>";
    accSvcMenu.querySelectorAll("a").forEach((el) => {
      el.addEventListener("click", (e) => {
        e.preventDefault();
        go(el.getAttribute("href") || "");
      });
    });
  }

  function toggleSvcMenu(force) {
    const open = force === undefined ? accSvcMenu.classList.contains("acc-hidden") : !!force;
    if (open) {
      renderSvcMenu();
      toggleMenu(false);
      post({ type: "ui.menu.open" }); // close chrome popups (one-dropdown rule)
    }
    accSvcMenu.classList.toggle("acc-hidden", !open);
  }

  function toggleMenu(force) {
    // force === undefined -> toggle; force === true -> open; force === false -> close.
    const open = force === undefined ? accMenu.classList.contains("acc-hidden") : !!force;
    if (open) {
      renderMenu();
      post({ type: "ui.menu.open" }); // close chrome popups (one-dropdown rule)
    }
    accMenu.classList.toggle("acc-hidden", !open);
  }

  function go(url) {
    toggleMenu(false);
    toggleSvcMenu(false);
    if (url) window.location.href = url;
  }

  function signInUrl() {
    const base = (acc && acc.baseUrl) || "https://www.niguro.com";
    // Keep niguro's own redirect allow-listing: redirect back to an in-house page.
    return base + "/nid?redirect_to=" + encodeURIComponent(base + "/");
  }

  function renderBtn() {
    accBtn.classList.remove("acc-av");
    if (acc && acc.avatar) {
      const img = document.createElement("img");
      img.src = acc.avatar;
      img.alt = "";
      img.addEventListener("error", () => {
        accBtn.innerHTML = icon("user");
        accBtn.title = acc.name || acc.email || "Niguro account";
      });
      accBtn.innerHTML = "";
      accBtn.appendChild(img);
      accBtn.title = acc.name || acc.email || "Niguro account";
    } else if (acc) {
      accBtn.innerHTML = "";
      const sp = document.createElement("span");
      sp.className = "acc-av";
      sp.textContent = initial(acc.name || acc.nicename || "N");
      accBtn.appendChild(sp);
      accBtn.title = acc.name || "Niguro account";
    } else {
      accBtn.innerHTML = icon("user");
      accBtn.title = "Sign in to Niguro";
    }
  }

  function fallbackAvatar(scope) {
    scope.querySelectorAll(".acc-head img").forEach((img) => {
      img.addEventListener("error", () => {
        const sp = document.createElement("span");
        sp.className = "acc-av";
        sp.textContent = initial(acc && (acc.name || acc.nicename || "N"));
        if (img.parentElement) img.parentElement.replaceChild(sp, img);
      });
    });
  }

  function row(ic, label, url) {
    return '<a class="acc-row" href="' + esc(url) + '">' + icon(ic) + "<span>" + esc(label) + "</span></a>";
  }

  function renderMenu() {
    const base = (acc && acc.baseUrl) || "https://www.niguro.com";
    if (!acc) {
      accMenu.innerHTML =
        '<div class="acc-note" style="padding-top:8px"><strong>Signed out</strong><br>Sign in with your Niguro ID to appear here.</div>' +
        '<div class="acc-sep"></div>' +
        '<button class="acc-row" data-go="signin">' + icon("logIn") + "<span><strong>Sign in to Niguro</strong></span></button>" +
        '<a class="acc-row" href="' + esc(base + "/signup") + '">' + icon("arrowRight") + "<span>Create an account</span></a>";
    } else {
      // Never show the email — the profile link uses the @nicename when known.
      const handle = acc.nicename ? "@" + esc(acc.nicename) : "";
      // /me on niguro.com redirects to the logged-in user's profile page.
      const profile = base + "/me";
      const avHtml = acc.avatar
        ? '<img src="' + esc(acc.avatar) + '" alt="">'
        : '<span class="acc-av">' + esc(initial(acc.name)) + "</span>";
      let m =
        '<a class="acc-head" href="' + esc(profile) + '">' + avHtml +
        '<span style="min-width:0"><div class="acc-name">' + esc(acc.name || "Niguro member") + '</div>' +
        (handle ? '<div class="acc-handle">' + handle + "</div>" : "") + "</span></a>";
      // Exactly the niguro.com header-bar avatar dropdown, minus karma.
      const consoleBase = base.replace(/^www\./i, "console.");
      const consoleSso = base + "/nid?sso=1&redirect_to=" + encodeURIComponent(consoleBase + "/dashboard");
      m += row("building2", "My Businesses", base + "/biz");
      m += row("plusCircle", "Create Community", base + "/create-community");
      m += row("pen", "Write a Story", base + "/write");
      m += row("circleDollar", "Stories Rewards", base + "/rewards");
      m += row("cog", "Settings", base + "/settings");
      m += row("bell", "Notifications", base + "/notifications");
      m += '<a class="acc-row" href="' + esc(base + "/my/streaks") + '">' + icon("flame", "acc-orange") + "<span>Search Streaks</span></a>";
      if (acc.nicename) m += row("bookmark", "Saved", base + "/u/" + encodeURIComponent(acc.nicename) + "/?tab=saved");
      m += row("search", "Search Console", consoleSso);
      if (acc.isAdmin) m += row("layoutDashboard", "Dashboard", base + "/wp-admin/");
      m += '<div class="acc-sep"></div>';
      m += '<button class="acc-row acc-danger" id="accLogout">' + icon("logout") + "<span>Log out</span></button>";
      accMenu.innerHTML = m;
      const lo = accMenu.querySelector("#accLogout");
      if (lo) lo.addEventListener("click", () => { toggleMenu(false); ask("account.logout"); });
    }
    accMenu.querySelectorAll(".acc-head, a.acc-row").forEach((el) => {
      el.addEventListener("click", (e) => {
        e.preventDefault();
        go(el.getAttribute("href") || "");
      });
    });
    fallbackAvatar(accMenu);
    const si = accMenu.querySelector('[data-go="signin"]');
    if (si) si.addEventListener("click", () => { toggleMenu(false); go(signInUrl()); });
  }

  // ---- Host messages ----
  function onMessage(e) {
    let msg = null;
    try { msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data; } catch (_) { return; }
    if (!msg || !msg.type) return;
    if (msg.type === "account.data" || msg.type === "account.changed") {
      acc = msg.account || null;
      renderBtn();
      toggleMenu(false);
    }
  }
  if (bridge) bridge.addEventListener("message", onMessage);
  window.addEventListener("message", onMessage);

  // Same close behavior as the niguro.com header bar: the button stops
  // propagation and toggles; any other click anywhere closes the menu.
  accBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    toggleMenu();
    toggleSvcMenu(false);
  });
  accSvcBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    toggleSvcMenu();
  });
  document.addEventListener("click", () => {
    if (!accMenu.classList.contains("acc-hidden")) toggleMenu(false);
    if (!accSvcMenu.classList.contains("acc-hidden")) toggleSvcMenu(false);
  });
  // The chrome asked us to close (a WPF popup opened) — one-dropdown rule, cross-layer.
  if (bridge) bridge.addEventListener("message", (e) => {
    let msg = null;
    try { msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data; } catch (_) { return; }
    if (msg && msg.type === "ui.dropdowns.close") {
      toggleMenu(false);
      toggleSvcMenu(false);
    }
  });

  // ---- Boot ----
  renderBtn();
  ask("account.get");
})();
