import { dismissClientJob, startClientUpdate, stopClientJob, syncClient, useClientJob } from "@/lib/clientJob";
import { useCallback, useEffect, useRef, useState } from "react";
import { Loader2, X } from "lucide-react";
import { api, asUiError, type ClientInfo, type Human, type Performance, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api";
import { cn, formatBytes, formatUptime } from "@/lib/utils";
import { useHuman, useT } from "@/i18n";
import { applyServerUpdate, useServerUpdate } from "@/lib/serverUpdate";
import { checkClient, useClientStatus } from "@/lib/clientUpdate";
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { RealmlistMenu } from "@/screens/RealmlistMenu";
import { RealmPicker } from "@/screens/RealmPicker";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
type Action = "starting" | "stopping" | "restarting" | null;
type Failure = { human: Human; technical: string };
/** World loop speed from the server's own timing report, with a simple smooth / busy / lagging verdict. */
function TickRate({ perf }: { perf: Performance }) {
const t = useT();
const level = perf.mean_ms <= 50 ? "good" : perf.mean_ms <= 100 ? "busy" : "lag";
const tone = { good: "text-ok bg-ok/15", busy: "text-warn bg-warn/15", lag: "text-bad bg-bad/15" }[level];
const bar = { good: "bg-ok", busy: "bg-warn", lag: "bg-bad" }[level];
const fill = Math.max(4, Math.min(100, Math.round(100 - perf.mean_ms)));
return (
{t("overview.tick")}
{t(level === "good" ? "overview.tickGood" : level === "busy" ? "overview.tickBusy" : "overview.tickLag")}
{Math.round(perf.ticks_per_sec)}
{t("overview.tickUnit")}
{t("overview.tickDetail", { mean: perf.mean_ms, p95: perf.p95_ms, max: perf.max_ms })}
);
}
function Row({ label, s }: { label: string; s: ServiceStatus }) {
const t = useT();
const running = s.state === "running";
const starting = s.state === "starting";
return (
{label}
{running ? t("status.running") : starting ? t("status.starting") : t("status.stopped")}
);
}
export function Overview({ server, companions = true, onForget, onOpenUpdates, onRealmChanged, onReport }: { server: ServerSummary; /** the companions module is on */ companions?: boolean; onForget: () => Promise; onOpenUpdates: () => void; onRealmChanged: () => void; /** open the problem report, which collects the diagnostics */ onReport: () => void }) {
const t = useT();
const human = useHuman();
const [status, setStatus] = useState(null);
// With both worlds started together, each realm gets its own card; the first realm owns the database and auth.
const [realms, setRealms] = useState<{ first: string; second: string } | null>(null);
const bothWorlds = !!status?.observed.secondary_world;
useEffect(() => {
if (!bothWorlds) { setRealms(null); return; }
let alive = true;
void api.realmProfiles(server.id).then((r) => {
if (!alive) return;
const name = (m: "coa" | "wildcard") => (m === "coa" ? "Conquest of Azeroth" : "Wildcard");
setRealms({ first: name(r.active), second: name(r.active === "coa" ? "wildcard" : "coa") });
}).catch(() => { if (alive) setRealms(null); });
return () => { alive = false; };
}, [bothWorlds, server.id]);
const [action, setAction] = useState(null);
const [realmBusy, setRealmBusy] = useState(false);
const [failure, setFailure] = useState(null);
const [showDetails, setShowDetails] = useState(false);
const [pop, setPop] = useState(null);
const [client, setClient] = useState(undefined);
const [dialog, setDialog] = useState(null);
const clientStatus = useClientStatus(server.id).status;
const [playing, setPlaying] = useState(false);
const job = useClientJob(server.id);
const jobBusy = job.phase === "scanning" || job.phase === "working";
const jobPct = job.step && job.step.total > 0 ? Math.min(100, Math.floor((job.step.done / job.step.total) * 100)) : 0;
const [keepMine, setKeepMine] = useState(true);
const [perf, setPerf] = useState(null);
const upd = useServerUpdate(server.id);
const needsDecision = (upd.preview?.conflicts.length ?? 0) > 0;
const [startBots, setStartBots] = useState(undefined);
useEffect(() => {
void api
.settings(server.id, "bots")
.then((v) => {
const on = v.settings.find((s) => s.key === "CoaBots.AutoLoginOnStartup");
const max = v.settings.find((s) => s.key === "CoaBots.AutoLogin.MaxCount");
setStartBots(on?.value === true && typeof max?.value === "number" ? max.value : null);
})
.catch(() => setStartBots(undefined));
}, [server.id]);
const alive = useRef(true);
useEffect(() => {
if (job.phase === "done" || job.phase === "current") void api.clientInfo(server.id).then(setClient).catch(() => undefined);
}, [job.phase, server.id]);
const poll = useCallback(async () => {
try {
const s = await api.status(server.id);
if (alive.current) setStatus(s);
if (s.observed.world.state === "running") {
const p = await api.population(server.id).catch(() => null);
if (alive.current) setPop(p);
} else if (alive.current) setPop(null);
} catch {
/* transient; next poll retries */
}
}, [server.id]);
// The tick rate comes from the server console (one short connection per reading), so it is read less often.
const worldUp = status?.observed.world.state === "running";
useEffect(() => {
if (!worldUp) {
setPerf(null);
return;
}
let live = true;
const read = () => void api.performance(server.id).then((p) => live && setPerf(p)).catch(() => {});
read();
const iv = setInterval(read, 10000);
return () => {
live = false;
clearInterval(iv);
};
}, [worldUp, server.id]);
useEffect(() => {
alive.current = true;
void api.clientInfo(server.id).then(setClient).catch(() => setClient(null));
void poll();
const t = setInterval(poll, 2000);
return () => {
alive.current = false;
clearInterval(t);
};
}, [poll]);
async function run(kind: Exclude) {
setFailure(null);
setShowDetails(false);
setAction(kind);
try {
if (kind !== "starting") {
const out = await api.stop(server.id);
if (!out.ok) throw { human: out.human, technical: out.output };
}
if (kind !== "stopping") {
setAction("starting");
const out = await api.start(server.id);
if (!out.ok) throw { human: out.human, technical: out.output };
}
} catch (e) {
const ui = asUiError(e);
setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical });
} finally {
setAction(null);
void poll();
}
}
async function play() {
setFailure(null);
setShowDetails(false);
setPlaying(true);
try {
const out = await api.play(server.id);
if (!out.ok) throw { human: out.human, technical: out.output };
} catch (e) {
const ui = asUiError(e);
setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical });
} finally {
setPlaying(false);
void poll();
}
}
if (!status) return {t("overview.checking")}
;
if (!status.path_exists) {
return (
{t("overview.missingTitle")}
{t("overview.missingText", { path: server.path })}
);
}
const { mysql, auth, world, secondary_world } = status.observed;
const all = [mysql, auth, world, ...(secondary_world ? [secondary_world] : [])];
const running = all.every((s) => s.state === "running");
const anyUp = all.some((s) => s.state !== "stopped");
const transitioning = action !== null || status.busy || realmBusy;
const conflict = all.find((s) => s.conflict)?.conflict ?? null;
const headline = realmBusy ? t("realm.switching") : transitioning
? action === "stopping"
? t("status.stopping")
: t("status.starting")
: running
? t("status.online")
: anyUp
? t("status.attention")
: t("status.offline");
const tone = transitioning ? "text-warn" : running ? "text-ok" : anyUp ? "text-warn" : "text-muted";
return (
{server.name}
{server.path}
{ onRealmChanged(); void poll(); }} />
{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}
{headline}
{!transitioning && !running && anyUp && (
{t("overview.reportHint")}{" "}
)}
- {t("overview.uptime")}
- {world.state === "running" ? formatUptime(world.uptime_secs) : "—"}
- {t("overview.players")}
- {pop ? `${pop.players_online}` : "—"}{companions && pop && pop.bots_online > 0 ? {t("overview.companions", { n: pop.bots_online })} : null}
{companions && startBots !== undefined && (
{startBots === null ? t("overview.startBotsOff") : t("overview.startBots", { n: startBots })}
)}
{perf && }
{running ? (
) : upd.available ? (
) : (
)}
{!running && upd.available && (
)}
{running && (
)}
{running && upd.available && (
)}
{anyUp && !running && (
)}
{client &&
}
{client && jobBusy ? (
{job.phase === "scanning" ? t("client.job.checking") : t("client.job.updating")}
{jobPct}%
{job.step && job.step.phase === "download" && job.step.bytes_per_sec > 0 ? ` · ${t("client.dl.speed", { speed: formatBytes(job.step.bytes_per_sec) })}` : ""}
) : client && (clientStatus?.update_available || job.phase === "choose") ? (
) : client ? (
) : client === null ? (
) : null}
{client && !jobBusy && (clientStatus?.update_available || job.phase === "choose") && (
)}
{anyUp && !running && !transitioning && (
{t("overview.partial")}
)}
{job.phase === "choose" && job.plan && (
{t("client.upd.modifiedTitle", { n: job.plan.items.filter((i) => i.kind === "modified").length })}
{t("client.upd.modifiedText")}
)}
{job.phase === "done" && {t("client.upd.done")}
}
{job.phase === "current" && {t("client.upd.upToDate", { v: job.plan?.version ?? "" })}
}
{job.phase === "stopped" && (
{t("client.dl.cancelled")}
)}
{job.phase === "failed" && job.error && (
{job.error.human.code === "unknown" ? job.error.technical : human(job.error.human).message}
)}
{upd.available && upd.preview && (
{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}
{needsDecision &&
{t("overview.updateConflicts")}
}
{upd.applying && (
{t("overview.updatingNote")}
{upd.step ?? ""}
{upd.percent}%
)}
)}
{secondary_world && (
{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}
{secondary_world.state === "running" ? t("status.online") : secondary_world.state === "starting" ? t("status.starting") : t("status.offline")}
- {t("overview.uptime")}
- {secondary_world.state === "running" ? formatUptime(secondary_world.uptime_secs) : "—"}
{t("realm.bothRunning")}
)}
{conflict && !anyUp && (
{t("overview.portTitle")}
{t("overview.portText", { port: conflict.port, exe: conflict.exe ? ` (${conflict.exe})` : "" })}
)}
{failure && (
{human(failure.human).title}
{human(failure.human).message}
{showDetails && (
{failure.technical || t("common.noOutput")}
)}
)}
{dialog && (
setDialog(null)}
onChanged={() => {
void api.clientInfo(server.id).then(setClient).catch(() => setClient(null));
void checkClient(server.id);
}}
onPlayAnyway={() => void play()}
/>
)}
);
}