/* global React */

// ────────────────────────────────────────────────────────────
// DIGEST — экран «Сводка за период» (12h по умолчанию)
// Открывается через deep-link ?screen=digest или из боттом-таба.
// ────────────────────────────────────────────────────────────
window.DigestScreen = ({ T, dark, onBack, onOpenEvent, hours = 12 }) => {
  const [period, setPeriod] = React.useState(hours); // 12 | 24
  const [events, setEvents] = React.useState(null);
  const [error, setError] = React.useState(null);

  // Pull the user's preferred magnitude filter from the reactive store so the
  // Сводка screen matches what's shown in Telegram's digest message.
  const data = window.DATA.useDataState();
  const minMag = data.userMagFilter ?? 4.0;

  React.useEffect(() => {
    let cancelled = false;
    setEvents(null);
    setError(null);
    window.DATA.fetchEventsSince({ hours: period, minMag })
      .then((rows) => { if (!cancelled) setEvents(rows); })
      .catch((e) => { if (!cancelled) setError(String(e)); });
    return () => { cancelled = true; };
  }, [period, minMag]);

  const now = new Date();
  const since = new Date(now.getTime() - period * 3600 * 1000);
  const fmtMsk = (d) => new Intl.DateTimeFormat("ru-RU", {
    hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "Europe/Moscow",
  }).format(d);
  const fmtDate = new Intl.DateTimeFormat("ru-RU", {
    day: "2-digit", month: "2-digit", year: "numeric", timeZone: "Europe/Moscow",
  }).format(now);
  const periodMsk = `${fmtMsk(since)} — ${fmtMsk(now)} МСК`;

  if (error) {
    return (
      <div style={{ background: T.bg, color: T.text, minHeight: "100%" }}>
        <window.ScreenHeader title="Сводка" subtitle="ошибка загрузки" onBack={onBack} T={T} />
        <div style={{ padding: 24, textAlign: "center", color: T.danger, fontSize: 13 }}>
          {error}
        </div>
      </div>
    );
  }

  if (events === null) {
    return (
      <div style={{ background: T.bg, color: T.text, minHeight: "100%" }}>
        <window.ScreenHeader title="Сводка" subtitle={periodMsk} onBack={onBack} T={T} />
        <div style={{ padding: 32, textAlign: "center", color: T.textMuted, fontSize: 13,
          fontFamily: '"JetBrains Mono", monospace', letterSpacing: 0.5 }}>
          ЗАГРУЗКА…
        </div>
      </div>
    );
  }

  const total = events.length;
  const ru = events.filter(e => e.isRu).length;
  const world = total; // anything in BD is M≥4; "world" = total here
  const m5plus = events.filter(e => e.mag >= 5.0).length;
  const m6plus = events.filter(e => e.mag >= 6.0).length;
  const m7plus = events.filter(e => e.mag >= 7.0).length;
  const maxMag = total > 0 ? Math.max(...events.map(e => e.mag)) : 0;
  const maxEvent = events.find(e => e.mag === maxMag);

  // Top 5 by magnitude
  const top5 = [...events].sort((a, b) => b.mag - a.mag).slice(0, 5);

  // Hourly bins for the inline chart
  const bins = makeHourlyBins(events, since, now);
  const maxBin = Math.max(1, ...bins.map(b => b.count));

  return (
    <div style={{ background: T.bg, color: T.text, minHeight: "100%", paddingBottom: 32 }}>
      <window.ScreenHeader title="Сводка" subtitle={`${period} ч · ${fmtDate}`} onBack={onBack} T={T} />

      {/* Период переключатель */}
      <div style={{ padding: "10px 16px", display: "flex", gap: 6, borderBottom: `1px solid ${T.borderSoft}`,
        background: T.surface, fontFamily: '"JetBrains Mono", monospace' }}>
        {[12, 24].map(h => (
          <button key={h} onClick={() => setPeriod(h)} style={{
            padding: "6px 14px", borderRadius: 14,
            border: `1px solid ${period === h ? T.accent : T.border}`,
            background: period === h ? T.accentSoft : "transparent",
            color: period === h ? T.accent : T.text,
            fontSize: 11.5, cursor: "pointer", whiteSpace: "nowrap",
            fontFamily: 'inherit', fontWeight: period === h ? 600 : 400,
          }}>{h} ч</button>
        ))}
        <span style={{ marginLeft: "auto", fontSize: 10.5, color: T.textMuted, alignSelf: "center" }}>
          {periodMsk}
        </span>
      </div>

      {/* Сводка-карточки */}
      <div style={{ padding: "16px", display: "grid",
        gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
        <window.Stat T={T} label="ВСЕГО"     value={total}    hint={`за ${period} ч · M≥${minMag.toFixed(1)}`} />
        <window.Stat T={T} label="РОССИЯ/СНГ" value={ru}       hint="из общего числа" />
        <window.Stat T={T} label="МАКС M"     value={maxMag.toFixed(1)}
          hint={maxEvent ? truncate(maxEvent.place, 20) : "—"} highlight />
      </div>

      {/* No-events placeholder */}
      {total === 0 && (
        <div style={{ padding: "0 16px 16px" }}>
          <div style={{
            background: T.surface, border: `1px solid ${T.border}`,
            borderRadius: 10, padding: "20px 16px", textAlign: "center",
          }}>
            <div style={{ fontSize: 14, color: T.textDim, marginBottom: 4 }}>
              За {period} часов событий M≥{minMag.toFixed(1)} нет
            </div>
            <div style={{ fontSize: 11, color: T.textMuted,
              fontFamily: '"JetBrains Mono", monospace', letterSpacing: 0.4 }}>
              {period === 12
                ? "Попробуйте «24 ч» — обычно за сутки 3–10 событий."
                : "Сейсмическая активность ниже среднего."}
            </div>
            {period === 12 && (
              <button onClick={() => setPeriod(24)} style={{
                marginTop: 12, padding: "8px 18px", borderRadius: 8,
                border: `1px solid ${T.accent}`, background: T.accent,
                color: T === window.TOKENS.dark ? "#1B1A17" : "#fff",
                fontSize: 12, fontWeight: 600, cursor: "pointer",
                fontFamily: 'inherit',
              }}>Показать за 24 часа</button>
            )}
          </div>
        </div>
      )}

      {/* Распределение M */}
      {total > 0 && (
        <div style={{ padding: "0 16px" }}>
          <div style={{ background: T.surface, border: `1px solid ${T.border}`,
            borderRadius: 10, padding: "12px 14px" }}>
            <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted,
              fontFamily: '"JetBrains Mono", monospace', marginBottom: 10 }}>
              ПО МАГНИТУДЕ
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
              <Pill T={T} k="M≥5" v={m5plus} />
              <Pill T={T} k="M≥6" v={m6plus} accent />
              <Pill T={T} k="M≥7" v={m7plus} danger />
            </div>
          </div>
        </div>
      )}

      {/* График по часам */}
      <div style={{ padding: "16px" }}>
        <div style={{ 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: 10, fontSize: 10,
              fontFamily: '"JetBrains Mono", monospace', color: T.textDim }}>
              <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                <span style={{ width: 8, height: 8, background: T.accent, display: "inline-block" }} /> Россия/СНГ
              </span>
              <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                <span style={{ width: 8, height: 8, background: T.textMuted, opacity: 0.5, display: "inline-block" }} /> Мир
              </span>
            </div>
          </div>
          <HourlyBars T={T} bins={bins} maxBin={maxBin} />
        </div>
      </div>

      {/* Топ событий */}
      {top5.length > 0 && (
        <div style={{ padding: "0 16px 16px" }}>
          <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted,
            fontFamily: '"JetBrains Mono", monospace', marginBottom: 8 }}>
            ТОП ПО МАГНИТУДЕ
          </div>
          <div style={{ background: T.surface, border: `1px solid ${T.border}`,
            borderRadius: 10, overflow: "hidden" }}>
            {top5.map((e, i, arr) => (
              <DigestRow key={e.id || i} ev={e} T={T} onClick={() => onOpenEvent(e)}
                last={i === arr.length - 1} />
            ))}
          </div>
        </div>
      )}

      {/* Footer-инфо */}
      <div style={{ padding: "0 16px", textAlign: "center", color: T.textMuted,
        fontSize: 10.5, fontFamily: '"JetBrains Mono", monospace', letterSpacing: 0.4 }}>
        ИСТОЧНИКИ: USGS · EMSC · мониторинг 24/7
      </div>
    </div>
  );
};

