/* global React, window */
// Pulse — live alert stream tied to Radar.
// Bi-directional: each alert deep-links back into Radar; Radar rows with
// active alerts get a ⚡ indicator that jumps back here scrolled to the alert.

const { useState, useMemo } = React;

function Pulse({ alerts, ads, focusedAlertId, onOpenAd, onBackToRadar }) {
  const { Thumb, Icon, relTimeFromMinutes } = window;
  const t = window.useT();
  const [filter, setFilter] = useState("all"); // all | critical | warn | info

  const filtered = useMemo(() => {
    if (filter === "all") return alerts;
    return alerts.filter(a => a.severity === filter);
  }, [alerts, filter]);

  const counts = {
    all: alerts.length,
    critical: alerts.filter(a => a.severity === "critical").length,
    warn: alerts.filter(a => a.severity === "warn").length,
    info: alerts.filter(a => a.severity === "info").length,
  };

  return (
    <div style={{ padding: "0 24px 60px" }}>
      <div style={{ padding: "32px 0 20px", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 32, flexWrap: "wrap" }}>
        <div style={{ minWidth: 0, flex: "1 1 320px" }}>
          <div className="eyebrow">{t("Analytics · Pulse · Live", "数据分析 · Pulse · 实时")}</div>
          <h1 className="t-display" style={{ margin: "6px 0 0" }}>
            <em>Pulse.</em> {t("Live signal across your active creatives.", "你所有在跑创意的实时信号。")}
          </h1>
          <div style={{ marginTop: 10, color: "var(--ink-3)", fontSize: 13, maxWidth: 720 }}>
            {t(
              "Radar is the weekly review; Pulse is the alarm clock. Anomalies below this hour, ranked by severity. Every alert deep-links to the source ad in Radar — and Radar rows with active alerts carry a",
              "Radar 是每周复盘;Pulse 是实时闹钟。下面是过去一小时内的异常情况,按严重程度排序。每条告警都能直接跳回 Radar 里那条源广告 —— 反过来,Radar 表格里带告警的行也会显示一个"
            )}{" "}
            <span className="mono" style={{ background: "var(--bg-deep)", padding: "1px 5px", borderRadius: 2 }}>⚡</span>{" "}
            {t("indicator that jumps back here.", "标记,点击就跳回这里。")}
          </div>
        </div>
        <div style={{ display: "flex", gap: 22, alignItems: "flex-end", flexShrink: 0, flexWrap: "wrap" }}>
          <PulseStat label={t("Active", "在跑")} value={counts.all} tone="default" />
          <PulseStat label={t("Critical", "严重")} value={counts.critical} tone="critical" />
          <PulseStat label={t("Warn", "警告")} value={counts.warn} tone="warn" />
          <PulseStat label={t("Info", "提示")} value={counts.info} tone="info" />
        </div>
      </div>

      <div className="hr" />

      {/* Severity filter */}
      <div style={{ display: "flex", padding: "8px 0", gap: 6, flexWrap: "wrap" }}>
        {[
          { id: "all", label: t("All", "全部") },
          { id: "critical", label: t("Critical", "严重") },
          { id: "warn", label: t("Warn", "警告") },
          { id: "info", label: t("Info", "提示") },
        ].map(f => (
          <button
            key={f.id}
            onClick={() => setFilter(f.id)}
            className={"tab " + (filter === f.id ? "active" : "")}
            style={{ padding: "8px 14px" }}
          >
            <span>{f.label}</span>
            <span className="tab-count">{counts[f.id]}</span>
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)", alignSelf: "center" }}>
          <span className="spinner" style={{ width: 8, height: 8, marginRight: 6, verticalAlign: "middle" }} />
          {t("Polling every 60s · last refresh just now", "每 60 秒轮询一次 · 刚刚刷新")}
        </span>
      </div>

      <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 10 }}>
        {filtered.length === 0 ? (
          <div className="empty">
            <div className="t-h3" style={{ marginBottom: 4 }}>{t(`No ${filter !== "all" ? filter : ""} alerts.`, "暂无告警。")}</div>
            <div>{t("Pulse is quiet — your campaigns are running within tolerance.", "Pulse 很安静 —— 你的投放都在容忍范围内。")}</div>
          </div>
        ) : (
          filtered.map(alert => {
            const ad = ads.find(a => a.id === alert.adId);
            return (
              <AlertCard
                key={alert.id}
                alert={alert}
                ad={ad}
                focused={focusedAlertId === alert.id}
                onOpenInRadar={() => onOpenAd && onOpenAd(alert.adId)}
              />
            );
          })
        )}
      </div>

      <div style={{ marginTop: 28, textAlign: "center", color: "var(--ink-3)", fontSize: 11 }}>
        <button className="btn ghost sm" onClick={onBackToRadar}>← {t("Back to Radar", "返回 Radar")}</button>
      </div>
    </div>
  );
}

