// dashboard-email-warmup.js — extracted verbatim from dashboard.js (pure move).

// ── Email Warmup ────────────────────────────────────────────────

// Tracks which warmup config is expanded so the user keeps the open detail
// across re-renders (Stop / Start buttons trigger renderEmailWarmup).
let _emailWarmupExpandedId = null;

async function renderEmailWarmup() {
  showLoading("Loading warmup status\u2026");
  const [warmupData, accountsData] = await Promise.all([
    api("email-warmup-list").catch(() => ({})),
    Promise.resolve(dashboardState.cache.accounts?.smtp || []),
  ]);
  if (warmupData?.error) {
    showError(warmupData.error, renderEmailWarmup);
    return;
  }
  const configs = warmupData.configs || [];

  const content = el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el("div", { class: "page-title" }, "Email Warmup"),
        el(
          "div",
          { class: "page-subtitle" },
          "Gradual daily ramp-up for new email accounts. Click a row to see ramp progress.",
        ),
      ]),
    ]),

    configs.length > 0
      ? el("div", { class: "card" }, [
          el("div", { class: "card-title" }, `Warmup Configs (${configs.length})`),
          ...configs.map((c) => buildWarmupConfigRow(c)),
        ])
      : null,

    accountsData.length > 0
      ? el("div", { class: "card" }, [
          el("div", { class: "card-title" }, "Start Warmup"),
          el(
            "div",
            { class: "muted small", style: "margin-bottom: 8px;" },
            "Start warmup on an SMTP account to gradually increase daily send limits.",
          ),
          ...accountsData
            .filter((a) => !configs.some((c) => c.smtp_identity === a.email))
            .map((a) =>
              el(
                "div",
                { style: "display: flex; align-items: center; gap: 8px; padding: 6px 0;" },
                [
                  el("span", { class: "primary-cell" }, a.email),
                  el(
                    "button",
                    {
                      class: "btn btn-tiny btn-primary",
                      type: "button",
                      onclick: async () => {
                        const r = await api("email-warmup-start", {
                          body: { smtpIdentity: a.email },
                        });
                        if (r?.error) {
                          toast(`Start failed: ${r.error}`, "err");
                          return;
                        }
                        // Clickable toast \u2014 navigate to the new config + expand it. The
                        // smtp_identity is stable so we use it as the expand target;
                        // when the page re-renders, the config row appears expanded.
                        toast(
                          `\u2705 Warmup started for ${a.email} \u2014 click to view`,
                          "ok",
                          5000,
                          () => {
                            _emailWarmupExpandedId = a.email;
                            renderEmailWarmup().then(() => {
                              // Scroll the expanded row into view + flash a highlight.
                              setTimeout(() => {
                                const row = document.querySelector(
                                  `[data-warmup-id="${cssIdEscape(a.email)}"]`,
                                );
                                if (row) {
                                  row.scrollIntoView({ behavior: "smooth", block: "center" });
                                  row.style.transition = "background 0.6s";
                                  row.style.background = "rgba(59,130,246,0.18)";
                                  setTimeout(() => {
                                    row.style.background = "";
                                  }, 1500);
                                }
                              }, 80);
                            });
                          },
                        );
                        // Auto-expand the just-started config so the user sees status immediately.
                        _emailWarmupExpandedId = a.email;
                        renderEmailWarmup();
                      },
                    },
                    "\ud83d\udd25 Start",
                  ),
                ],
              ),
            ),
        ])
      : el("div", { class: "empty-state" }, [
          el("div", { class: "empty-state-icon" }, "\u2709\ufe0f"),
          el("div", { class: "empty-state-title" }, "No SMTP accounts"),
          el(
            "div",
            { class: "empty-state-hint" },
            "Add an email account in the Accounts page first.",
          ),
        ]),
  ]);
  setContentNode(content);
}

