/* global React, window */
// Overview dashboard + Brands list — supporting screens that round out the
// platform. Both deep-link into the more substantive Radar / Pulse / History.

const { useMemo } = React;

function Overview({ ads, tasks, alerts, iterationsByAd, brand, onNavigate, onOpenAlert, onCreateAd }) {
  const { Icon, Thumb, relTimeFromMinutes } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";

  // KPIs
  const activeAds = ads.length;
  const totalSpend = ads.reduce((s, a) => s + a.spend, 0);
  const avgRoas = ads.length ? ads.reduce((s, a) => s + a.roas, 0) / ads.length : 0;
  const runningJobs = tasks.filter(t => t.status === "running").length;
  const completedToday = tasks.filter(t => t.status === "completed").length;
  const totalIterations = Object.values(iterationsByAd).reduce((s, n) => s + n, 0);

  const topAlerts = alerts
    .slice()
    .sort((a, b) => {
      const order = { critical: 0, warn: 1, info: 2 };
      return (order[a.severity] - order[b.severity]) || (a.minutesAgo - b.minutesAgo);
    })
    .slice(0, 3);

  const topRecs = ads
    .filter(a => a.type !== "video" && (a.recType === "Iterate" || a.recType === "Refresh"))
    .slice(0, 3);

  const recentTasks = tasks
    .filter(t => t.status === "completed")
    .sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0))
    .slice(0, 3);

  return (
    <div style={{ padding: "0 24px 60px" }}>
      <div style={{ padding: "32px 0 20px", display: "flex", alignItems: "flex-start", gap: 24, flexWrap: "wrap" }}>
        <div style={{ minWidth: 0, flex: "1 1 480px" }}>
          <div className="eyebrow">{t("Analytics · Overview", "数据分析 · 总览")} · {brand?.name || "Lipsum Brand"}</div>
          <h1 className="t-display" style={{ margin: "6px 0 0" }}>
            <em>Overview.</em> {t("Your week at a glance.", "本周一图看懂。")}
          </h1>
          <div style={{ marginTop: 10, color: "var(--ink-3)", fontSize: 13, maxWidth: 720 }}>
            {t(
              "The lobby of Atria. Three things to do from here:",
              "Atria 的大厅。从这里可以做三件事:"
            )}{" "}
            <strong>{t("act on alerts", "处理告警")}</strong>、<strong>{t("review top recommendations", "查看主推建议")}</strong>{t(", or", ",或者")}{" "}
            <strong>{t("check what shipped recently", "看最近上线了什么")}</strong>。{t("Each section links to its full screen.", "每一块都能直接跳到对应的完整页面。")}
          </div>
        </div>
        {onCreateAd && (
          <button
            className="btn primary"
            onClick={onCreateAd}
            title={t(
              "Create a new ad creative — Raya can do it from one sentence",
              "新建一条广告创意 —— Raya 一句话就能做完"
            )}
            style={{ paddingTop: 10, paddingBottom: 10, fontSize: 13 }}
          >
            <Icon name="plus" size={13} />
            {t("Create ad creative", "创建广告创意")}
          </button>
        )}
      </div>

      <div className="hr" />

      {/* KPI strip */}
      <div style={{
        marginTop: 18,
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
        gap: 12,
      }}>
        <KpiCard label={t("Active ads", "在跑广告")} value={activeAds} sub={t("across all campaigns", "所有投放总和")} />
        <KpiCard label={t("Total spend (14d)", "总花费(14 天)")} value={window.fmtMoney(totalSpend)} sub={t("across active ads", "所有在跑广告合计")} />
        <KpiCard label={t("Avg ROAS", "平均 ROAS")} value={avgRoas.toFixed(2)} sub={avgRoas >= 1 ? t("profitable", "盈利") : t("deficit", "亏损")} tone={avgRoas >= 1 ? "good" : "bad"} />
        <KpiCard label={t("Iterations", "迭代任务")} value={totalIterations + runningJobs} sub={t(`${runningJobs} running · ${completedToday} done`, `${runningJobs} 个进行中 · ${completedToday} 个已完成`)} />
      </div>

      {/* Two column main area */}
      <div style={{
        marginTop: 28,
        display: "grid",
        gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)",
        gap: 18,
      }}>
        {/* Today's Pulse */}
        <div className="card" style={{ padding: 18, display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
            <div>
              <div className="label" style={{ marginBottom: 2 }}>{t("Today's Pulse", "今日告警")}</div>
              <div className="t-h2" style={{ margin: 0 }}>{t("3 alerts that need attention", "3 条需要处理的告警")}</div>
            </div>
            <button className="btn sm" onClick={() => onNavigate && onNavigate("pulse")}>
              {t("See all", "查看全部")} <Icon name="arrow" size={11} />
            </button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {topAlerts.map(a => (
              <button
                key={a.id}
                onClick={() => { onOpenAlert && onOpenAlert(a.id); }}
                style={{
                  textAlign: "left",
                  padding: "10px 12px",
                  background: "var(--bg-deep)",
                  border: "1px solid var(--rule)",
                  borderLeft: `3px solid ${a.severity === "critical" ? "var(--grade-d)" : a.severity === "warn" ? "var(--grade-b)" : "var(--status-running)"}`,
                  borderRadius: 4,
                  cursor: "pointer",
                  display: "flex", flexDirection: "column", gap: 4,
                  transition: "background .12s",
                }}
                onMouseEnter={e => { e.currentTarget.style.background = "var(--card)"; }}
                onMouseLeave={e => { e.currentTarget.style.background = "var(--bg-deep)"; }}
              >
                <div className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em", textTransform: "uppercase" }}>
                  {a.severity === "critical" ? t("CRITICAL", "严重") : a.severity === "warn" ? t("WARN", "警告") : t("INFO", "提示")} · {a.adCode} · {window.relTimeFromMinutes(a.minutesAgo)}
                </div>
                <div style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.35, fontWeight: 500 }}>
                  {isZh && a.titleZh ? a.titleZh : a.title}
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Top Recommendations */}
        <div className="card" style={{ padding: 18 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
            <div>
              <div className="label" style={{ marginBottom: 2 }}>{t("Top recommendations", "主推建议")}</div>
              <div className="t-h2" style={{ margin: 0 }}>{t("From Radar this week", "本周 Radar 的建议")}</div>
            </div>
            <button className="btn sm" onClick={() => onNavigate && onNavigate("radar")}>
              {t("Open Radar", "打开 Radar")} <Icon name="arrow" size={11} />
            </button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {topRecs.map(ad => (
              <div key={ad.id} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "8px 0",
                borderBottom: "1px solid var(--rule)",
              }}>
                <Thumb ad={ad} w={42} h={42} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{ad.code} · {t("grade", "评级")} {ad.grade}</div>
                  <div className="t-h3" style={{ fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                    {(isZh && ad.recs[0]?.titleZh) ? ad.recs[0].titleZh : (ad.recs[0]?.title || (isZh && ad.headlineZh ? ad.headlineZh : ad.headline))}
                  </div>
                </div>
                <span className="mono" style={{
                  fontSize: 10, padding: "2px 7px",
                  background: "var(--accent-tint)", color: "var(--accent)",
                  border: "1px solid var(--accent-tint-2)",
                  borderRadius: 3, letterSpacing: ".08em", fontWeight: 600,
                }}>{ad.recType === "Iterate" ? t("Iterate", "迭代") : ad.recType === "Refresh" ? t("Refresh", "换素材") : ad.recType === "Pause" ? t("Pause", "暂停") : ad.recType === "Scale" ? t("Scale", "扩量") : ad.recType}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Recent iterations */}
      <div className="card" style={{ marginTop: 18, padding: 18 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div>
            <div className="label" style={{ marginBottom: 2 }}>{t("Recent iterations", "近期迭代")}</div>
            <div className="t-h2" style={{ margin: 0 }}>{t("Shipped from Radar in the last 24h", "过去 24 小时从 Radar 推回投放的产物")}</div>
          </div>
          <button className="btn sm" onClick={() => onNavigate && onNavigate("history")}>
            {t("See all", "查看全部")} <Icon name="arrow" size={11} />
          </button>
        </div>
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))",
          gap: 10,
        }}>
          {recentTasks.map(tk => (
            <div key={tk.id} style={{
              padding: 10,
              background: "var(--bg-deep)",
              border: "1px solid var(--rule)",
              borderRadius: 4,
              fontSize: 12,
            }}>
              <div className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".06em" }}>
                {tk.adCode} · {window.relTime ? window.relTime(tk.completedAt) : t("earlier", "之前")}
              </div>
              <div className="t-h3" style={{ fontSize: 13, marginTop: 2 }}>{window.localizedRecTitle(tk)}</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--grade-a)", marginTop: 4 }}>
                {t("✓ 4 variants ready", "✓ 4 个变体已就绪")}
              </div>
            </div>
          ))}
          {recentTasks.length === 0 && (
            <div className="empty" style={{ gridColumn: "1 / -1", padding: 14 }}>
              {t("No iterations shipped in the last 24h.", "过去 24 小时没有推回投放的迭代。")}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function KpiCard({ label, value, sub, tone }) {
  const subColor =
    tone === "good" ? "var(--grade-a)"
    : tone === "bad" ? "var(--grade-d)"
    : "var(--ink-3)";
  return (
    <div className="card" style={{ padding: 16 }}>
      <div className="label">{label}</div>
      <div className="t-h1" style={{ fontSize: 30, lineHeight: 1.05, margin: "6px 0 2px" }}>{value}</div>
      <div className="mono" style={{ fontSize: 10, color: subColor }}>{sub}</div>
    </div>
  );
}

// ===== Brands list =====

function BrandsList({ brands, activeBrandId, onSwitch, onBackToRadar }) {
  const { Icon } = window;
  const t = window.useT();
  return (
    <div style={{ padding: "0 24px 60px" }}>
      <div style={{ padding: "32px 0 20px" }}>
        <div className="eyebrow">{t(`Brand profiles · ${brands.length} active`, `品牌档案 · ${brands.length} 个在管`)}</div>
        <h1 className="t-display" style={{ margin: "6px 0 0" }}>
          <em>Brands.</em> {t("Switch between active campaigns.", "在多个品牌的投放之间切换。")}
        </h1>
        <div style={{ marginTop: 10, color: "var(--ink-3)", fontSize: 13, maxWidth: 720 }}>
          {t(
            "One Atria account, multiple brands. Switching here updates the active context across Radar, Pulse, Iterations, and Image Ads. Brand data (voice, palette, product URLs, fonts) is shared between AI features.",
            "一个 Atria 账号,可以管多个品牌。在这里切换会同步更新 Radar、Pulse、迭代历史、图片广告里的当前品牌上下文。品牌数据(品牌语气、配色、产品链接、字体)会在所有 AI 功能之间共享。"
          )}
        </div>
      </div>

      <div className="hr" />

      <div style={{
        marginTop: 18,
        display: "grid",
        gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
        gap: 14,
      }}>
        {brands.map(b => (
          <BrandCard
            key={b.id}
            brand={b}
            isActive={b.id === activeBrandId}
            onSwitch={() => onSwitch && onSwitch(b)}
          />
        ))}
        {/* Removed the disabled "+ Add brand (coming soon)" tile —
            looked clickable but did nothing. */}
      </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 BrandCard({ brand, isActive, onSwitch }) {
  const { Icon } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  return (
    <div style={{
      padding: 16,
      background: "var(--card)",
      border: isActive ? "2px solid var(--accent)" : "1px solid var(--rule)",
      borderRadius: 6,
      display: "flex",
      flexDirection: "column",
      gap: 12,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          width: 38, height: 38, borderRadius: 6,
          background: brand.primary, color: "#fff",
          display: "grid", placeItems: "center",
          fontFamily: "Source Serif 4, Georgia, serif",
          fontWeight: 600, fontSize: 18, fontStyle: "italic",
        }}>{brand.logo}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="t-h3" style={{ fontSize: 15, lineHeight: 1.2 }}>{brand.name}</div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            {isZh && brand.sublineZh ? brand.sublineZh : brand.subline}
          </div>
        </div>
        {isActive && (
          <span className="mono" style={{
            fontSize: 9, padding: "2px 6px",
            background: "var(--accent)", color: "var(--accent-ink)",
            borderRadius: 2, letterSpacing: ".08em", fontWeight: 600,
          }}>{t("ACTIVE", "当前")}</span>
        )}
      </div>

      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(3, 1fr)",
        gap: 8,
        padding: "10px 0",
        borderTop: "1px solid var(--rule)",
      }}>
        <BrandStat label={t("Active ads", "在跑广告")} value={brand.activeAds} />
        <BrandStat label={t("Iterations", "迭代")} value={brand.iterations} />
        <BrandStat label={t("Spend (14d)", "花费(14 天)")} value={brand.spend} />
      </div>

      {!isActive ? (
        <button className="btn" style={{ width: "100%" }} onClick={onSwitch}>
          {t("Switch to this brand", "切换到这个品牌")} <Icon name="arrow" size={11} />
        </button>
      ) : (
        <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", textAlign: "center", padding: "6px 0" }}>
          {t("Current active context", "当前活动品牌")}
        </div>
      )}
    </div>
  );
}

function BrandStat({ label, value }) {
  return (
    <div>
      <div className="label" style={{ fontSize: 9 }}>{label}</div>
      <div className="mono" style={{ fontSize: 13, fontWeight: 600, marginTop: 2, color: "var(--ink)" }}>{value}</div>
    </div>
  );
}

Object.assign(window, { Overview, BrandsList });
