/* global React */

// ────────────────────────────────────────────────────────────
// SETTINGS — уведомления, пороги магнитуды, тема, источники
// Phase 2: пороги/пауза летят в бот через /api/v1/config/*.
// Тема — фронтенд-only (localStorage).
// ────────────────────────────────────────────────────────────
window.SettingsScreen = ({ T, dark, onBack, onToggleTheme, onOpenAbout, onOpenSafety,
                           homeVariant, onChangeHomeVariant }) => {
  const [magRu, setMagRu] = React.useState(null);
  const [magWorld, setMagWorld] = React.useState(null);
  const [magDigest, setMagDigest] = React.useState(null);
  const [paused, setPaused] = React.useState(false);
  const [pausedUntil, setPausedUntil] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const [pauseMinutes, setPauseMinutes] = React.useState(60);

  // Load current snapshot from API on mount
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const s = await window.API.getStatus();
        if (cancelled) return;
        setMagRu(s.mag_region);
        setMagWorld(s.mag_global);
        // mag_digest may be absent on older backends — fall back to mag_region.
        setMagDigest(typeof s.mag_digest === "number" ? s.mag_digest : s.mag_region);
        setPaused(!!s.paused);
        setPausedUntil(s.paused_until || null);
      } catch (e) {
        if (!cancelled) setError(e.message || String(e));
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  // Debounced threshold push (fires 400ms after last change)
  const pushThreshold = React.useMemo(() => {
    let timer = null;
    return (target, value) => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(async () => {
        try {
          await window.API.setThreshold(target, value);
          const human = target === "region" ? "регион"
                      : target === "global" ? "мир"
                      : "дайджест";
          showToast(`✓ M ${human} → ${value.toFixed(1)}`);
        } catch (e) {
          showToast(`❌ ${e.message}`);
        }
      }, 400);
    };
  }, []);

  function showToast(msg) {
    setToast(msg);
    setTimeout(() => setToast(null), 2500);
  }

  async function togglePause() {
    const minutes = paused ? 0 : pauseMinutes;
    try {
      const r = await window.API.setPause(minutes);
      setPaused(!!r.paused);
      setPausedUntil(r.paused_until || null);
      showToast(paused ? "✓ Алерты возобновлены" : `✓ Пауза на ${minutes} мин`);
    } catch (e) {
      showToast(`❌ ${e.message}`);
    }
  }

  if (loading) {
    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,
          fontFamily: '"JetBrains Mono", monospace' }}>
          ЗАГРУЗКА…
        </div>
      </div>
    );
  }
  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, fontSize: 13, color: T.text }}>
          <div style={{ marginBottom: 8 }}>⚠️ Не удалось связаться с ботом:</div>
          <div style={{ color: T.danger, fontFamily: '"JetBrains Mono", monospace',
            fontSize: 11, marginBottom: 12 }}>{error}</div>
          <div style={{ color: T.textMuted, fontSize: 11.5, lineHeight: 1.5 }}>
            Возможные причины: API не запущен на сервере, либо ты открыл Mini App
            не из своего бота. Изменить пороги можно через команду
            <code style={{ background: T.surface, padding: "1px 6px", borderRadius: 3,
              fontFamily: '"JetBrains Mono", monospace', margin: "0 4px" }}>/set</code>
            в чате с ботом.
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ background: T.bg, color: T.text, paddingBottom: 32, minHeight: "100%",
      position: "relative" }}>
      <window.ScreenHeader title="Настройки" subtitle="уведомления и пороги" onBack={onBack} T={T} />

      <div style={{ padding: 16 }}>
        {/* Emergency reference at the very top — first thing users see when
            they open Settings.  Below that come the regular config blocks. */}
        <button onClick={onOpenSafety} style={{
          width: "100%", padding: "14px 16px", marginBottom: 18,
          background: T.warning, color: "#fff", border: "none",
          borderRadius: 10, cursor: "pointer", fontFamily: 'inherit',
          fontSize: 14, fontWeight: 600,
          display: "flex", alignItems: "center", justifyContent: "space-between",
          boxShadow: dark ? "0 1px 4px rgba(232,177,70,0.2)" : "0 1px 4px rgba(200,136,28,0.15)",
        }}>
          <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 20 }}>🚨</span>
            <span style={{ textAlign: "left" }}>
              <div>Что делать при землетрясении</div>
              <div style={{ fontSize: 11, fontWeight: 400, opacity: 0.9, marginTop: 2,
                fontFamily: '"JetBrains Mono", monospace', letterSpacing: 0.4 }}>
                СПРАВОЧНИК · 5 СИТУАЦИЙ
              </div>
            </span>
          </span>
          <span style={{ fontSize: 20, opacity: 0.85 }}>›</span>
        </button>

        <Section T={T} title="ПОРОГИ МАГНИТУДЫ">
          <Slider T={T} label="Россия / СНГ — алерты" value={magRu} min={3.0} max={6.0} step={0.1}
            onChange={(v) => { setMagRu(v); pushThreshold("region", v); }}
            hint={`Оповещать при M ≥ ${magRu.toFixed(1)} (в реальном времени)`} />
          <window.Divider T={T} />
          <Slider T={T} label="Весь мир — алерты" value={magWorld} min={5.0} max={8.0} step={0.1}
            onChange={(v) => { setMagWorld(v); pushThreshold("global", v); }}
            hint={`Оповещать при M ≥ ${magWorld.toFixed(1)} (в реальном времени)`} />
          <window.Divider T={T} />
          <Slider T={T} label="Дайджест 2× в сутки"
            value={magDigest ?? magRu} min={3.5} max={7.0} step={0.1}
            onChange={(v) => {
              setMagDigest(v);
              pushThreshold("digest", v);
              // Update Mini App feed filter immediately so the Лента/Сводка
              // screens reflect the new threshold without re-opening the app.
              if (window.DATA && window.DATA.setUserMagFilter) {
                window.DATA.setUserMagFilter(v);
              }
            }}
            hint={`Сводка 08:00/20:00 МСК и Лента — события M ≥ ${(magDigest ?? magRu).toFixed(1)}`} />
        </Section>

        <Section T={T} title="ПАУЗА АЛЕРТОВ">
          <div style={{ padding: 14 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <div style={{ fontSize: 13.5, fontWeight: 500 }}>
                {paused ? "Алерты на паузе" : "Алерты включены"}
              </div>
              <div style={{ fontSize: 11, color: paused ? T.warning : T.ok,
                fontFamily: '"JetBrains Mono", monospace' }}>
                {paused && pausedUntil ? `до ${formatPausedUntil(pausedUntil)}` : ""}
              </div>
            </div>
            {!paused && (
              <div style={{ marginTop: 12 }}>
                <div style={{ fontSize: 10.5, color: T.textMuted, marginBottom: 8,
                  fontFamily: '"JetBrains Mono", monospace' }}>
                  Длительность паузы: <b>{pauseMinutes} мин</b>
                </div>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {[15, 30, 60, 120, 240].map(m => (
                    <button key={m} onClick={() => setPauseMinutes(m)} style={{
                      padding: "5px 12px", borderRadius: 14,
                      border: `1px solid ${pauseMinutes === m ? T.accent : T.border}`,
                      background: pauseMinutes === m ? T.accentSoft : "transparent",
                      color: pauseMinutes === m ? T.accent : T.text,
                      fontSize: 11, cursor: "pointer",
                      fontFamily: '"JetBrains Mono", monospace',
                      fontWeight: pauseMinutes === m ? 600 : 400,
                    }}>{m} мин</button>
                  ))}
                </div>
              </div>
            )}
            <button onClick={togglePause} style={{
              marginTop: 14, width: "100%", padding: "11px",
              background: paused ? T.ok : T.accent, color: "#fff",
              border: "none", borderRadius: 8, cursor: "pointer",
              fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
            }}>
              {paused ? "▶️ Возобновить алерты" : `⏸ Поставить на паузу (${pauseMinutes} мин)`}
            </button>
          </div>
        </Section>

        <Section T={T} title="СТИЛЬ ДОМАШНЕЙ">
          <HomeVariantPicker T={T} value={homeVariant || "A"}
            onChange={onChangeHomeVariant} />
        </Section>

        <Section T={T} title="ВНЕШНИЙ ВИД">
          <button onClick={onToggleTheme} style={{
            width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "14px", background: "none", border: "none", color: T.text,
            cursor: "pointer", fontFamily: "inherit", textAlign: "left",
          }}>
            <div>
              <div style={{ fontSize: 13.5 }}>Тема</div>
              <div style={{ fontSize: 11, color: T.textMuted, marginTop: 2,
                fontFamily: '"JetBrains Mono", monospace' }}>
                {dark ? "Тёмная" : "Светлая"}
              </div>
            </div>
            <div style={{ display: "flex", gap: 4, padding: 3, background: T.surface2,
              borderRadius: 14, border: `1px solid ${T.border}` }}>
              <span style={{
                padding: "3px 10px", borderRadius: 11, fontSize: 11,
                background: !dark ? T.surface : "transparent",
                fontWeight: !dark ? 600 : 400,
                color: !dark ? T.text : T.textMuted,
                border: !dark ? `1px solid ${T.border}` : "1px solid transparent",
              }}>светлая</span>
              <span style={{
                padding: "3px 10px", borderRadius: 11, fontSize: 11,
                background: dark ? T.surface : "transparent",
                fontWeight: dark ? 600 : 400,
                color: dark ? T.text : T.textMuted,
                border: dark ? `1px solid ${T.border}` : "1px solid transparent",
              }}>тёмная</span>
            </div>
          </button>
        </Section>

        <Section T={T} title="ИСТОЧНИКИ ДАННЫХ">
          <DataSource T={T} name="USGS" desc="U.S. Geological Survey · глобальное покрытие" />
          <window.Divider T={T} />
          <DataSource T={T} name="EMSC" desc="European-Mediterranean Seismological Centre" />
        </Section>

        <button onClick={onOpenAbout} style={{
          marginTop: 8, width: "100%", padding: "13px",
          background: "transparent", border: `1px solid ${T.border}`,
          borderRadius: 10, cursor: "pointer", color: T.text,
          fontSize: 13, fontFamily: 'inherit', fontWeight: 500,
        }}>О приложении →</button>
      </div>

      {toast && (
        <div style={{
          position: "fixed", bottom: 80, left: 0, right: 0,
          display: "flex", justifyContent: "center", pointerEvents: "none",
          zIndex: 100,
        }}>
          <div style={{
            background: T.surface, border: `1px solid ${T.border}`,
            color: T.text, padding: "9px 16px", borderRadius: 20,
            fontSize: 12.5, fontFamily: 'inherit',
            boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
          }}>{toast}</div>
        </div>
      )}
    </div>
  );
};

