// dashboard-library-zone-helpers.js — extracted verbatim from dashboard.js (pure move).

// ── Library zone helpers ─────────────────────────────────────────────
// The Automations library renders three fixed zones: Per-account actions,
// Campaigns & workflows, and Background services.

// Flattens dashboardState.cache.accounts into an ordered list for the
// per-account zone. The picker's `smtp` key is mapped to `email` so it
// lines up with PLATFORM_ACTIONS platform values.
function getConnectedAccountsForLibrary() {
  const accts = (dashboardState.cache && dashboardState.cache.accounts) || {};
  const order = [
    { key: "twitter", platform: "twitter" },
    { key: "linkedin", platform: "linkedin" },
    { key: "telegram", platform: "telegram" },
    { key: "smtp", platform: "email" },
  ];
  const out = [];
  for (const { key, platform } of order) {
    for (const a of accts[key] || []) {
      out.push({
        platform,
        accountId: a.id,
        label: a.account_identifier
          ? `@${a.account_identifier}`
          : a.label || a.identifier || a.email || a.phone || `Account ${a.id}`,
        status: a.status || "unknown",
        healthScore: a.health_score,
      });
    }
  }
  return out;
}

// Shared collapsible wrapper for a top-level library zone. Mirrors the
// header/toggle pattern of buildBackgroundServicesSection.
function buildLibraryZone({ icon, label, count, blurb, storageKey, defaultExpanded }, bodyNode) {
  let expanded = defaultExpanded !== false;
  try {
    const saved = localStorage.getItem(storageKey);
    if (saved === "1") expanded = true;
    else if (saved === "0") expanded = false;
  } catch {}

  const arrow = el("span", { style: "font-size:13px;color:var(--text-2);" }, expanded ? "▾" : "▸");
  const body = el(
    "div",
    {
      style: "display:" + (expanded ? "block" : "none") + ";padding-top:8px;",
    },
    [bodyNode],
  );

  const header = el(
    "button",
    {
      type: "button",
      style: [
        "background:transparent",
        "border:none",
        "cursor:pointer",
        "padding:10px 0 12px",
        "width:100%",
        "display:flex",
        "align-items:baseline",
        "gap:10px",
        "color:inherit",
        "text-align:left",
        "border-bottom:1px solid var(--border)",
      ].join(";"),
      onclick: () => {
        expanded = !expanded;
        try {
          localStorage.setItem(storageKey, expanded ? "1" : "0");
        } catch {}
        body.style.display = expanded ? "block" : "none";
        arrow.textContent = expanded ? "▾" : "▸";
      },
    },
    [
      arrow,
      el("span", { style: "font-size:18px;line-height:1;" }, icon),
      el(
        "div",
        { style: "font-size:15px;font-weight:600;color:var(--text-1);letter-spacing:0.01em;" },
        label,
      ),
      count != null
        ? el(
            "div",
            { style: "font-size:11px;font-family:ui-monospace,monospace;color:var(--text-4);" },
            `${count}`,
          )
        : null,
      blurb
        ? el("div", { style: "font-size:12px;color:var(--text-2);font-weight:400;" }, blurb)
        : null,
    ],
  );

  return el("div", { class: "library-zone" }, [header, body]);
}

