/* global React */

// ────────────────────────────────────────────────────────────
// STATS — статистика (графики за 14 дней)
// ────────────────────────────────────────────────────────────
window.StatsScreen = ({ T, dark, onBack }) => {
  const data = window.DATA.useDataState();
  const A = data.activity;
  const M = data.magDist;

  if (!A.length) {
    return (
      <div style={{ background: T.bg, color: T.text, minHeight: "100%" }}>
        <window.ScreenHeader title="Статистика" subtitle="загрузка…" onBack={onBack} T={T} />
        <div style={{ padding: 32, textAlign: "center", color: T.textMuted, fontSize: 13 }}>
          Данные ещё не загружены.
        </div>
      </div>
    );
  }

  const maxA = Math.max(1, ...A.map(d => d.world));
  const maxM = Math.max(1, ...M.map(d => d.count));
  const totalRu = A.reduce((s, d) => s + d.ru, 0);
  const totalWorld = A.reduce((s, d) => s + d.world, 0);
  const avgRu = (totalRu / A.length).toFixed(1);
  // Max magnitude over the past 30 days from the loaded events feed
  const events = data.events;
  const recent30 = events.filter(e => e.minutesAgo < 30 * 24 * 60);
  const maxMag = recent30.length > 0 ? Math.max(...recent30.map(e => e.mag)) : 0;
  const maxMagEvent = recent30.find(e => e.mag === maxMag);

  // SVG uses a viewBox so it scales fluidly to whatever width the card has.
  // The W/H here are virtual coordinates, not pixels.
  const W = 344, H = 140, PAD = 8;
  const stepX = A.length > 1 ? (W - PAD*2) / (A.length - 1) : (W - PAD*2);

  const pathRu = A.map((d, i) => `${i === 0 ? "M" : "L"} ${PAD + i*stepX} ${H - PAD - (d.ru / maxA) * (H - PAD*2)}`).join(" ");
  const pathW = A.map((d, i) => `${i === 0 ? "M" : "L"} ${PAD + i*stepX} ${H - PAD - (d.world / maxA) * (H - PAD*2)}`).join(" ");

  return (
    <div style={{ background: T.bg, color: T.text, paddingBottom: 32, minHeight: "100%" }}>
      <window.ScreenHeader title="Статистика" subtitle={`${A.length} дней · M ≥ 4.0`} onBack={onBack} T={T} />

      <div style={{ padding: 16 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
          <window.Stat T={T} label="ВСЕГО" value={totalWorld} hint={`за ${A.length} дн`} />
          <window.Stat T={T} label="РОССИЯ" value={totalRu} hint={`в среднем ${avgRu}/д`} />
          <window.Stat T={T} label="МАКС M" value={maxMag.toFixed(1)}
            hint={maxMagEvent ? truncate(maxMagEvent.place, 18) : "—"} highlight />
        </div>

        {/* График активности */}
        <div style={{ marginTop: 20, background: T.surface, border: `1px solid ${T.border}`,
          borderRadius: 10, padding: 14 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <div style={{ fontSize: 12, fontWeight: 600 }}>Активность по дням</div>
            <div style={{ display: "flex", gap: 12, fontSize: 10,
              fontFamily: '"JetBrains Mono", monospace', color: T.textDim }}>
              <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                <span style={{ width: 8, height: 2, background: T.text, display: "inline-block" }} /> РОССИЯ
              </span>
              <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                <span style={{ width: 8, height: 2, background: T.textMuted, display: "inline-block" }} /> МИР
              </span>
            </div>
          </div>
          <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none"
            style={{ marginTop: 12, display: "block", width: "100%", height: H }}>
            {[0, 0.25, 0.5, 0.75, 1].map((f, i) => (
              <line key={i} x1={PAD} y1={PAD + f*(H-PAD*2)} x2={W-PAD} y2={PAD + f*(H-PAD*2)}
                stroke={T.grid} strokeWidth="0.5" />
            ))}
            <path d={pathW + ` L ${W-PAD} ${H-PAD} L ${PAD} ${H-PAD} Z`} fill={T.textMuted} fillOpacity="0.08" />
            <path d={pathW} fill="none" stroke={T.textMuted} strokeWidth="1.2" strokeDasharray="2 2" />
            <path d={pathRu + ` L ${W-PAD} ${H-PAD} L ${PAD} ${H-PAD} Z`} fill={T.accent} fillOpacity="0.12" />
            <path d={pathRu} fill="none" stroke={T.accent} strokeWidth="1.6" />
            {A.map((d, i) => (
              <circle key={i} cx={PAD + i*stepX} cy={H - PAD - (d.ru / maxA) * (H - PAD*2)}
                r="2" fill={T.accent} />
            ))}
          </svg>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6,
            fontSize: 9.5, color: T.textMuted, fontFamily: '"JetBrains Mono", monospace' }}>
            <span>{A[0].d}</span>
            <span>{A[Math.floor(A.length/2)].d}</span>
            <span>{A[A.length-1].d}</span>
          </div>
        </div>

        {/* Распределение по магнитудам */}
        {M.length > 0 && (
          <div style={{ marginTop: 16, background: T.surface, border: `1px solid ${T.border}`,
            borderRadius: 10, padding: 14 }}>
            <div style={{ fontSize: 12, fontWeight: 600 }}>Распределение по магнитудам · 30 дней</div>
            {/* Rows capped to a max width so the bar doesn't stretch on wide
                (desktop) viewports; the count lives in a fixed-width column so
                it stays visible at ANY width. The bar column uses minmax(0,1fr)
                so it can shrink instead of overflowing and pushing the count
                off-screen (the failure mode in Telegram Desktop's webview). */}
            <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8, maxWidth: 460 }}>
              {M.map((d) => {
                const pct = (d.count / maxM) * 100;
                const isStrong = parseFloat(d.range) >= 5.0;
                return (
                  <div key={d.range} style={{ display: "grid",
                    gridTemplateColumns: "max-content minmax(0, 1fr) 48px",
                    gap: 10, alignItems: "center", fontFamily: '"JetBrains Mono", monospace' }}>
                    <div style={{ fontSize: 11, color: T.textDim, whiteSpace: "nowrap" }}>
                      M {d.range || "—"}
                    </div>
                    <div style={{ height: 20, background: T.surface2, borderRadius: 3, position: "relative", overflow: "hidden" }}>
                      <div style={{
                        width: `${pct}%`, height: "100%",
                        background: isStrong ? T.accent : T.text, opacity: isStrong ? 1 : 0.7,
                        borderRadius: 3,
                      }} />
                    </div>
                    <div style={{ fontSize: 12, fontWeight: 600, textAlign: "right", whiteSpace: "nowrap" }}>{d.count}</div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

function truncate(s, n) {
  if (!s) return "";
  return s.length <= n ? s : s.slice(0, n - 1) + "…";
}