// Build one warmup config row. Click the row (anywhere outside the Stop
// button) to toggle expansion. Expanded view shows the ramp curve, progress
// to target, days remaining estimate, and a progress bar.
function buildWarmupConfigRow(c) {
  const isExpanded = _emailWarmupExpandedId === c.smtp_identity;
  // Curve from inbox-routes.js \u2014 matches the server-side computation.
  const CURVE = [
    2, 3, 5, 5, 8, 8, 8, 12, 12, 12, 18, 18, 18, 18, 25, 25, 25, 25, 25, 25, 25, 35, 35, 35, 35, 35,
    35, 35, 35, 35, 50,
  ];
  const day = Math.max(0, Number(c.current_day) || 0);
  const targetDay = CURVE.length - 1;
  const targetLimit = CURVE[targetDay];
  const progressPct = Math.min(100, Math.round((day / targetDay) * 100));
  const daysRemaining = Math.max(0, targetDay - day);

  const headerRow = el(
    "div",
    {
      "data-warmup-id": c.smtp_identity,
      class: "channel-row",
      style: "cursor:pointer;",
      onclick: (e) => {
        // Don't toggle when clicking the Stop button
        if (e.target.closest("button")) return;
        _emailWarmupExpandedId = isExpanded ? null : c.smtp_identity;
        renderEmailWarmup();
      },
    },
    [
      el("div", { class: "channel-icon" }, c.status === "active" ? "\ud83d\udd25" : "\u23f8"),
      el("div", { style: "flex: 1;" }, [
        el("div", { class: "primary-cell" }, c.smtp_identity),
        el(
          "div",
          { class: "muted", style: "font-size: 10px;" },
          `Day ${day}/${targetDay} \u00b7 Sending up to ${c.dailyLimit}/day \u00b7 ${c.status}`,
        ),
      ]),
      el(
        "span",
        { class: "muted small", style: "margin-right: 8px;font-family:ui-monospace,monospace;" },
        isExpanded ? "\u25be" : "\u25b8",
      ),
      el(
        "button",
        {
          class: "btn btn-tiny btn-danger",
          type: "button",
          onclick: async () => {
            const r = await api("email-warmup-stop", { body: { smtpIdentity: c.smtp_identity } });
            if (r?.error) {
              toast(`Stop failed: ${r.error}`, "err");
              return;
            }
            toast("Warmup stopped", "ok");
            renderEmailWarmup();
          },
        },
        "Stop",
      ),
    ],
  );

  if (!isExpanded) return headerRow;

  // Expanded detail panel
  const startedAt = c.warmup_started_at ? fmtDate(c.warmup_started_at) : "\u2014";
  const today = new Date();
  const eta = new Date(today.getTime() + daysRemaining * 86400000);

  // Mini-curve: 14-day rolling slice of the curve, current day highlighted.
  const sliceStart = Math.max(0, day - 4);
  const sliceEnd = Math.min(CURVE.length, sliceStart + 14);
  const sliceCells = [];
  for (let i = sliceStart; i < sliceEnd; i++) {
    const isCurrent = i === day;
    const isPast = i < day;
    sliceCells.push(
      el(
        "div",
        {
          style: `flex:1;min-width:24px;text-align:center;padding:6px 4px;border-radius:4px;font-size:11px;font-family:ui-monospace,monospace;${
            isCurrent
              ? "background:#3b82f6;color:#fff;font-weight:700;"
              : isPast
                ? "background:#1f1f22;color:#71717a;"
                : "background:transparent;color:#52525b;border:1px dashed #2a2a2e;"
          }`,
          title: `Day ${i}: ${CURVE[i]} sends/day`,
        },
        [
          el("div", { style: "font-size:9px;opacity:0.6;" }, `D${i}`),
          el("div", {}, String(CURVE[i])),
        ],
      ),
    );
  }

  const detail = el(
    "div",
    {
      style:
        "padding:14px 16px 16px 50px;background:#0f0f10;border-left:3px solid #3b82f6;margin:4px 0 10px;border-radius:0 6px 6px 0;",
    },
    [
      // Top stats row
      el(
        "div",
        {
          style: "display:flex;gap:24px;flex-wrap:wrap;margin-bottom:14px;font-size:12px;",
        },
        [
          el("div", {}, [
            el(
              "div",
              {
                style:
                  "color:#71717a;font-size:10px;text-transform:uppercase;letter-spacing:0.06em;font-weight:600;margin-bottom:2px;",
              },
              "Today's limit",
            ),
            el(
              "div",
              {
                style:
                  "font-size:18px;font-weight:700;color:#e5e7eb;font-variant-numeric:tabular-nums;",
              },
              `${c.dailyLimit}/day`,
            ),
          ]),
          el("div", {}, [
            el(
              "div",
              {
                style:
                  "color:#71717a;font-size:10px;text-transform:uppercase;letter-spacing:0.06em;font-weight:600;margin-bottom:2px;",
              },
              "Target",
            ),
            el(
              "div",
              {
                style:
                  "font-size:18px;font-weight:700;color:#e5e7eb;font-variant-numeric:tabular-nums;",
              },
              `${targetLimit}/day`,
            ),
          ]),
          el("div", {}, [
            el(
              "div",
              {
                style:
                  "color:#71717a;font-size:10px;text-transform:uppercase;letter-spacing:0.06em;font-weight:600;margin-bottom:2px;",
              },
              "Days remaining",
            ),
            el(
              "div",
              {
                style:
                  "font-size:18px;font-weight:700;color:#e5e7eb;font-variant-numeric:tabular-nums;",
              },
              daysRemaining > 0 ? String(daysRemaining) : "Done",
            ),
          ]),
          el("div", {}, [
            el(
              "div",
              {
                style:
                  "color:#71717a;font-size:10px;text-transform:uppercase;letter-spacing:0.06em;font-weight:600;margin-bottom:2px;",
              },
              "Started",
            ),
            el("div", { style: "font-size:13px;color:#cbd5e1;" }, startedAt),
          ]),
          daysRemaining > 0
            ? el("div", {}, [
                el(
                  "div",
                  {
                    style:
                      "color:#71717a;font-size:10px;text-transform:uppercase;letter-spacing:0.06em;font-weight:600;margin-bottom:2px;",
                  },
                  "Est. complete",
                ),
                el(
                  "div",
                  { style: "font-size:13px;color:#cbd5e1;" },
                  eta.toISOString().slice(0, 10),
                ),
              ])
            : null,
        ],
      ),

      // Progress bar
      el(
        "div",
        {
          style:
            "margin-bottom:6px;font-size:11px;color:#9ca3af;display:flex;justify-content:space-between;",
        },
        [
          el("span", {}, `Ramp progress`),
          el(
            "span",
            { style: "font-family:ui-monospace,monospace;color:#cbd5e1;" },
            `${progressPct}%`,
          ),
        ],
      ),
      el(
        "div",
        {
          style:
            "height:6px;background:#1f1f22;border-radius:3px;overflow:hidden;margin-bottom:18px;",
        },
        [
          el("div", {
            style: `width:${progressPct}%;height:100%;background:linear-gradient(90deg,#3b82f6,#10b981);transition:width 300ms;`,
          }),
        ],
      ),

      // Mini-curve
      el(
        "div",
        {
          style:
            "font-size:10px;color:#71717a;text-transform:uppercase;letter-spacing:0.06em;font-weight:600;margin-bottom:6px;",
        },
        "Daily limit curve",
      ),
      el("div", { style: "display:flex;gap:3px;align-items:stretch;" }, sliceCells),

      // Footer hint
      el(
        "div",
        { style: "margin-top:14px;font-size:11px;color:#71717a;line-height:1.5;" },
        c.status === "active"
          ? `Warmup advances 1 day at 00:05 UTC. Today the runner will send up to ${c.dailyLimit} emails (mix of replies + outbound) to build your sender reputation.`
          : "Warmup is paused \u2014 daily counter won't advance. Click Start to resume from the current day.",
      ),
    ],
  );

  return el("div", {}, [headerRow, detail]);
}

// Tiny CSS-id-safe escaper for use in querySelector.
function cssIdEscape(s) {
  return String(s ?? "").replace(/[^a-zA-Z0-9_-]/g, "_");
}