// Zone 1 — per-account actions, grouped by individual connected account.
// Each account is a collapsible sub-group; the topbar picker expands the
// matching one. Replaces the old buildPerAccountPrompt callout.
function buildPerAccountActionsZone(connectedAccounts, ctx) {
  const platformMeta = {
    linkedin: { icon: "briefcase", label: "LinkedIn", color: "#0a66c2" },
    twitter: { icon: "𝕏", label: "Twitter / X", color: "#1da1f2" },
    telegram: { icon: "✈️", label: "Telegram", color: "#0088cc" },
    email: { icon: "mail", label: "Email", color: "#ea4335" },
  };
  const ctxPlatform = ctx ? (ctx.platform === "smtp" ? "email" : ctx.platform) : null;

  const inner = el("div", { style: "display:flex;flex-direction:column;gap:8px;" });

  if (!connectedAccounts.length) {
    inner.appendChild(
      el(
        "div",
        {
          style:
            "padding:14px 16px;background:rgba(255,255,255,0.02);border:1px solid var(--border);border-radius:8px;color:var(--text-2);font-size:13px;display:flex;align-items:center;gap:12px;",
        },
        [
          el(
            "span",
            { style: "flex:1;" },
            "No accounts connected yet — connect one to see its in-browser actions.",
          ),
          el(
            "button",
            {
              type: "button",
              class: "btn btn-tiny btn-primary",
              onclick: () => {
                try {
                  navigate("accounts");
                } catch {}
              },
            },
            "Connect an account",
          ),
        ],
      ),
    );
  }

  for (const acct of connectedAccounts) {
    const meta = platformMeta[acct.platform] || {
      icon: "·",
      label: acct.platform,
      color: "#94a3b8",
    };
    const myActions = (window.PLATFORM_ACTIONS || []).filter((a) => a.platform === acct.platform);
    const isCtx =
      !!ctxPlatform &&
      ctxPlatform === acct.platform &&
      ctx &&
      String(ctx.id) === String(acct.accountId);

    const storageKey = `automations:acctActions:${acct.platform}:${acct.accountId}`;
    let expanded = false;
    try {
      expanded = localStorage.getItem(storageKey) === "1";
    } catch {}
    // Topbar picker jump: when a context account is set, force the matching
    // sub-group open and all others closed.
    if (ctx) expanded = isCtx;

    const dotClass =
      acct.status === "active" ? "online" : acct.status === "rate_limited" ? "warning" : "offline";

    const arrow = el(
      "span",
      { style: "font-size:12px;color:var(--text-2);" },
      expanded ? "▾" : "▸",
    );

    let bodyContent;
    if (myActions.length > 0) {
      bodyContent = buildPlatformActionsSection(myActions, { hideHeader: true });
    } else if (acct.platform === "email") {
      bodyContent = el(
        "div",
        {
          style:
            "padding:14px 16px;background:rgba(234,179,8,0.04);border:1px solid rgba(234,179,8,0.18);border-radius:8px;color:var(--text-1);font-size:13px;",
        },
        "Email accounts don't have in-browser actions — see Email campaigns and sequences under Campaigns & workflows.",
      );
    } else {
      bodyContent = el(
        "div",
        {
          style:
            "padding:14px 16px;background:rgba(255,255,255,0.02);border:1px solid var(--border);border-radius:8px;color:var(--text-2);font-size:13px;",
        },
        `No actions registered for ${meta.label} yet.`,
      );
    }
    const body = el(
      "div",
      {
        style: "display:" + (expanded ? "block" : "none") + ";padding:10px 0 12px 14px;",
      },
      [bodyContent],
    );

    const header = el(
      "button",
      {
        type: "button",
        style: [
          "background:rgba(255,255,255,0.02)",
          "border:1px solid var(--border)",
          "border-left:3px solid " + meta.color,
          "border-radius:8px",
          "cursor:pointer",
          "padding:10px 14px",
          "width:100%",
          "display:flex",
          "align-items:center",
          "gap:10px",
          "color:inherit",
          "text-align:left",
        ].join(";"),
        onclick: () => {
          const open = body.style.display === "none";
          body.style.display = open ? "block" : "none";
          arrow.textContent = open ? "▾" : "▸";
          try {
            localStorage.setItem(storageKey, open ? "1" : "0");
          } catch {}
        },
      },
      [
        arrow,
        el("span", { class: "topbar-account-dot " + dotClass }),
        icon.for(meta.icon)
          ? icon(icon.for(meta.icon))
          : el("span", { style: "font-size:15px;" }, meta.icon),
        el("div", { style: "font-size:13px;font-weight:600;color:var(--text-1);" }, acct.label),
        el("div", { style: "font-size:11px;color:var(--text-4);" }, meta.label),
        el("span", { style: "flex:1;" }),
        el(
          "div",
          { style: "font-size:11px;font-family:ui-monospace,monospace;color:var(--text-4);" },
          myActions.length ? `${myActions.length} action${myActions.length === 1 ? "" : "s"}` : "—",
        ),
      ],
    );

    inner.appendChild(el("div", { class: "account-subgroup" }, [header, body]));
  }

  return buildLibraryZone(
    {
      icon: "user",
      label: "Per-account actions",
      count: connectedAccounts.length || null,
      blurb: "In-browser actions you trigger on one specific account.",
      storageKey: "automations:zone:perAccount",
      defaultExpanded: true,
    },
    inner,
  );
}