function PulseStat({ label, value, tone }) {
  const color =
    tone === "critical" ? "var(--grade-d)"
    : tone === "warn" ? "var(--grade-b)"
    : tone === "info" ? "var(--status-running)"
    : "var(--ink)";
  return (
    <div style={{ minWidth: 70, textAlign: "right" }}>
      <div className="label">{label}</div>
      <div className="t-h1" style={{ fontSize: 28, lineHeight: 1, marginTop: 2, color }}>{value}</div>
    </div>
  );
}

function AlertCard({ alert, ad, focused, onOpenInRadar }) {
  const { Thumb, Icon, relTimeFromMinutes } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const sevColor =
    alert.severity === "critical" ? "var(--grade-d)"
    : alert.severity === "warn" ? "var(--grade-b)"
    : "var(--status-running)";
  const sevBg =
    alert.severity === "critical" ? "#3d1515"
    : alert.severity === "warn" ? "#2d1a00"
    : "#0d2137";
  const sevLabel =
    alert.severity === "critical" ? t("CRITICAL", "严重")
    : alert.severity === "warn" ? t("WARN", "警告")
    : t("INFO", "提示");
  const sevGlyph =
    alert.severity === "critical" ? "⚠"
    : alert.severity === "warn" ? "▴"
    : "•";

  return (
    <div
      data-alert-id={alert.id}
      className="card"
      style={{
        padding: 14,
        display: "flex",
        gap: 14,
        alignItems: "stretch",
        borderLeft: `4px solid ${sevColor}`,
        boxShadow: focused ? "0 0 0 2px var(--accent), 0 0 16px rgba(209, 74, 31, 0.15)" : undefined,
        transition: "box-shadow .2s",
      }}
    >
      <div style={{ flexShrink: 0 }}>
        {ad ? <Thumb ad={ad} w={56} h={56} /> : (
          <div style={{ width: 56, height: 56, background: "var(--bg-deep)", borderRadius: 4 }} />
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4, flexWrap: "wrap" }}>
          <span className="mono" style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            fontSize: 10, fontWeight: 600, letterSpacing: ".08em", textTransform: "uppercase",
            padding: "2px 7px",
            background: sevColor, color: "var(--bg)",
            borderRadius: 3,
          }}>
            <span>{sevGlyph}</span> {sevLabel}
          </span>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{ad?.code || alert.adCode}</span>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>· {relTimeFromMinutes(alert.minutesAgo)}</span>
        </div>
        <div className="t-h3" style={{ fontSize: 15, lineHeight: 1.3, marginBottom: 4 }}>
          {isZh && alert.titleZh ? alert.titleZh : alert.title}
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.55, marginBottom: 8 }}>
          {isZh && alert.bodyZh ? alert.bodyZh : alert.body}
        </div>
        {/* Metric delta visualization */}
        {typeof alert.from === "number" && (
          <div style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            fontSize: 11,
            fontFamily: "IBM Plex Mono, monospace",
            padding: "3px 8px",
            background: "var(--bg-deep)",
            border: "1px solid var(--rule)",
            borderRadius: 3,
            color: "var(--ink-2)",
          }}>
            <span>{alert.metric}</span>
            <span style={{ color: "var(--ink-3)" }}>{alert.from}{alert.metric === "Spend" ? "$" : ""}</span>
            <span style={{ color: "var(--ink-3)" }}>→</span>
            <span style={{ color: sevColor, fontWeight: 600 }}>{alert.to}{alert.metric === "Spend" ? "$" : ""}</span>
            <span style={{ color: sevColor, fontWeight: 600 }}>
              {alert.delta > 0 ? "+" : ""}{alert.delta}%
            </span>
          </div>
        )}
      </div>
      <div style={{
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        alignItems: "flex-end", gap: 8, flexShrink: 0, minWidth: 130,
      }}>
        <button
          className={"btn sm " + (alert.severity === "critical" ? "primary" : "")}
          onClick={onOpenInRadar}
        >
          {isZh && alert.actionLabelZh ? alert.actionLabelZh : alert.actionLabel} <Icon name="arrow" size={10} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { Pulse });
