File size: 9,173 Bytes
96bba34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { useEffect, useRef, useState } from "react";

import {
  getFlight,
  getFlights,
  simulate,
  type FlightDetail,
  type FlightSummary,
  type InjectedFlight,
  type SimulationResult,
} from "../api";
import AlertBanner from "../components/AlertBanner";
import RadarPlot from "../components/RadarPlot";
import ScoreTimeline from "../components/ScoreTimeline";
import { useT } from "../i18n";

interface SimulatorProps {
  onInject: (flight: InjectedFlight) => void;
  hasInjected: boolean;
  onClearInjected: () => void;
}

interface KindConfig {
  id: string;
  min: number;
  max: number;
  step: number;
  def: number;
  unit: string;
}

const KINDS: KindConfig[] = [
  { id: "route_deviation", min: 0, max: 80000, step: 2000, def: 40000, unit: "m" },
  { id: "altitude", min: 0, max: 2500, step: 100, def: 1200, unit: "m" },
  { id: "speed", min: 0.3, max: 2.6, step: 0.1, def: 2.2, unit: "x" },
  { id: "holding", min: 60, max: 300, step: 20, def: 160, unit: "s/turn" },
  { id: "freeze", min: 0, max: 0, step: 1, def: 0, unit: "" },
];

const MOBILE_BREAKPOINT_QUERY = "(max-width: 900px)";
const SLIDER_TRACK_HEIGHT = 26;
const INJECT_BUTTON_PADDING_MOBILE = "14px";
const INJECT_BUTTON_PADDING_DESKTOP = "10px";
const INJECT_BUTTON_FONT_MOBILE = 13;

function useIsMobile() {
  const [isMobile, setIsMobile] = useState(() => {
    if (typeof window === "undefined") return false;
    return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches;
  });
  useEffect(() => {
    if (typeof window === "undefined") return;
    const mql = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
    const handler = (event: MediaQueryListEvent) => setIsMobile(event.matches);
    setIsMobile(mql.matches);
    mql.addEventListener("change", handler);
    return () => mql.removeEventListener("change", handler);
  }, []);
  return isMobile;
}