// Zone 2 — campaigns & workflows: compositions, legacy customs, and
// cross-account campaign presets. Reuses the existing section builders.
function buildCampaignsZone({ compositions, customs, crossAccountPresets, presets }) {
  const inner = el("div", { style: "display:flex;flex-direction:column;gap:32px;" });

  if (compositions.length > 0) {
    inner.appendChild(buildCompositionsSection(compositions));
  }
  if (customs.length > 0) {
    inner.appendChild(
      buildAutomationSection(
        {
          key: "custom",
          label: "My legacy workflows",
          icon: "edit",
          blurb:
            "Older customized clones from the preset catalog. New work happens on the Build page.",
        },
        customs,
      ),
    );
  }
  if (crossAccountPresets.length > 0) {
    inner.appendChild(
      buildAutomationSection(
        {
          key: "cross_account",
          label: "Cross-account campaigns",
          icon: "bolt",
          blurb:
            "Outreach, amplification, and multi-step orchestrations that target lists of contacts",
        },
        crossAccountPresets,
      ),
    );
  }
  // Operation templates (orphaned wizards — accountMode=multi mostly).
  if (typeof OPERATIONS !== "undefined" && Array.isArray(OPERATIONS)) {
    const presetIdsSet = new Set(presets.map((w) => w.id));
    const orphanedOps = OPERATIONS.filter(
      (op) => op.templateKey && !presetIdsSet.has(op.templateKey),
    );
    if (orphanedOps.length > 0) {
      inner.appendChild(buildOperationTemplatesSection(orphanedOps));
    }
  }

  if (!inner.childNodes.length) {
    inner.appendChild(
      el(
        "div",
        {
          style:
            "padding:14px 16px;background:rgba(255,255,255,0.02);border:1px solid var(--border);border-radius:8px;color:var(--text-2);font-size:13px;",
        },
        "No campaigns or workflows yet — clone one from a preset, or build one on the Build page.",
      ),
    );
  }

  return buildLibraryZone(
    {
      icon: "bolt",
      label: "Campaigns & workflows",
      count: compositions.length + customs.length + crossAccountPresets.length,
      blurb: "Multi-step runs you orchestrate across contacts and accounts.",
      storageKey: "automations:zone:campaigns",
      defaultExpanded: true,
    },
    inner,
  );
}

// Collapsible "Background services" section — passive cron jobs.
// Default collapsed within the library to reduce visual noise; user
// can expand when they want to see signal scrapers, enrichment, etc.
function buildBackgroundServicesSection(items) {
  const KEY = "automations:bgServicesExpanded";
  let expanded = false;
  try {
    expanded = localStorage.getItem(KEY) === "1";
  } catch {}

  const wrap = el("div", {});
  const headerBtn = el(
    "button",
    {
      type: "button",
      style: [
        "background:transparent",
        "border:none",
        "cursor:pointer",
        "padding:8px 0 14px",
        "width:100%",
        "display:flex",
        "align-items:baseline",
        "gap:10px",
        "color:inherit",
        "text-align:left",
      ].join(";"),
      onclick: () => {
        expanded = !expanded;
        try {
          localStorage.setItem(KEY, expanded ? "1" : "0");
        } catch {}
        content.style.display = expanded ? "grid" : "none";
        arrow.textContent = expanded ? "▾" : "▸";
      },
    },
    [
      el(
        "span",
        { class: "bg-services-arrow", style: "font-size:13px;color:var(--text-2);" },
        expanded ? "▾" : "▸",
      ),
      el("span", { style: "font-size:18px;line-height:1;" }, icon("bot")),
      el(
        "div",
        { style: "font-size:15px;font-weight:600;color:var(--text-1);letter-spacing:0.01em;" },
        "Background services",
      ),
      el(
        "div",
        { style: "font-size:11px;font-family:ui-monospace,monospace;color:var(--text-4);" },
        `${items.length}`,
      ),
      el(
        "div",
        { style: "font-size:12px;color:var(--text-2);font-weight:400;" },
        expanded ? "" : "(clone catalog — see Always-on services above for live status)",
      ),
    ],
  );
  // Find the arrow span so toggle can update its glyph.
  const arrow = headerBtn.querySelector(".bg-services-arrow");
  wrap.appendChild(headerBtn);

  const content = el("div", {
    style: [
      "display:" + (expanded ? "grid" : "none"),
      "grid-template-columns:repeat(auto-fill,minmax(340px,1fr))",
      "gap:14px",
    ].join(";"),
  });
  // Reuse the existing card builder. Pass a minimal "group" for color.
  const fakeGroup = { key: "background", icon: "bot", label: "Background", blurb: "" };
  for (const wf of items) content.appendChild(buildAutomationCard(wf, fakeGroup));
  wrap.appendChild(content);

  return wrap;
}
