import { useEffect, useState } from "react"; import { Loader2 } from "lucide-react"; import { api, asUiError, type CompanionSizes, type Population, type UiError } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useHuman, useT } from "@/i18n"; export function CompanionsCard({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); const [sizes, setSizes] = useState(null); const [pop, setPop] = useState(null); const [running, setRunning] = useState(false); const [choice, setChoice] = useState("small"); const [custom, setCustom] = useState("100"); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [note, setNote] = useState(null); useEffect(() => { void api.companionSizes().then(setSizes); let alive = true; const poll = async () => { const s = await api.status(serverId).catch(() => null); if (!alive || !s) return; const up = s.observed.world.state === "running"; setRunning(up); setPop(up ? await api.population(serverId).catch(() => null) : null); }; void poll(); const t = setInterval(poll, 4000); return () => { alive = false; clearInterval(t); }; }, [serverId]); const count = choice === "custom" ? Number(custom) : (sizes?.sizes.find((s) => s.id === choice)?.bots ?? 0); const warning = choice === "custom" ? (count > 500 ? t("comp.largeWarning") : null) : (sizes?.sizes.find((s) => s.id === choice)?.warning ?? null); const valid = Number.isInteger(count) && count >= 1 && count <= 2000; async function add() { setBusy(true); setError(null); setNote(null); try { const r = await api.addCompanions(serverId, count); setNote(r.spawned ? t("comp.spawned", { n: count }) : t("comp.saved", { n: count })); } catch (e) { setError(asUiError(e)); } finally { setBusy(false); } } return (

{t("comp.title")}

{pop ? t("comp.population", { online: pop.bots_online, total: pop.bots_total }) : running ? t("comp.reading") : t("comp.startToSee")}

{t("comp.wantMore")}
{sizes?.sizes.map((s) => ( ))} {choice === "custom" && ( setCustom(e.target.value)} inputMode="numeric" className="w-24 rounded-md border border-line bg-bg px-3 py-2 text-right text-sm outline-none focus:border-gold" /> )}
{warning &&

{warning}

} {sizes &&

{t("comp.hardware", { cores: sizes.hardware.cores, ram: sizes.hardware.ram_gb.toFixed(0) })}

}
{!running && {t("comp.stoppedHint")}}
{note &&

{note}

} {error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

}
); }