// dashboard-persistent-topbar-actions-sear.js — extracted verbatim from dashboard.js (pure move).

// ── Persistent topbar actions (Search / Inbox / + New) ──────────────
function wireTopbarActions() {
  // Search → opens command palette (same as Ctrl+K).
  const searchBtn = $("#topbar-search-btn");
  if (searchBtn) {
    searchBtn.addEventListener("click", () => {
      logTelemetry("header", "search_open");
      openCommandPalette();
    });
  }

  // Inbox → navigate to inbox route.
  const inboxBtn = $("#topbar-inbox-btn");
  if (inboxBtn) {
    inboxBtn.addEventListener("click", () => {
      logTelemetry("header", "inbox_open");
      navigate("inbox");
    });
  }

  // Notifications bell → navigate to the notification center.
  const notifBtn = $("#topbar-notif-btn");
  if (notifBtn) {
    notifBtn.addEventListener("click", () => {
      logTelemetry("header", "notifications_open");
      navigate("notifications");
    });
  }

  // Workspace switcher → toggle dropdown.
  const wsBtn = $("#topbar-ws-btn");
  const wsMenu = $("#topbar-ws-menu");
  if (wsBtn && wsMenu) {
    wsBtn.addEventListener("click", (e) => {
      e.stopPropagation();
      wsMenu.hidden = !wsMenu.hidden;
    });
    document.addEventListener("click", (e) => {
      if (
        !wsMenu.hidden &&
        !wsMenu.contains(e.target) &&
        e.target !== wsBtn &&
        !wsBtn.contains(e.target)
      ) {
        wsMenu.hidden = true;
      }
    });
  }

  // + New → toggle dropdown menu.
  const newBtn = $("#topbar-new-btn");
  const newMenu = $("#topbar-new-menu");
  if (newBtn && newMenu) {
    populateNewMenu(newMenu);
    newBtn.addEventListener("click", (e) => {
      e.stopPropagation();
      const wasHidden = newMenu.hidden;
      newMenu.hidden = !newMenu.hidden;
      if (wasHidden) logTelemetry("header", "new_menu_open");
    });
    // Close menu on outside click or Escape.
    document.addEventListener("click", (e) => {
      if (!newMenu.hidden && !newMenu.contains(e.target) && e.target !== newBtn) {
        newMenu.hidden = true;
      }
    });
    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape" && !newMenu.hidden) newMenu.hidden = true;
    });
  }

  // Account picker → toggle dropdown menu.
  const accBtn = $("#topbar-account-btn");
  const accMenu = $("#topbar-account-menu");
  if (accBtn && accMenu) {
    accBtn.addEventListener("click", (e) => {
      e.stopPropagation();
      const wasHidden = accMenu.hidden;
      if (wasHidden) {
        // Repopulate every time it opens — accounts cache may have changed
        populateAccountMenu(accMenu);
        logTelemetry("header", "account_picker_open");
      }
      accMenu.hidden = !accMenu.hidden;
    });
    document.addEventListener("click", (e) => {
      if (!accMenu.hidden && !accMenu.contains(e.target) && e.target !== accBtn) {
        accMenu.hidden = true;
      }
    });
    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape" && !accMenu.hidden) accMenu.hidden = true;
    });
  }
}

