import { useEffect, useState } from "react"; import { Loader2, Bot, CheckCircle2, AlertCircle, RefreshCw, Power, Users, Database, } from "lucide-react"; import { api, asUiError, type Population, type RealmMode, type RealmProfiles, type UiError, type WildcardArchetypeDto, } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useHuman, useT } from "@/i18n"; function formatRole(roles: number): string { const parts: string[] = []; if (roles & 1) parts.push("Tank"); if (roles & 2) parts.push("Melee"); if (roles & 4) parts.push("Ranged"); if (roles & 8) parts.push("Healer"); return parts.join("/") || "DPS"; } function formatStat(stat: number): string { switch (stat) { case 0: return "Strength"; case 1: return "Agility"; case 2: return "Stamina"; case 3: return "Intellect"; case 4: return "Spirit"; default: return "All"; } } export function CompanionsCard({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); // Realm & Environment state const [profiles, setProfiles] = useState(null); const [selectedRealm, setSelectedRealm] = useState("coa"); const [pop, setPop] = useState(null); const [running, setRunning] = useState(false); // Fleet Configuration state const [spawnMode, setSpawnMode] = useState<"population" | "fleet">("population"); const [countChoice, setCountChoice] = useState("50"); const [customCount, setCustomCount] = useState("50"); const [targetLevel, setTargetLevel] = useState(80); const [selectedClass, setSelectedClass] = useState("all"); const [selectedRole, setSelectedRole] = useState("all"); const [selectedArchetype, setSelectedArchetype] = useState("all"); const [wildcardArchetypes, setWildcardArchetypes] = useState([]); // Operational state const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [note, setNote] = useState(null); const [job, setJob] = useState<{ baseline: number; target: number; since: number } | null>(null); // Startup Auto-Login settings const [autoOn, setAutoOn] = useState(true); const [autoMax, setAutoMax] = useState(""); const [startNote, setStartNote] = useState(null); const [startBusy, setStartBusy] = useState(false); const [despawnN, setDespawnN] = useState("10"); const activeServerRealm = profiles?.active ?? "coa"; const isViewingActiveRealm = selectedRealm === activeServerRealm; const isRealmOperational = isViewingActiveRealm || running; const maxLevelForRealm = 60; // Load realm profiles const loadProfiles = async () => { try { const r = await api.realmProfiles(serverId); setProfiles(r); if (!selectedRealm) { setSelectedRealm(r.active); } } catch { // ignore } }; useEffect(() => { void loadProfiles(); }, [serverId]); // Adjust target level if realm changed useEffect(() => { if (targetLevel > maxLevelForRealm) { setTargetLevel(maxLevelForRealm); } }, [selectedRealm, maxLevelForRealm, targetLevel]); // Load wildcard archetypes dynamically from target characters db useEffect(() => { if (selectedRealm === "wildcard") { api.getWildcardArchetypes(serverId) .then((archs) => setWildcardArchetypes(archs)) .catch(() => {}); if (selectedClass === "all") { setSelectedClass("10"); } } else { setSelectedArchetype("all"); } }, [serverId, selectedRealm]); // Load startup settings useEffect(() => { void api .settings(serverId, "bots") .then((v) => { const on = v.settings.find((s) => s.key === "CoaBots.AutoLoginOnStartup"); const max = v.settings.find((s) => s.key === "CoaBots.AutoLogin.MaxCount"); if (on) setAutoOn(on.value === true); if (max) setAutoMax(String(max.value)); }) .catch(() => {}); }, [serverId]); const maxNum = Number(autoMax); const maxValid = autoMax.trim() !== "" && Number.isInteger(maxNum) && maxNum >= 0 && maxNum <= 5000; // Polling population const fetchPopulation = async () => { const s = await api.status(serverId).catch(() => null); if (!s) return; const up = s.observed.world.state === "running"; setRunning(up); if (up) { const p = await api.population(serverId, selectedRealm).catch(() => null); setPop(p); } else { setPop(null); } }; useEffect(() => { let alive = true; const poll = async () => { if (!alive) return; await fetchPopulation(); }; void poll(); const interval = setInterval(poll, job ? 1500 : 4000); return () => { alive = false; clearInterval(interval); }; }, [serverId, selectedRealm, job !== null]); // eslint-disable-line react-hooks/exhaustive-deps const done = job && pop ? Math.max(0, Math.min(job.target, pop.bots_total - job.baseline)) : 0; useEffect(() => { if (!job) return; if ((pop && done >= job.target) || !running) { if (pop && done >= job.target) setNote(t("comp.progressDone", { n: job.target })); setJob(null); } }, [done, running]); // eslint-disable-line react-hooks/exhaustive-deps const count = countChoice === "custom" ? Number(customCount) : Number(countChoice); const valid = Number.isInteger(count) && count >= 1 && count <= 2000; async function act(fn: () => Promise) { setBusy(true); setError(null); try { setNote(await fn()); } catch (e) { setError(asUiError(e)); } finally { setBusy(false); } } // Primary action: Spawn bots / fleet const handleSpawn = async () => { if (!valid) return; setBusy(true); setError(null); setNote(null); try { if (spawnMode === "fleet") { const race = 1; const out = await api.spawnBotFleet(serverId, race, targetLevel, selectedRealm); setNote(out || `Spawned level ${targetLevel} fleet`); } else { const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : (selectedRealm === "wildcard" ? 10 : undefined); let specNum: number | undefined = undefined; if (selectedRole === "tank") { if (selectedRealm === "reborn") { specNum = (classNum === 7 || classNum === 9 || classNum === 11) ? 4 : (classNum === 2 ? 2 : classNum === 1 ? 3 : 1); } else if (selectedRealm === "wildcard") { specNum = 1; } } else if (selectedRole === "healer") { if (selectedRealm === "reborn") { specNum = (classNum === 2 || classNum === 5) ? 1 : (classNum === 7 || classNum === 11 ? 3 : 1); } else if (selectedRealm === "wildcard") { specNum = 2; } } const archStr = selectedArchetype !== "all" ? selectedArchetype : undefined; const r = await api.addCompanions(serverId, count, selectedRealm, targetLevel, classNum, specNum, archStr); if (r.spawned && r.baseline !== null) { setJob({ baseline: r.baseline, target: count, since: Date.now() }); } setNote( r.created ? t("comp.offlineDone", { n: r.created }) : r.spawned ? t("comp.spawned", { n: count }) : t("comp.saved", { n: count }) ); } await fetchPopulation(); } catch (e) { setError(asUiError(e)); } finally { setBusy(false); } }; // Bring offline bots online const handleLoginAll = () => act(async () => { const out = await api.loginAllCompanions(serverId, selectedRealm); await fetchPopulation(); return out || "All available offline bots queued for login."; }); // Stop queued creations const stopCreating = () => act(async () => { const r = await api.stopSpawning(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.stopped", { n: r.count }); }); // Take online bots offline const takeOffline = () => { if (!window.confirm(t("comp.offlineConfirm"))) return; void act(async () => { const r = await api.takeOffline(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.offlineDone2", { n: r.count }); }); }; // Despawn batch const dn = Number(despawnN); const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000; const despawnSome = () => act(async () => { const r = await api.despawnSome(serverId, dn, selectedRealm); await fetchPopulation(); return t("comp.despawnSomeDone", { n: r.count }); }); // Delete all bots in realm const deleteAll = () => { if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return; void act(async () => { await api.deleteAllCompanions(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.deleteDone"); }); }; // Switch server realm const switchServerRealm = async (mode: RealmMode) => { if (!window.confirm(`Switch server active realm to ${mode.toUpperCase()} and restart?`)) return; setBusy(true); try { await api.realmSelect(serverId, mode, true); await loadProfiles(); setSelectedRealm(mode); } catch (e) { setError(asUiError(e)); } finally { setBusy(false); } }; // Save auto startup settings async function saveStart() { setStartBusy(true); setError(null); setStartNote(null); try { await api.save(serverId, "bots", { "CoaBots.AutoLoginOnStartup": autoOn, "CoaBots.AutoLogin.MaxCount": maxNum, }); setStartNote(t("comp.startSaved")); } catch (e) { setError(asUiError(e)); } finally { setStartBusy(false); } } // Database schema name for selected realm const dbSchema = selectedRealm === "coa" ? "acore_characters" : selectedRealm === "wildcard" ? "acore_characters_wildcard" : "acore_characters_reborn"; // Binary compatibility check const isBinaryCompatible = selectedRealm === "coa" || (selectedRealm === "wildcard" && (profiles?.supported ?? true)) || (selectedRealm === "reborn" && (profiles?.reborn_supported ?? true)); return ( {/* Header & Realm Switcher */}

{t("comp.title")}

DB: {dbSchema}
{/* Realm Navigation Tabs */}
{(["coa", "wildcard", "reborn"] as RealmMode[]).map((mode) => { const isSelected = selectedRealm === mode; const isActive = activeServerRealm === mode; const label = mode === "coa" ? "Conquest of Azeroth" : mode === "wildcard" ? "Wildcard (Hero)" : "Warcraft Reborn"; return ( ); })}
{/* Binary Compatibility & Realm Mode Warning */} {!isBinaryCompatible && (
Binary Compatibility Warning

The currently running server core binary does not have full multi-realm support enabled for {selectedRealm.toUpperCase()}. Automated bot features may be restricted.

)} {/* Active Realm Switch Helper */} {!isViewingActiveRealm && (
Viewing {selectedRealm.toUpperCase()} bots, but the worldserver is currently running in{" "} {activeServerRealm.toUpperCase()} mode.
)} {/* Realm Population Dashboard */}
Bots Online
{running && pop ? pop.bots_online : "—"}
Total Fleet
{pop ? pop.bots_total : "—"}
Players Online
{running && pop ? pop.players_online : "—"}
Status
{running ? ( Running ) : ( Offline )}
{/* Fleet Configuration & Spawning Section */}

Fleet Deployment Controls

{/* Count Selector */} {spawnMode === "population" && (
{["10", "25", "50", "100", "250", "500"].map((n) => ( ))} {countChoice === "custom" && ( setCustomCount(e.target.value)} className="w-24 rounded-md border border-line bg-bg px-3 py-1.5 text-right text-sm outline-none focus:border-gold" /> )}
)} {/* Fleet Specific Settings: Level, Class, Role, Archetype */}
{/* Target Level */}
setTargetLevel(Math.max(1, Math.min(maxLevelForRealm, Number(e.target.value))))} className="mt-1.5 w-full rounded-md border border-line bg-bg px-3 py-1.5 text-sm outline-none focus:border-gold" />
{/* Class Filter */}
{/* Role Filter */}
{/* Archetype Filter */}
{/* Deployment Actions */}
{running && pop && pop.bots_total > pop.bots_online && ( )} {!running && ( Server stopped: bots will be created directly in DB or queued for startup. )}
{/* Progress Bar during active spawn */} {job && (
Creating bots: {done} / {job.target} {Math.round((done / job.target) * 100)}%
Paced creation prevents server stalls and guarantees full talent/gear setup.
)} {note && !job && (

{note}

)}
{/* Online Fleet Management (Despawn, Purge) */} {running && pop && pop.bots_total > 0 && isViewingActiveRealm && (

Online Fleet Management

setDespawnN(e.target.value)} inputMode="numeric" aria-invalid={!dnValid} className="w-20 rounded-md border border-line bg-bg px-2.5 py-1 text-right text-sm outline-none focus:border-gold" />
)} {/* Startup Auto-Login Configuration */}

Persistent Startup Fleet

Configure how many bots automatically log into the world whenever the server launches.

setAutoMax(e.target.value)} inputMode="numeric" disabled={!autoOn} aria-invalid={!maxValid} className="w-24 rounded-md border border-line bg-bg px-2.5 py-1 text-right text-sm outline-none focus:border-gold disabled:opacity-40" />
{startNote &&

{startNote}

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