/* global React */

// ────────────────────────────────────────────────────────────
// EVENT DETAIL — детали одного события
// ────────────────────────────────────────────────────────────
window.EventDetailScreen = ({ T, dark, ev, onBack, onShowTsunami }) => {
  const mapRef = React.useRef(null);
  const mapId = React.useMemo(() => "map-detail-" + Math.random().toString(36).slice(2,8), []);

  React.useEffect(() => {
    if (!window.L || !ev) return;
    if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; }
    const m = window.L.map(mapId, {
      zoomControl: false, attributionControl: false,
    }).setView([ev.lat, ev.lon], 5);
    const tileUrl = dark
      ? "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
      : "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png";
    window.L.tileLayer(tileUrl, { maxZoom: 10 }).addTo(m);
    const color = window.magColor(ev.mag, T);
    const r = 8 + (ev.mag - 4) * 5;
    window.L.circleMarker([ev.lat, ev.lon], {
      radius: r, color, fillColor: color, fillOpacity: 0.35, weight: 2,
    }).addTo(m);
    window.L.circleMarker([ev.lat, ev.lon], {
      radius: 3, color: "#fff", fillColor: color, fillOpacity: 1, weight: 2,
    }).addTo(m);
    mapRef.current = m;
    return () => { if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; } };
  }, [dark, ev]);

  if (!ev) return null;

  const usgsUrl = ev.id && /^[a-z0-9]+$/i.test(String(ev.id))
    ? `https://earthquake.usgs.gov/earthquakes/eventpage/${ev.id}`
    : null;

  return (
    <div style={{ background: T.bg, color: T.text, paddingBottom: 32 }}>
      <window.ScreenHeader title="Событие" subtitle={ev.id || ""} onBack={onBack} T={T} />

      <div style={{ position: "relative", height: 220, background: T.surface2 }}>
        <div id={mapId} style={{ position: "absolute", inset: 0 }} />
      </div>

      <div style={{ padding: "16px" }}>
        <div style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
          <window.MagBadge mag={ev.mag} T={T} size={88} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, fontFamily: '"JetBrains Mono", monospace',
              color: window.magColor(ev.mag, T), letterSpacing: 0.5 }}>
              {window.magLabel(ev.mag).toUpperCase()}
            </div>
            <div style={{ fontSize: 17, fontWeight: 600, marginTop: 4, lineHeight: 1.25 }}>
              {ev.place}
            </div>
            <div style={{ fontSize: 12, color: T.textDim, marginTop: 6,
              fontFamily: '"JetBrains Mono", monospace' }}>
              {ev.flag} {ev.region}
            </div>
          </div>
        </div>

        {/* Сейсмограф */}
        <div style={{
          marginTop: 16, background: T.surface, border: `1px solid ${T.border}`,
          borderRadius: 8, padding: "12px 14px",
        }}>
          <div style={{ fontSize: 10, letterSpacing: 1.2, color: T.textMuted,
            fontFamily: '"JetBrains Mono", monospace', marginBottom: 8 }}>
            ВОЛНОВАЯ ФОРМА · ИЛЛЮСТРАТИВНО
          </div>
          <window.SeismoLine T={T} w={344} h={48} seed={Math.floor(ev.mag * 13 + ev.lat)}
            intense={Math.min(ev.mag / 4, 1.6)} />
        </div>

        {/* Параметры */}
        <div style={{ marginTop: 16, background: T.surface, border: `1px solid ${T.border}`,
          borderRadius: 8, overflow: "hidden" }}>
          <Row T={T} k="МАГНИТУДА" v={`M ${ev.mag.toFixed(1)}`} />
          <Row T={T} k="ГЛУБИНА" v={`${ev.depth.toFixed(1)} км`} />
          <Row T={T} k="ШИРОТА" v={`${ev.lat.toFixed(4)}° ${ev.lat >= 0 ? "N" : "S"}`} />
          <Row T={T} k="ДОЛГОТА" v={`${ev.lon.toFixed(4)}° ${ev.lon >= 0 ? "E" : "W"}`} />
          <Row T={T} k="ВРЕМЯ UTC" v={fmtFull(ev.timeUtc, "UTC")} />
          <Row T={T} k="ВРЕМЯ МСК" v={fmtFull(ev.timeUtc, "Europe/Moscow")} />
          <Row T={T} k="МЕСТНОЕ" v={ev.timeLocal} />
          <Row T={T} k="ИСТОЧНИКИ" v={ev.sources.join(" + ") || "—"} last />
        </div>

        {ev.confirmed && (
          <div style={{ marginTop: 12, padding: "10px 12px",
            border: `1px solid ${T.ok}`, borderRadius: 6,
            display: "flex", alignItems: "center", gap: 8,
            fontSize: 12, color: T.ok, fontFamily: '"JetBrains Mono", monospace' }}>
            ✓ Событие подтверждено двумя независимыми источниками
          </div>
        )}

        {/* Tsunami warning notice for qualifying events (M >= 6.5, h <= 50, oceanic). */}
        {window.TsunamiNotice && (
          <window.TsunamiNotice T={T} dark={dark} ev={ev} onOpenDetail={onShowTsunami} />
        )}

        {/* Aftershocks timeline — appears for M >= 5 if ≥ 2 aftershocks found. */}
        {ev.mag >= 5.0 && window.AftershockSection && (
          <window.AftershockSection T={T} dark={dark} mainEvent={ev} />
        )}

        <div style={{ marginTop: 20, display: "grid",
          gridTemplateColumns: usgsUrl ? "1fr 1fr" : "1fr", gap: 8 }}>
          <Btn T={T} primary onClick={() => share(ev)}>Поделиться</Btn>
          {usgsUrl && (
            <Btn T={T} onClick={() => window.open(usgsUrl, "_blank")}>Открыть в USGS</Btn>
          )}
        </div>
      </div>
    </div>
  );
};