// Populate the account picker dropdown. Reads dashboardState.cache.accounts
// (populated by buildSidebar's apiCached("accounts-all") call). Groups by
// platform, shows a status dot per account, supports an "All accounts"
// reset row at the top.
function populateAccountMenu(menu) {
  menu.innerHTML = "";
  const accts = dashboardState.cache.accounts || {};
  const platforms = [
    { key: "twitter", label: "X / Twitter", icon: "bird", list: accts.twitter || [] },
    { key: "linkedin", label: "LinkedIn", icon: "briefcase", list: accts.linkedin || [] },
    { key: "telegram", label: "Telegram", icon: "message", list: accts.telegram || [] },
    { key: "smtp", label: "Email", icon: "mail", list: accts.smtp || [] },
  ];
  const totalCount = platforms.reduce((s, p) => s + p.list.length, 0);
  const ctx = dashboardState.contextAccount;

  // "All accounts" reset row
  const allRow = el(
    "div",
    {
      class: `topbar-account-menu-item${ctx === null ? " active" : ""}`,
      onclick: (e) => {
        e.stopPropagation();
        dashboardState.contextAccount = null;
        refreshAccountPickerLabel();
        menu.hidden = true;
        logTelemetry("header", "account_context_clear");
        // Re-render the current page so any context-aware filter clears immediately.
        try {
          handleRoute();
        } catch {}
      },
    },
    [
      el("span", { class: "topbar-account-dot online" }),
      el("span", {}, "All accounts"),
      el("span", { class: "topbar-account-menu-item-platform" }, `${totalCount}`),
    ],
  );
  menu.appendChild(allRow);
  menu.appendChild(el("div", { class: "topbar-account-menu-divider" }));

  let renderedAny = false;
  for (const p of platforms) {
    if (p.list.length === 0) continue;
    renderedAny = true;
    menu.appendChild(
      el(
        "div",
        { class: "topbar-account-menu-section" },
        `${icon.for(p.icon) ? iconHtml(icon.for(p.icon)) : p.icon} ${p.label}`,
      ),
    );
    for (const a of p.list) {
      const label = a.account_identifier
        ? `@${a.account_identifier}`
        : a.label || a.identifier || a.email || a.phone || `Account ${a.id}`;
      const dotClass =
        a.status === "active" ? "online" : a.status === "rate_limited" ? "warning" : "offline";
      const isActive = ctx && ctx.platform === p.key && String(ctx.id) === String(a.id);
      menu.appendChild(
        el(
          "div",
          {
            class: `topbar-account-menu-item${isActive ? " active" : ""}`,
            onclick: (e) => {
              e.stopPropagation();
              dashboardState.contextAccount = {
                platform: p.key,
                id: a.id,
                label,
                status: a.status || null,
              };
              refreshAccountPickerLabel();
              menu.hidden = true;
              toast(`Context: ${label}`, "ok");
              logTelemetry("header", "account_context_set", { platform: p.key });
              // Re-render the current page so context-aware filters apply immediately.
              try {
                handleRoute();
              } catch {}
            },
          },
          [
            el("span", { class: `topbar-account-dot ${dotClass}` }),
            el("span", {}, label),
            el("span", { class: "topbar-account-menu-item-platform" }, p.key),
          ],
        ),
      );
    }
  }

  if (!renderedAny) {
    menu.appendChild(
      el(
        "div",
        {
          class: "topbar-account-menu-section",
          style:
            "padding:14px 12px;color:var(--text-3);font-size:12px;text-transform:none;letter-spacing:0;",
        },
        "No accounts connected yet.",
      ),
    );
    menu.appendChild(
      el(
        "div",
        {
          class: "topbar-account-menu-item",
          onclick: () => {
            menu.hidden = true;
            navigate("accounts");
          },
        },
        [el("span", {}, icon("link")), el("span", {}, "Connect an account")],
      ),
    );
  }
}

// Update the picker button's label + dot to reflect dashboardState.contextAccount.
// Called after a selection or after accounts cache refreshes.
function refreshAccountPickerLabel() {
  const lbl = $("#topbar-account-label");
  const dot = $("#topbar-account-dot");
  if (!lbl || !dot) return;
  const ctx = dashboardState.contextAccount;
  if (!ctx) {
    lbl.textContent = "All accounts";
    dot.className = "topbar-account-dot online";
  } else {
    lbl.textContent = ctx.label;
    const dotClass =
      ctx.status === "active" ? "online" : ctx.status === "rate_limited" ? "warning" : "offline";
    dot.className = `topbar-account-dot ${dotClass}`;
  }
  refreshContextBar();
}

// Render the context bar at the top of the content area when contextAccount
// is set. Shows the selected account + platform + a Clear button. When no
// account is selected, the mount is empty (zero visual weight).
//
// Note: page renderers don't read contextAccount yet — this bar is the user's
// signal that "we know which account you mean." Filter integration is a
// separate pass that touches Campaigns, Signals, CRM, Outreach Queue.
function refreshContextBar() {
  const mount = $("#context-bar-mount");
  if (!mount) return;
  const ctx = dashboardState.contextAccount;
  if (!ctx) {
    mount.innerHTML = "";
    return;
  }

  mount.innerHTML = "";
  const platformPretty =
    {
      twitter: "X / Twitter",
      linkedin: "LinkedIn",
      telegram: "Telegram",
      smtp: "Email",
    }[ctx.platform] || ctx.platform;

  const bar = el("div", { class: "context-bar" }, [
    el("span", { class: "context-bar-dot" }),
    el("span", {}, "Working as"),
    el("span", { class: "context-bar-label" }, ctx.label),
    el("span", { class: "context-bar-platform" }, platformPretty),
    el("span", { class: "context-bar-spacer" }),
    el(
      "button",
      {
        class: "context-bar-clear",
        type: "button",
        onclick: () => {
          dashboardState.contextAccount = null;
          refreshAccountPickerLabel();
          toast("Context cleared", "info", 1500);
        },
      },
      "× Clear",
    ),
  ]);
  mount.appendChild(bar);
}

