/* global React */

// ────────────────────────────────────────────────────────────
// HOME — «Научный приборный»
// Топ: статус-приборная панель + большой «последний толчок» + лента
// ────────────────────────────────────────────────────────────
window.HomeScreenA = ({ T, dark, onOpenEvent, onOpenSettings }) => {
  const data = window.DATA.useDataState();
  const events = data.events;
  const filterMag = data.userMagFilter;
  if (!events.length) {
    return (
      <div style={{ padding: 32, textAlign: "center", color: T.textMuted, fontSize: 13 }}>
        События ещё не загружены или пусты.
      </div>
    );
  }
  const last = events[0];
  const ru24 = events.filter(e => e.isRu && e.minutesAgo < 24*60).length;
  const world24 = events.filter(e => e.minutesAgo < 24*60).length;
  const recent24 = events.filter(e => e.minutesAgo < 24*60);
  const maxMag = recent24.length > 0 ? Math.max(...recent24.map(e => e.mag)) : 0;

  return (
    <div style={{ background: T.bg, color: T.text, paddingBottom: 24 }}>
      {/* Status bar */}
      <div style={{
        padding: "12px 16px", display: "flex", alignItems: "center", gap: 10,
        borderBottom: `1px solid ${T.borderSoft}`, background: T.surface,
        fontFamily: '"JetBrains Mono", monospace', fontSize: 11,
      }}>
        <window.LivePulse color={T.ok} />
        <span style={{ color: T.textDim, letterSpacing: 0.4 }}>СИСТЕМА АКТИВНА</span>
        <span style={{ color: T.textMuted }}>·</span>
        <span style={{ color: T.textMuted }}>USGS · EMSC</span>
        <span style={{ marginLeft: "auto", color: T.textMuted }}>обн. {window.formatAgo(last.minutesAgo)}</span>
      </div>

      {/* Filter pill — shows the user's active magnitude threshold and lets
          them jump straight to Settings to change it. Explains why some
          smaller events aren't shown in the feed. */}
      {typeof filterMag === "number" && (
        <div onClick={onOpenSettings} style={{
          padding: "8px 16px", display: "flex", alignItems: "center", gap: 8,
          borderBottom: `1px solid ${T.borderSoft}`, background: T.bg,
          fontFamily: '"JetBrains Mono", monospace', fontSize: 10.5,
          cursor: onOpenSettings ? "pointer" : "default",
        }}>
          <span style={{ color: T.textMuted, letterSpacing: 0.4 }}>ФИЛЬТР:</span>
          <span style={{
            color: T.accent, fontWeight: 600, letterSpacing: 0.4,
            padding: "2px 8px", borderRadius: 10, border: `1px solid ${T.accent}`,
            background: T.accentSoft,
          }}>M ≥ {filterMag.toFixed(1)}</span>
          <span style={{ marginLeft: "auto", color: T.textMuted, fontSize: 10 }}>
            настройки →
          </span>
        </div>
      )}

      {/* Hero — последнее событие */}
      <div style={{ padding: "16px 16px 0" }}>
        <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted, fontFamily: '"JetBrains Mono", monospace', marginBottom: 8 }}>
          ПОСЛЕДНЕЕ СОБЫТИЕ · {window.formatAgo(last.minutesAgo).toUpperCase()}
        </div>
        <div onClick={() => onOpenEvent(last)} style={{
          background: T.surface, border: `1px solid ${T.border}`, borderRadius: 10,
          padding: 16, cursor: "pointer", position: "relative", overflow: "hidden",
        }}>
          <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
            <window.MagBadge mag={last.mag} T={T} size={68} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, fontFamily: '"JetBrains Mono", monospace', color: window.magColor(last.mag, T), letterSpacing: 0.5 }}>
                {window.magLabel(last.mag).toUpperCase()}
              </div>
              <div style={{ fontSize: 15, fontWeight: 600, marginTop: 4, lineHeight: 1.3, letterSpacing: -0.1 }}>
                {last.place}
              </div>
              <div style={{ fontSize: 12, color: T.textDim, marginTop: 6, fontFamily: '"JetBrains Mono", monospace' }}>
                {last.lat.toFixed(2)}°N, {last.lon.toFixed(2)}°E · h={last.depth.toFixed(1)} км
              </div>
            </div>
          </div>
          <div style={{ marginTop: 14, marginLeft: -16, marginRight: -16, paddingLeft: 16, paddingRight: 16,
            paddingTop: 10, paddingBottom: 6, borderTop: `1px solid ${T.borderSoft}`,
          }}>
            <window.SeismoLine T={T} w={344} h={28} seed={Math.floor(last.mag * 10)} intense={Math.min(last.mag / 5, 1.4)} />
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4,
              fontSize: 9.5, fontFamily: '"JetBrains Mono", monospace', color: T.textMuted, letterSpacing: 0.4 }}>
              <span>{last.timeMsk} МСК</span>
              <span>{last.timeUtc.slice(11,16)} UTC</span>
              <span>{last.timeLocal} (местное)</span>
            </div>
          </div>
          {last.confirmed && (
            <div style={{
              position: "absolute", top: 10, right: 10,
              fontSize: 9.5, color: T.ok, fontFamily: '"JetBrains Mono", monospace',
              letterSpacing: 0.5,
              border: `1px solid ${T.ok}`, padding: "2px 6px", borderRadius: 3, opacity: 0.85,
            }}>✓ ПОДТВ. 2 ИСТ.</div>
          )}
        </div>
      </div>

      {/* Счётчики 24ч */}
      <div style={{ padding: "16px 16px 0", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
        <Stat T={T} label="РОССИЯ / СНГ" value={ru24} hint="за 24 ч · M≥4" />
        <Stat T={T} label="МИР" value={world24} hint="за 24 ч · M≥4" />
        <Stat T={T} label="МАКС M" value={maxMag.toFixed(1)} hint="за 24 ч" highlight />
      </div>

      {/* Лента событий */}
      <div style={{ padding: "20px 16px 0" }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 8 }}>
          <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted, fontFamily: '"JetBrains Mono", monospace' }}>
            ХРОНОЛОГИЯ · {events.length} СОБЫТИЙ
          </div>
        </div>
        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 10, overflow: "hidden" }}>
          {events.slice(1).map((e, i, arr) => (
            <EventRow key={e.id || i} ev={e} T={T} onClick={() => onOpenEvent(e)} last={i === arr.length - 1}/>
          ))}
        </div>
      </div>
    </div>
  );
};

