/* global React */

// ────────────────────────────────────────────────────────────
// AFTERSHOCKS — таймлайн повторных толчков для основного события.
// Радиус 50км, окно 72ч после основного.
// Используется как inline-секция в EventDetailScreen для M ≥ 5.0.
// ────────────────────────────────────────────────────────────

window.AftershockSection = ({ T, dark, mainEvent }) => {
  const [aftershocks, setAftershocks] = React.useState(null); // null = loading, [] = none
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (!mainEvent) return;
    let cancelled = false;
    window.DATA.fetchAftershocks(mainEvent, { radiusKm: 50, windowHours: 72 })
      .then((rows) => { if (!cancelled) setAftershocks(rows); })
      .catch((e) => { if (!cancelled) setError(String(e)); });
    return () => { cancelled = true; };
  }, [mainEvent && mainEvent.id]);

  if (error) return null; // silent fail — don't break detail screen
  if (aftershocks === null) {
    return (
      <div style={{ marginTop: 16, padding: "12px 14px", background: T.surface,
        border: `1px solid ${T.border}`, borderRadius: 8,
        fontSize: 11, color: T.textMuted, fontFamily: '"JetBrains Mono", monospace' }}>
        ПОИСК АФТЕРШОКОВ…
      </div>
    );
  }
  // Don't bother rendering for fewer than 2 aftershocks.
  if (aftershocks.length < 2) return null;

  return (
    <AftershockBlock T={T} dark={dark} mainEvent={mainEvent} aftershocks={aftershocks} />
  );
};