// ────────── helpers ──────────

function makeHourlyBins(events, since, now) {
  const totalMs = now.getTime() - since.getTime();
  const totalHours = Math.max(1, Math.round(totalMs / 3600000));
  const bins = [];
  for (let i = 0; i < totalHours; i++) {
    const t0 = new Date(since.getTime() + i * 3600000);
    bins.push({ t: t0, count: 0, ru: 0 });
  }
  for (const e of events) {
    const t = new Date(e.timeUtc);
    const idx = Math.min(totalHours - 1,
      Math.max(0, Math.floor((t.getTime() - since.getTime()) / 3600000)));
    if (bins[idx]) {
      bins[idx].count++;
      if (e.isRu) bins[idx].ru++;
    }
  }
  return bins;
}

// Responsive (viewBox-scaled) bar chart with proper axes.
// Layout (in viewBox units):
//   left strip  L_PAD = 28px → Y-axis tick labels (0, mid, max)
//   bottom strip B_PAD = 18px → X-axis labels (start, mid, end times in МСК)
//   plot area   the rest of (W × H)
const HourlyBars = ({ T, bins, maxBin }) => {
  const W = 360, H = 120;
  const L_PAD = 28, R_PAD = 6, T_PAD = 6, B_PAD = 18;
  const plotW = W - L_PAD - R_PAD;
  const plotH = H - T_PAD - B_PAD;
  const barW = bins.length > 0 ? plotW / bins.length : plotW;

  // Y-axis ticks: 0, half, max — keep them as round integers when possible.
  const yMax = Math.max(1, maxBin);
  const yMid = Math.ceil(yMax / 2);
  const tickFor = (v) => T_PAD + plotH - (v / yMax) * plotH;

  // X-axis labels: first, middle, last hour in МСК.
  const fmtTickHour = (d) => {
    if (!d) return "";
    return new Intl.DateTimeFormat("ru-RU", {
      hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "Europe/Moscow",
    }).format(d);
  };
  const xLabels = bins.length > 0
    ? [bins[0].t, bins[Math.floor(bins.length / 2)].t, bins[bins.length - 1].t]
    : [];

  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none"
      style={{ marginTop: 10, display: "block", width: "100%", height: H,
        fontFamily: '"JetBrains Mono", monospace' }}>

      {/* Y gridlines + tick labels */}
      {[yMax, yMid, 0].map((v, i) => (
        <g key={i}>
          <line x1={L_PAD} y1={tickFor(v)} x2={W - R_PAD} y2={tickFor(v)}
            stroke={T.grid} strokeWidth="0.5" />
          <text x={L_PAD - 4} y={tickFor(v) + 3.5} fill={T.textMuted}
            fontSize="9" textAnchor="end">
            {v}
          </text>
        </g>
      ))}

      {/* Bars */}
      {bins.map((b, i) => {
        const x = L_PAD + i * barW;
        const totalH = (b.count / yMax) * plotH;
        const ruH    = (b.ru    / yMax) * plotH;
        const worldH = totalH - ruH;
        const baseY  = T_PAD + plotH;
        return (
          <g key={i}>
            <rect x={x + 1} y={baseY - worldH} width={Math.max(1, barW - 2)} height={worldH}
              fill={T.textMuted} opacity={0.45} />
            <rect x={x + 1} y={baseY - totalH} width={Math.max(1, barW - 2)} height={ruH}
              fill={T.accent} opacity={0.9} />
          </g>
        );
      })}

      {/* X-axis labels */}
      {xLabels[0] && (
        <text x={L_PAD} y={H - 4} fill={T.textMuted} fontSize="9" textAnchor="start">
          {fmtTickHour(xLabels[0])}
        </text>
      )}
      {xLabels[1] && (
        <text x={L_PAD + plotW / 2} y={H - 4} fill={T.textMuted} fontSize="9" textAnchor="middle">
          {fmtTickHour(xLabels[1])}
        </text>
      )}
      {xLabels[2] && (
        <text x={W - R_PAD} y={H - 4} fill={T.textMuted} fontSize="9" textAnchor="end">
          {fmtTickHour(xLabels[2])} МСК
        </text>
      )}
    </svg>
  );
};

