// The Add events page: a chat where each message becomes an event the tower reads (EventChat),
// and the event run that walks the feed (EventRun).
import { useCallback, useEffect, useRef, useState } from "react";
import { Icon } from "../lib/icons.jsx";
import { useData } from "../lib/data.jsx";
import { go, useUi } from "../lib/ui.jsx";
import { MIC_SETTINGS, clock, useVoice } from "../lib/voice.js";
import { useSettings } from "../lib/settings.jsx";
import { ACCEPT, AttachError, readAttachment } from "../lib/attach.js";
import { CardHead } from "./common.jsx";
import { RESET_EVENT, ResetButton } from "./ResetButton.jsx";
import { msg, tr } from "../lib/i18n.js";
const EMPTY = { seq: 0, running: false, current: null, done: 0, total: 0, error: null, events: [] };
const MAX = 4000;
// Starters fill the box with a message built from real records, so each one reads as its kind.
// The labels are translated when shown; the sample messages stay English, like real ops traffic.
const STARTERS = [
[msg("Supplier delay"), "Shipment SH-0310 of airbag modules for Greensboro was due Monday Mar 15 and will now arrive Thursday Mar 18. Reason: a customs hold."],
[msg("Plant outage"), "Greensboro plant update: a power failure. We're dark from Tuesday Mar 23 through Wednesday Mar 24; the line restarts the following working day."],
[msg("Quality hold"), "Quality alert: lot LOT-0247 of 60 kWh battery packs installed at Huntsville on vehicles built 2027-03-02 to 2027-03-03 failed a cell inspection. Hold the lot."],
[msg("Rumor"), "Someone at the supplier day said a brake supplier might be running behind. Nothing confirmed, no dates."],
];
export function EventChat() {
const { reload } = useData();
const { toast, set } = useUi();
const [chat, setChat] = useState([]);
// Reset events clears the chat history on the server; clear this copy of it too.
useEffect(() => {
const on = (e) => { if (e.detail?.kind === "events") setChat([]); };
window.addEventListener(RESET_EVENT, on);
return () => window.removeEventListener(RESET_EVENT, on);
}, []);
const [text, setText] = useState("");
const [busy, setBusy] = useState(false);
const [waited, setWaited] = useState(0);
const log = useRef(null);
const box = useRef(null);
const file = useRef(null);
const { settings } = useSettings();
const [note, setNote] = useState(null); // a voice problem, shown under the box
const heard = useCallback((words) => {
setNote(null);
setText((prev) => `${prev.trim() ? `${prev.trimEnd()} ` : ""}${words}`.slice(0, MAX));
box.current?.focus();
}, []);
const problem = useCallback((message) => setNote({ text: message }), []);
const voice = useVoice({ lang: settings.voiceLang, onText: heard, onProblem: problem });
const recording = voice.state === "recording", transcribing = voice.state === "transcribing";
const voiceBusy = voice.state !== "idle";
// While recording: Esc cancels, Enter stops and transcribes.
useEffect(() => {
if (!recording) return undefined;
const on = (e) => {
if (e.key === "Escape") { e.preventDefault(); voice.cancel(); }
if (e.key === "Enter") { e.preventDefault(); voice.stop(); }
};
document.addEventListener("keydown", on);
return () => document.removeEventListener("keydown", on);
}, [recording, voice]);
const micSettings = () => {
if (window.towerDesktop?.openMicSettings) window.towerDesktop.openMicSettings();
else window.location.href = MIC_SETTINGS;
};
useEffect(() => {
(async () => {
try {
const res = await fetch("/api/events/chat", { cache: "no-store" });
if (res.ok) setChat((await res.json()).messages || []);
} catch { /* the transcript stays empty */ }
})();
}, []);
useEffect(() => {
const el = log.current;
if (el) el.scrollTop = el.scrollHeight;
}, [chat, busy]);
// The box grows with its text, up to the CSS max-height (Safari has no field-sizing).
useEffect(() => {
const el = box.current;
if (!el) return;
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
}, [text]);
// Seconds since the message was sent, for the thinking bubble.
useEffect(() => {
if (!busy) { setWaited(0); return undefined; }
const t0 = Date.now();
const timer = setInterval(() => setWaited(Math.floor((Date.now() - t0) / 1000)), 1000);
return () => clearInterval(timer);
}, [busy]);
const open = (id) => { set({ sel: id, openEvent: id }); go("#/events"); };
const fill = (value) => { setText(value); box.current?.focus(); };
const attach = async (e) => {
const f = e.target.files?.[0];
e.target.value = "";
if (!f) return;
try {
const texts = await readAttachment(f);
if (texts.length > 1) { setNote({ text: tr("{name} has {texts} events.", { name: f.name, texts: texts.length }), batch: texts }); return; }
if (texts[0].length > MAX) toast(tr("{name} is long; only the first {MAX} characters were added", { name: f.name, MAX: MAX.toLocaleString() }));
setNote(null);
fill(texts[0].slice(0, MAX));
} catch (err) {
setNote({ text: err instanceof AttachError ? err.message : tr("Could not read {name}.", { name: f.name }) });
}
};
// One message to the tower. Returns true when it was added to the feed.
const post = async (message) => {
setChat((rows) => [...rows, { role: "user", text: message }]);
try {
const res = await fetch("/api/events/chat", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: message }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
toast(data.error || "Could not add that event");
setChat((rows) => rows.slice(0, -1));
return false;
}
setChat((rows) => [...rows, { role: "tower", text: data.reply, event_id: data.event.event_id }]);
set({ sel: data.event.event_id });
return true;
} catch {
toast(tr("Could not add that event"));
setChat((rows) => rows.slice(0, -1));
return false;
}
};
const send = async () => {
const message = text.trim();
if (!message || busy || voiceBusy) return;
setBusy(true);
setText("");
try {
if (!(await post(message))) setText(message);
else await reload();
} finally {
setBusy(false);
}
};
// A JSON file with several events: add them one after another, in order.
const sendAll = async (texts) => {
setNote(null);
setBusy(true);
let added = 0;
try {
for (const t of texts) {
if (!(await post(t.slice(0, MAX)))) break;
added += 1;
}
await reload();
toast(tr("Added {added} of {texts} events", { added: added, texts: texts.length }));
} finally {
setBusy(false);
}
};
const fresh = !chat.length && !busy;
return (
{tr("Paste a supplier email, plant alert, quality bulletin or chat message. The tower reads it, traces the records it touches and acts, or asks a person when it isn't sure.")}{tr("What happened in operations?")}