// ────────────────────────────────────────────

const Section = ({ T, title, children }) => (
  <div style={{ marginBottom: 20 }}>
    <div style={{ fontSize: 10, letterSpacing: 1.4, color: T.textMuted,
      fontFamily: '"JetBrains Mono", monospace', marginBottom: 8, paddingLeft: 4 }}>
      {title}
    </div>
    <div style={{ background: T.surface, border: `1px solid ${T.border}`,
      borderRadius: 10, overflow: "hidden" }}>{children}</div>
  </div>
);

const Slider = ({ T, label, value, min, max, step, onChange, hint }) => (
  <div style={{ padding: "14px" }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
      <div style={{ fontSize: 13.5, fontWeight: 500 }}>{label}</div>
      <div style={{ fontSize: 16, fontWeight: 600, color: T.accent,
        fontFamily: '"JetBrains Mono", monospace' }}>M ≥ {value.toFixed(1)}</div>
    </div>
    <input type="range" min={min} max={max} step={step} value={value}
      onChange={e => onChange(parseFloat(e.target.value))}
      style={{ width: "100%", marginTop: 10, accentColor: T.accent }} />
    <div style={{ display: "flex", justifyContent: "space-between",
      fontSize: 9.5, color: T.textMuted, marginTop: 4, fontFamily: '"JetBrains Mono", monospace' }}>
      <span>M {min.toFixed(1)}</span>
      <span style={{ flex: 1, textAlign: "center" }}>{hint}</span>
      <span>M {max.toFixed(1)}</span>
    </div>
  </div>
);

const DataSource = ({ T, name, desc }) => (
  <div style={{ padding: "14px", display: "flex", alignItems: "center", gap: 12 }}>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13.5, fontWeight: 600,
        fontFamily: '"JetBrains Mono", monospace' }}>{name}</div>
      <div style={{ fontSize: 11, color: T.textMuted, marginTop: 2 }}>{desc}</div>
    </div>
    <div style={{ display: "flex", alignItems: "center", gap: 6,
      fontSize: 10.5, color: T.ok, fontFamily: '"JetBrains Mono", monospace',
      letterSpacing: 0.4 }}>
      <window.LivePulse color={T.ok} size={6} />
      ONLINE
    </div>
  </div>
);