const Pill = ({ T, k, v, accent, danger }) => {
  const color = danger ? T.danger : accent ? T.accent : T.text;
  return (
    <div style={{
      background: T.surface2, border: `1px solid ${T.borderSoft}`,
      borderRadius: 8, padding: "8px 10px",
      fontFamily: '"JetBrains Mono", monospace',
    }}>
      <div style={{ fontSize: 10, color: T.textMuted, letterSpacing: 0.6 }}>{k}</div>
      <div style={{ fontSize: 18, fontWeight: 600, color, marginTop: 2 }}>{v}</div>
    </div>
  );
};

const DigestRow = ({ ev, T, onClick, last }) => (
  <div onClick={onClick} style={{
    display: "flex", gap: 12, padding: "11px 14px",
    borderBottom: last ? "none" : `1px solid ${T.borderSoft}`,
    cursor: "pointer", alignItems: "center",
  }}>
    <window.MagBadge mag={ev.mag} T={T} size={40} />
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, fontWeight: 500, color: T.text, lineHeight: 1.25,
        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
        {ev.place}
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 3, fontSize: 10.5,
        color: T.textDim, fontFamily: '"JetBrains Mono", monospace' }}>
        <span>{ev.flag}</span>
        <span>{ev.timeMsk} МСК</span>
        <span style={{ color: T.textMuted }}>·</span>
        <span>h={ev.depth.toFixed(1)} км</span>
        {ev.confirmed && <span style={{ color: T.ok, marginLeft: "auto" }}>✓ 2 ист.</span>}
      </div>
    </div>
  </div>
);

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