function populateNewMenu(menu) {
  // Phase 2 IA: + New collapses to TWO items only.
  //   • Operations Center is the canonical launch surface — every op flows through it.
  //   • Add (data) opens a drawer to create CRM nouns (contact / company / deal).
  // Everything else (Campaign / Signal / VC / DM / Email / Sequence) lives in
  // the Operations catalog — discoverable, filterable, and uses the unified flow.
  const groups = [
    {
      section: "Launch",
      items: [
        {
          icon: "settings",
          label: "New Operation",
          route: "operations",
          hint: "Browse catalog → pick accounts → launch",
        },
      ],
    },
    {
      section: "Add",
      items: [
        {
          icon: "folder",
          label: "Contact",
          route: "crm",
          action: () => {
            navigate("crm");
            setTimeout(() => {
              try {
                openCrmAddContactDrawer && openCrmAddContactDrawer();
              } catch {}
            }, 250);
          },
        },
        {
          icon: "building",
          label: "Company",
          route: "crm",
          action: () => {
            navigate("crm");
            setTimeout(() => {
              try {
                openCrmAddCompanyDrawer && openCrmAddCompanyDrawer();
              } catch {}
            }, 250);
          },
        },
        { icon: "money", label: "Deal", route: "deals" },
        { icon: "inbox", label: "Import contacts (CSV)", route: "import" },
      ],
    },
  ];

  menu.innerHTML = "";
  for (const group of groups) {
    menu.appendChild(el("div", { class: "topbar-new-menu-section" }, group.section));
    for (const item of group.items) {
      const row = el(
        "div",
        {
          class: "topbar-new-menu-item",
          onclick: (e) => {
            e.stopPropagation();
            menu.hidden = true;
            logTelemetry("campaign", "new_menu_item_click", {
              label: item.label,
              route: item.route,
            });
            if (item.action) item.action();
            else navigate(item.route);
          },
        },
        [
          icon.for(item.icon)
            ? icon(icon.for(item.icon))
            : el("span", { class: "menu-icon" }, item.icon),
          el("div", { style: "display: flex; flex-direction: column; gap: 1px; min-width: 0;" }, [
            el("span", {}, item.label),
            item.hint
              ? el("span", { class: "muted small", style: "font-size: 10px;" }, item.hint)
              : null,
          ]),
        ],
      );
      menu.appendChild(row);
    }
  }
}

// Inbox unread badge — polls the inbox-replies endpoint and shows count.
// 0 → hidden; 1-99 → number; 100+ → "99+".
// Uses apiCached so renderInbox() and the badge tick share fetches when fresh.
async function refreshInboxBadge() {
  const badge = $("#topbar-inbox-badge");
  if (!badge) return;
  try {
    const data = await apiCached("inbox-replies");
    const count = (data?.replies || []).length;
    if (count > 0) {
      badge.textContent = count > 99 ? "99+" : String(count);
      badge.hidden = false;
    } else {
      badge.hidden = true;
    }
  } catch {
    // Silent fail — leave badge as-is.
  }
}

// Visibility-aware poller for the inbox badge.
// Skips the 60s tick when the tab is hidden (saves bandwidth + battery), and
// fires immediately when the tab becomes visible again so the badge is fresh.
function startInboxBadgePolling() {
  setInterval(() => {
    if (document.visibilityState === "visible") {
      refreshInboxBadge();
      refreshNotifBadge();
    }
  }, 60000);
  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "visible") {
      refreshInboxBadge();
      refreshNotifBadge();
    }
  });
}

// Notification-center unread badge — polls /api/notifications (unread count).
// 0 → hidden; 1-99 → number; 100+ → "99+".
async function refreshNotifBadge() {
  const badge = $("#topbar-notif-badge");
  if (!badge) return;
  try {
    const data = await api("notifications-list", { queryString: "?unread=1&limit=1&scope=all" });
    const count = Number(data?.unread || 0);
    if (count > 0) {
      badge.textContent = count > 99 ? "99+" : String(count);
      badge.hidden = false;
    } else {
      badge.hidden = true;
    }
  } catch {
    // Silent fail — leave badge as-is.
  }
}