export default function Simulator({ onInject, hasInjected, onClearInjected }: SimulatorProps) {
  const t = useT();
  const isMobile = useIsMobile();
  const [bases, setBases] = useState<FlightSummary[]>([]);
  const [baseId, setBaseId] = useState<number | null>(null);
  const [baseDetail, setBaseDetail] = useState<FlightDetail | null>(null);
  const [kind, setKind] = useState("speed");
  const [magnitude, setMagnitude] = useState(2.2);
  const [onset, setOnset] = useState(0.5);
  const [result, setResult] = useState<SimulationResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const simSeedRef = useRef(1);

  useEffect(() => {
    getFlights(20, "typical")
      .then((rows) => {
        setBases(rows);
        if (rows.length) setBaseId(rows[0].id);
      })
      .catch((reason) => setError(String(reason)));
  }, []);

  useEffect(() => {
    if (baseId == null) return;
    getFlight(baseId)
      .then(setBaseDetail)
      .catch((reason) => setError(String(reason)));
  }, [baseId]);

  useEffect(() => {
    if (baseId == null) return;
    simulate({ id: baseId, kind, magnitude, onset })
      .then(setResult)
      .catch((reason) => setError(String(reason)));
  }, [baseId, kind, magnitude, onset]);

  if (error) {
    return <div className="status-alert">{t.monitor.offline}</div>;
  }

  const config = KINDS.find((entry) => entry.id === kind)!;

  function changeKind(id: string) {
    setKind(id);
    setMagnitude(KINDS.find((entry) => entry.id === id)!.def);
  }

  const controlsPanel = (
    <div className="panel" style={{ padding: 16, display: "grid", gap: 16, alignContent: "start", overflowY: "auto", minHeight: 0 }}>
      <div>
        <div className="label">{t.simulator.baseFlight}</div>
        <select
          value={baseId ?? ""}
          onChange={(event) => setBaseId(Number(event.target.value))}
          style={{ width: "100%", marginTop: 6, background: "var(--bg-deep)", color: "var(--text)", border: "1px solid var(--panel-edge)", padding: 8, fontFamily: "var(--mono)" }}
        >
          {bases.map((flight) => (
            <option key={flight.id} value={flight.id}>
              WIN {String(flight.id).padStart(5, "0")} ({flight.score.toFixed(2)})
            </option>
          ))}
        </select>
      </div>

      <div>
        <div className="label">{t.simulator.injectedAnomaly}</div>
        <div style={{ display: "grid", gap: 4, marginTop: 6 }}>
          {KINDS.map((entry) => (
            <button
              key={entry.id}
              onClick={() => changeKind(entry.id)}
              style={{ textAlign: "left", borderColor: kind === entry.id ? "var(--alert)" : "var(--panel-edge)", color: kind === entry.id ? "var(--alert)" : "var(--text)" }}
            >
              {t.simulator.kinds[entry.id]}
            </button>
          ))}
        </div>
      </div>

      {config.max > config.min && (
        <div>
          <div className="label">
            {t.simulator.intensity}: {magnitude}
            {config.unit}
          </div>
          <input
            type="range"
            min={config.min}
            max={config.max}
            step={config.step}
            value={magnitude}
            onChange={(event) => setMagnitude(Number(event.target.value))}
            style={{ width: "100%", marginTop: 8, accentColor: "var(--alert)", height: SLIDER_TRACK_HEIGHT }}
          />
        </div>
      )}

      <div>
        <div className="label">
          {t.simulator.onset}: {(onset * 100).toFixed(0)}
          {t.simulator.onsetSuffix}
        </div>
        <input
          type="range"
          min={0.1}
          max={0.8}
          step={0.05}
          value={onset}
          onChange={(event) => setOnset(Number(event.target.value))}
          style={{ width: "100%", marginTop: 8, accentColor: "var(--warn)", height: SLIDER_TRACK_HEIGHT }}
        />
      </div>

      <div
        style={{
          borderTop: "1px solid var(--panel-edge)",
          paddingTop: 14,
          display: "flex",
          flexDirection: "column",
          gap: 8,
          position: isMobile ? "sticky" : "static",
          bottom: isMobile ? 0 : "auto",
          background: isMobile ? "var(--bg-panel)" : "transparent",
          boxShadow: isMobile ? "0 -8px 16px rgba(0, 0, 0, 0.45)" : "none",
          zIndex: 2,
        }}
      >
        <button
          disabled={!result}
          onClick={() => {
            if (!result) return;
            const seed = simSeedRef.current++;
            const injected: InjectedFlight = {
              id: 100000 + seed,
              callsign: "SDR001",
              path: result.path,
              scores: result.scores,
              anomalous: true,
              start_offset: 0,
              injected: true,
              kind: result.kind,
            };
            onInject(injected);
          }}
          style={{
            padding: isMobile ? INJECT_BUTTON_PADDING_MOBILE : INJECT_BUTTON_PADDING_DESKTOP,
            fontSize: isMobile ? INJECT_BUTTON_FONT_MOBILE : undefined,
            borderColor: "#d96bd9",
            color: "#d96bd9",
            fontWeight: 700,
            letterSpacing: "0.12em",
          }}
        >
          {"> INJECT INTO MONITOR"}
        </button>
        {hasInjected && (
          <button
            onClick={onClearInjected}
            style={{ padding: "6px", borderColor: "#d96bd9", color: "#d96bd9" }}
          >
            CLEAR INJECTED
          </button>
        )}
        <div style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.04em", lineHeight: 1.4 }}>
          Appears in the Monitor as <span style={{ color: "#d96bd9" }}>SDR001</span> within 5 s.
          Replaces any previous injection.
        </div>
      </div>
    </div>
  );

  const radarColumn = (
    <div style={{ display: "flex", flexDirection: "column", gap: 10, minHeight: 0, minWidth: 0 }}>
      {result && (
        <AlertBanner
          scores={result.scores}
          stepThreshold={result.step_threshold}
          latency={result.latency_seconds}
        />
      )}
      {result && baseDetail && (
        <div className="panel" style={{ flex: 1, minHeight: 320, padding: 10 }}>
          <RadarPlot
            tracks={[
              { points: baseDetail.path, color: "var(--muted)", label: t.simulator.original, dashed: true },
              { points: result.path, color: "var(--alert)", label: t.simulator.injected },
            ]}
          />
        </div>
      )}
    </div>
  );

  const timelineColumn = (
    <div style={{ display: "flex", flexDirection: "column", minHeight: 260, minWidth: 0 }}>
      <div className="label" style={{ marginBottom: 6 }}>{t.monitor.scoreTitle}</div>
      {result && (
        <div style={{ flex: 1, minHeight: 220 }}>
          <ScoreTimeline
            scores={result.scores}
            threshold={result.step_threshold}
            onsetIndex={result.onset_index}
          />
        </div>
      )}
    </div>
  );

  if (isMobile) {
    return (
      <div className="simulator-layout">
        {radarColumn}
        {controlsPanel}
        {timelineColumn}
      </div>
    );
  }

  return (
    <div className="simulator-layout">
      {controlsPanel}
      {radarColumn}
      {timelineColumn}
    </div>
  );
}