const Stat = ({ T, label, value, hint, highlight }) => (
  <div style={{
    background: highlight ? T.accentSoft : T.surface,
    border: `1px solid ${highlight ? T.accent : T.border}`,
    borderRadius: 8, padding: "10px 10px 9px",
  }}>
    <div style={{ fontSize: 9.5, letterSpacing: 0.8, color: highlight ? T.accent : T.textMuted, fontFamily: '"JetBrains Mono", monospace' }}>{label}</div>
    <div style={{ fontSize: 24, fontWeight: 600, marginTop: 4, fontFamily: '"JetBrains Mono", monospace',
      color: highlight ? T.accent : T.text, lineHeight: 1 }}>{value}</div>
    <div style={{ fontSize: 9.5, color: T.textMuted, marginTop: 4, fontFamily: '"JetBrains Mono", monospace' }}>{hint}</div>
  </div>
);

const EventRow = ({ ev, T, onClick, last }) => (
  <div onClick={onClick} style={{
    display: "flex", gap: 12, padding: "12px 14px",
    borderBottom: last ? "none" : `1px solid ${T.borderSoft}`,
    cursor: "pointer", alignItems: "center",
  }}>
    <window.MagBadge mag={ev.mag} T={T} size={42} />
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13.5, 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: 11, 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" }}>✓</span>}
      </div>
    </div>
    <window.MiniMap lat={ev.lat} lon={ev.lon} T={T} mag={ev.mag} w={56} h={42}/>
  </div>
);

window.EventRow = EventRow;
window.Stat = Stat;