// 3-button picker for the home variant. Stores label + 1-line description.
const HomeVariantPicker = ({ T, value, onChange }) => {
  const variants = [
    { id: "A", label: "Приборный",   desc: "Hero событие + сейсмограмма" },
    { id: "B", label: "Карта-первая", desc: "Live-карта сверху, лента снизу" },
    { id: "C", label: "Минимализм",   desc: "Чистая хронология по дням" },
  ];
  return (
    <div style={{ padding: 14 }}>
      <div style={{ display: "flex", gap: 6, marginBottom: 10 }}>
        {variants.map((v) => {
          const active = v.id === value;
          return (
            <button key={v.id} onClick={() => onChange && onChange(v.id)}
              style={{
                flex: 1, padding: "10px 8px", borderRadius: 8,
                border: `1px solid ${active ? T.accent : T.border}`,
                background: active ? T.accentSoft : "transparent",
                color: active ? T.accent : T.text,
                cursor: "pointer", fontFamily: "inherit",
                display: "flex", flexDirection: "column", alignItems: "center", gap: 4,
              }}>
              <span style={{ fontSize: 16, fontWeight: 700,
                fontFamily: '"JetBrains Mono", monospace' }}>{v.id}</span>
              <span style={{ fontSize: 11, fontWeight: active ? 600 : 400 }}>{v.label}</span>
            </button>
          );
        })}
      </div>
      <div style={{ fontSize: 11, color: T.textMuted,
        fontFamily: '"JetBrains Mono", monospace', textAlign: "center" }}>
        {variants.find((v) => v.id === value)?.desc || ""}
      </div>
    </div>
  );
};

function formatPausedUntil(iso) {
  try {
    const d = new Date(iso);
    return new Intl.DateTimeFormat("ru-RU", {
      hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "Europe/Moscow",
    }).format(d) + " МСК";
  } catch (e) {
    return iso;
  }
}