const AftershockBlock = ({ T, dark, mainEvent, aftershocks }) => {
  const main = mainEvent;
  const total = aftershocks.length;
  const maxAft = total > 0 ? Math.max(...aftershocks.map((a) => a.mag)) : 0;
  const mainTime = new Date(main.timeUtc).getTime();
  const lastEnd = total > 0
    ? new Date(aftershocks[aftershocks.length - 1].timeUtc).getTime()
    : mainTime;
  const totalMin = Math.max(60, Math.ceil((lastEnd - mainTime) / 60000));

  // Bar bottom strip = baseline; height = magnitude scaled
  const heightFor = (mag) => 14 + Math.max(0, mag - 3) * 22;
  const events = [{ ...main, _isMain: true, min: 0 }, ...aftershocks.map((a) => ({
    ...a, _isMain: false, min: Math.floor((new Date(a.timeUtc).getTime() - mainTime) / 60000),
  }))];

  return (
    <div style={{ marginTop: 20 }}>
      <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted,
        fontFamily: '"JetBrains Mono", monospace', marginBottom: 8, paddingLeft: 4 }}>
        АФТЕРШОКИ · {total} ШТ. · РАДИУС 50 КМ · 72 Ч
      </div>

      <div style={{ background: T.surface, border: `1px solid ${T.border}`,
        borderRadius: 10, overflow: "hidden" }}>

        {/* Stat row */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
          borderBottom: `1px solid ${T.borderSoft}` }}>
          <Stat T={T} k="МАКС. АФТ." v={`M ${maxAft.toFixed(1)}`}
            color={maxAft >= 5 ? T.warning : T.text} />
          <Stat T={T} k="ВСЕГО" v={String(total)} color={T.text} />
          <Stat T={T} k="ПЕРИОД" v={fmtTime(totalMin)} color={T.accent} last />
        </div>

        {/* Timeline visualization */}
        <div style={{ padding: "16px 14px 12px" }}>
          <div style={{ fontSize: 9.5, letterSpacing: 1.4, color: T.textMuted,
            fontFamily: '"JetBrains Mono", monospace', marginBottom: 14 }}>
            ВРЕМЕННАЯ ШКАЛА · ЗАТУХАНИЕ ПО ОМОРИ
          </div>
          <div style={{ position: "relative", height: 110, marginBottom: 8 }}>
            {/* Baseline */}
            <div style={{ position: "absolute", left: 0, right: 0, bottom: 22,
              height: 1, background: T.border }} />
            {/* Bars */}
            {events.map((e, i) => {
              const x = (e.min / totalMin) * 100;
              const h = heightFor(e.mag);
              const isMain = e._isMain;
              const col = isMain ? T.danger : (e.mag >= 5 ? T.warning : T.accent);
              return (
                <div key={i} style={{
                  position: "absolute", left: `${x}%`, bottom: 22,
                  width: isMain ? 4 : 2.5, height: h, background: col, borderRadius: 1.5,
                  transform: "translateX(-50%)",
                  boxShadow: isMain ? `0 0 8px ${col}80` : "none",
                }} />
              );
            })}
            {/* Top labels for the strongest events */}
            {events.filter((e) => e.mag >= Math.max(4.5, maxAft - 0.5))
              .slice(0, 5).map((e, i) => {
                const x = (e.min / totalMin) * 100;
                const h = heightFor(e.mag);
                const isMain = e._isMain;
                const col = isMain ? T.danger : T.warning;
                return (
                  <div key={"d" + i} style={{
                    position: "absolute", left: `${x}%`, bottom: 22 + h + 4,
                    fontSize: 9, fontFamily: '"JetBrains Mono", monospace',
                    color: col, fontWeight: 700, transform: "translateX(-50%)",
                  }}>{e.mag.toFixed(1)}</div>
                );
              })}
          </div>
          <div style={{ display: "flex", justifyContent: "space-between",
            fontSize: 9.5, color: T.textMuted, fontFamily: '"JetBrains Mono", monospace',
            letterSpacing: 0.5, paddingTop: 4, borderTop: `1px dashed ${T.borderSoft}` }}>
            <span>0</span>
            <span>{fmtTime(Math.floor(totalMin / 4))}</span>
            <span>{fmtTime(Math.floor(totalMin / 2))}</span>
            <span>{fmtTime(Math.floor((3 * totalMin) / 4))}</span>
            <span>{fmtTime(totalMin)}</span>
          </div>
        </div>

        {/* List, newest first */}
        <div style={{ padding: "0 14px 12px" }}>
          <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted,
            fontFamily: '"JetBrains Mono", monospace',
            padding: "10px 0 8px", borderTop: `1px solid ${T.borderSoft}`,
            display: "flex", justifyContent: "space-between" }}>
            <span>СПИСОК · НОВЕЙШИЕ СВЕРХУ</span>
            <span>{total} ШТ.</span>
          </div>
          {[...aftershocks].reverse().slice(0, 10).map((e, i) => {
            const col = e.mag >= 5 ? T.warning : T.accent;
            const min = Math.floor((new Date(e.timeUtc).getTime() - mainTime) / 60000);
            const dist = window.DATA.haversineKm(main.lat, main.lon, e.lat, e.lon);
            return (
              <div key={e.id || i} style={{
                display: "flex", alignItems: "center", gap: 12, padding: "9px 4px",
                borderBottom: i === Math.min(aftershocks.length, 10) - 1 ? "none" : `1px solid ${T.borderSoft}`,
              }}>
                <div style={{ fontSize: 10, fontFamily: '"JetBrains Mono", monospace',
                  color: T.textMuted, width: 22, letterSpacing: 0.5 }}>
                  {String(total - i).padStart(2, "0")}
                </div>
                <div style={{ width: 10, height: 10, borderRadius: 5, background: col, flexShrink: 0 }} />
                <div style={{ fontSize: 16, fontWeight: 700, color: col,
                  fontFamily: '"JetBrains Mono", monospace', minWidth: 38 }}>
                  {e.mag.toFixed(1)}
                </div>
                <div style={{ flex: 1, fontSize: 11, color: T.textDim,
                  fontFamily: '"JetBrains Mono", monospace', letterSpacing: 0.3 }}>
                  {fmtTime(min)}
                </div>
                <div style={{ fontSize: 11, color: T.textMuted,
                  fontFamily: '"JetBrains Mono", monospace' }}>
                  ~{Math.round(dist)} км
                </div>
              </div>
            );
          })}
          {total > 10 && (
            <div style={{ fontSize: 11, color: T.textMuted, padding: "8px 0",
              fontFamily: '"JetBrains Mono", monospace', textAlign: "center" }}>
              … и ещё {total - 10}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const Stat = ({ T, k, v, color, last }) => (
  <div style={{ padding: "11px 14px",
    borderRight: last ? "none" : `1px solid ${T.borderSoft}` }}>
    <div style={{ fontSize: 9, letterSpacing: 1.2, color: T.textMuted,
      fontFamily: '"JetBrains Mono", monospace', marginBottom: 4 }}>{k}</div>
    <div style={{ fontSize: 14, fontWeight: 700, color,
      fontFamily: '"JetBrains Mono", monospace' }}>{v}</div>
  </div>
);

function fmtTime(min) {
  if (min < 60) return `+${min}м`;
  const hh = Math.floor(min / 60);
  const mm = min % 60;
  if (hh < 24) return mm ? `+${hh}ч ${mm}м` : `+${hh}ч`;
  const dd = Math.floor(hh / 24);
  const rem = hh % 24;
  return rem ? `+${dd}д ${rem}ч` : `+${dd}д`;
}