const Row = ({ T, k, v, last }) => (
  <div style={{
    display: "flex", justifyContent: "space-between", alignItems: "center",
    padding: "11px 14px",
    borderBottom: last ? "none" : `1px solid ${T.borderSoft}`,
    fontFamily: '"JetBrains Mono", monospace',
  }}>
    <span style={{ fontSize: 10.5, color: T.textMuted, letterSpacing: 0.6 }}>{k}</span>
    <span style={{ fontSize: 13, color: T.text, fontWeight: 500 }}>{v}</span>
  </div>
);

const Btn = ({ T, primary, children, onClick }) => (
  <button onClick={onClick} style={{
    padding: "12px", borderRadius: 8,
    border: `1px solid ${primary ? T.accent : T.border}`,
    background: primary ? T.accent : "transparent",
    color: primary ? (T === window.TOKENS.dark ? "#1B1A17" : "#fff") : T.text,
    fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: 'inherit',
    letterSpacing: 0.2,
  }}>{children}</button>
);

// Unified date-time formatter: "21:38:53 04 мая 2026"
function fmtFull(iso, tz) {
  const months = [
    "января", "февраля", "марта", "апреля", "мая", "июня",
    "июля", "августа", "сентября", "октября", "ноября", "декабря",
  ];
  const fmt = new Intl.DateTimeFormat("en-GB", {
    timeZone: tz,
    year: "numeric", month: "numeric", day: "2-digit",
    hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false,
  });
  const parts = fmt.formatToParts(new Date(iso));
  const get = (t) => parts.find((p) => p.type === t)?.value || "";
  const day = get("day"), month = get("month"), year = get("year");
  const h = get("hour"), m = get("minute"), s = get("second");
  return `${h}:${m}:${s}  ${day} ${months[parseInt(month, 10) - 1] || ""} ${year}`;
}

// Share — copy a one-line summary to the clipboard with a small confirmation.
// Native navigator.share on Windows surfaces only Outlook/Teams/Mail (no
// Telegram), so a clipboard copy is the most reliable cross-platform path.
function share(ev) {
  const text =
    `M ${ev.mag.toFixed(1)} · ${ev.place}\n` +
    `${ev.timeMsk} МСК · h=${ev.depth.toFixed(1)} км · ${ev.lat.toFixed(2)}°N, ${ev.lon.toFixed(2)}°E`;

  // Inside Telegram clients prefer the native "share with chat" sheet.
  const tg = window.Telegram?.WebApp;
  if (tg?.shareMessage) {
    try { tg.shareMessage(text); return; } catch (e) {}
  }
  // Outside Telegram (or older clients) — copy + brief tooltip-style hint.
  try {
    navigator.clipboard.writeText(text).then(() => {
      const node = document.createElement("div");
      node.textContent = "Скопировано в буфер";
      node.style.cssText =
        "position:fixed;bottom:20px;left:50%;transform:translateX(-50%);" +
        "background:#1B1A17;color:#F4F1EA;padding:10px 18px;border-radius:20px;" +
        "font:500 13px Manrope,sans-serif;z-index:9999;box-shadow:0 4px 12px rgba(0,0,0,0.2);";
      document.body.appendChild(node);
      setTimeout(() => node.remove(), 2000);
    });
  } catch (e) {
    // Last-resort fallback.
    if (navigator.share) navigator.share({ text }).catch(() => {});
  }
}
