import { useEffect, useMemo, useState } from "react"; import { open } from "@tauri-apps/plugin-dialog"; import { AlertTriangle, CheckCircle2, History, Loader2, Plus, ShieldAlert, Swords, Trash2, X } from "lucide-react"; import { useT, type Key } from "@/i18n"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { RulesetBadge } from "@/components/RulesetBadge"; import type { Ruleset } from "@/lib/browse"; import { cn } from "@/lib/utils"; import { asPortableError, portable, usePortable, type CharacterView, type HistoryEntry, type LocalCharacterView, type Note, type PlayStatus, type PlayView, type PortableError, type PreflightView, type RealmView, } from "@/lib/portable"; const WORKING: PlayStatus[] = ["preparing", "syncing", "saving"]; const LIVE: PlayStatus[] = ["playing", "waiting_login", "preparing", "syncing", "saving"]; function when(iso: string): string { const d = new Date(iso); return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(); } function StatusChip({ status, degraded }: { status: PlayStatus; degraded?: boolean }) { const t = useT(); const tone = status === "playing" ? "bg-ok/15 text-ok" : status === "conflict" || status === "incompatible" || status === "error" ? "bg-bad/15 text-bad" : status === "update_required" || status === "compat_warning" || status === "offline" ? "bg-warn/15 text-warn" : WORKING.includes(status) || status === "waiting_login" ? "bg-gold/15 text-gold" : "bg-white/5 text-muted"; return {WORKING.includes(status) && } {t(`portable.status.${status}` as Key)} {degraded && {t("portable.status.compat_warning")}} ; } /** The words of one line of the compatibility check. */ function noteText(t: ReturnType, n: Note): string { const key = `portable.note.${n.code}` as Key; const text = t(key, { ...n.params }); return text === key ? t("portable.note.generic", { detail: n.detail }) : text; } export function Notes({ notes }: { notes: Note[] }) { const t = useT(); const shown = notes.filter((n) => n.code !== "projection"); if (!shown.length) return null; return ; } export function Projection({ from, to, cap }: { from: number; to: number; cap?: number | null }) { const t = useT(); return

{t("portable.projection.title", { cap: cap ?? to })}

{t("portable.projection.text", { from, to })}

{t("portable.projection.safe", { from })}

; } function ErrorLine({ error }: { error: PortableError }) { const t = useT(); const key = `portable.err.${error.code}` as Key; const text = t(key); return

{text === key ? t("portable.err.other") : text}

{t("portable.details")}

{error.message}

; } // ---- Play -------------------------------------------------------------------------------------------------------------------- function PlayDialog({ character, realms, initial, onClose, onChanged }: { character: CharacterView; realms: RealmView[]; initial: string; onClose: () => void; onChanged: () => void }) { const t = useT(); const [realmId, setRealmId] = useState(initial); const realm = realms.find((r) => r.id === realmId)!; const [pre, setPre] = useState(null); const [account, setAccount] = useState(realm.game_account ?? ""); const [busy, setBusy] = useState(false); const [done, setDone] = useState(null); const [error, setError] = useState(null); const [launching, setLaunching] = useState(false); useEffect(() => { let alive = true; setPre(null); setError(null); setDone(null); setAccount(realm.game_account ?? ""); void portable.preflight(character.id, realmId).then((p) => { if (alive) setPre(p); }).catch((e) => { if (alive) setError(asPortableError(e)); }); return () => { alive = false; }; }, [character.id, realmId]); // eslint-disable-line react-hooks/exhaustive-deps async function play() { setBusy(true); setError(null); try { setDone(await portable.play(character.id, realmId, account.trim() || undefined)); onChanged(); } catch (e) { setError(asPortableError(e)); } finally { setBusy(false); } } async function launch() { setLaunching(true); setError(null); try { await portable.launch(realmId); } catch (e) { setError(asPortableError(e)); } finally { setLaunching(false); } } async function resolve(action: "use_canonical" | "detach") { setBusy(true); setError(null); try { await portable.resolve(character.id, realmId, action); onChanged(); setPre(await portable.preflight(character.id, realmId)); } catch (e) { setError(asPortableError(e)); } finally { setBusy(false); } } const blocked = !pre || pre.step === "blocked" || pre.step === "offline" || pre.step === "resolve" || busy; return

{t("portable.play.title", { name: character.name })}

{!pre && !error &&

{t("portable.play.checking")}

} {pre && !done && <>

{pre.verdict === "compatible" ? : } {t(`portable.verdict.${pre.verdict}` as Key)}

{pre.projection && } {pre.verdict === "degraded" &&

{t("portable.degraded.text")}

}

{t(`portable.step.${pre.step}` as Key)}

{pre.step === "resolve" &&
} {pre.step === "resolve" &&

{t("portable.resolve.help")}

} {(pre.needs_account || realm.game_account === null) && pre.step === "prepare" &&

{t("portable.play.accountHint")}

setAccount(e.target.value)} disabled={busy} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" autoComplete="off" />
} } {done &&

{t("portable.play.ready")}

{done.projection && }

{t("portable.play.next", { address: done.realm_address })}

} {error && }
{!done && } {done && }
; } // ---- Make portable ------------------------------------------------------------------------------------------------------------ function MakeDialog({ realms, onClose, onChanged }: { realms: RealmView[]; onClose: () => void; onChanged: () => void }) { const t = useT(); const usable = realms.filter((r) => r.database_ok); const [realmId, setRealmId] = useState(usable[0]?.id ?? ""); const [list, setList] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(null); const [made, setMade] = useState(null); useEffect(() => { if (!realmId) return; let alive = true; setList(null); setError(null); void portable.localCharacters(realmId).then((l) => { if (alive) setList(l); }).catch((e) => { if (alive) setError(asPortableError(e)); }); return () => { alive = false; }; }, [realmId]); async function make(c: LocalCharacterView) { setBusy(c.token); setError(null); try { const v = await portable.make(realmId, c.token); setMade(v.name); onChanged(); setList((l) => l?.filter((x) => x.token !== c.token) ?? null); } catch (e) { setError(asPortableError(e)); } finally { setBusy(null); } } return

{t("portable.make.title")}

{t("portable.make.text")}

{usable.length === 0 ?

{t("portable.make.noRealm")}

: <> {!list && !error &&

{t("portable.make.loading")}

} {list && list.length === 0 &&

{t("portable.make.none")}

} {list && list.length > 0 &&
    {list.map((c) =>
  • {c.name}

    {c.class_name} · {t("portable.level", { level: c.level })}{c.account ? ` · ${c.account}` : ""}

    {!c.eligible &&

    {c.reasons.map((r) => t(`portable.blocker.${r}` as Key)).join(", ")}

    }
  • )}
} } {made &&

{t("portable.make.done", { name: made })}

} {error && }
; } // ---- History ------------------------------------------------------------------------------------------------------------------ function HistoryDialog({ character, onClose }: { character: CharacterView; onClose: () => void }) { const t = useT(); const [list, setList] = useState(null); const [error, setError] = useState(null); useEffect(() => { void portable.history(character.id).then(setList).catch((e) => setError(asPortableError(e))); }, [character.id]); return

{t("portable.history.title", { name: character.name })}

{!list && !error && } {list &&
    {list.map((h) =>
  • #{h.revision}{when(h.at)} · {t(`portable.history.${h.kind}` as Key, { realm: h.source_realm })}
  • )}
} {error && }
; } // ---- the page ---------------------------------------------------------------------------------------------------------------- export function PortablePage({ onOpenSettings }: { onOpenSettings?: () => void }) { const t = useT(); const { state, refresh } = usePortable(); const [playing, setPlaying] = useState<{ character: CharacterView; realm: string } | null>(null); const [history, setHistory] = useState(null); const [making, setMaking] = useState(false); const [error, setError] = useState(null); const [copied, setCopied] = useState(false); const [rulesetFilter, setRulesetFilter] = useState<"" | Ruleset>(""); const realms = state?.realms ?? []; const characters = state?.characters ?? []; const filteredCharacters = useMemo(() => { if (!rulesetFilter) return characters; return characters.filter((c) => c.ruleset === rulesetFilter); }, [characters, rulesetFilter]); const usable = useMemo(() => realms, [realms]); async function addRealm() { setError(null); try { const file = await open({ multiple: false, filters: [{ name: t("portable.realm.fileType"), extensions: ["json"] }] }); if (typeof file === "string") { await portable.addRealm(file); await refresh(); } } catch (e) { setError(asPortableError(e)); } } async function removeRealm(id: string) { setError(null); try { await portable.removeRealm(id); await refresh(); } catch (e) { setError(asPortableError(e)); } } async function copyDiagnostics() { try { const json = JSON.stringify(await portable.diagnostics(), null, 2); await navigator.clipboard.writeText(json); setCopied(true); setTimeout(() => setCopied(false), 2500); } catch (e) { setError(asPortableError(e)); } } return

{t("portable.title")}

{t("portable.intro")}

{t("portable.experimental")}

{state && !state.runtime.running &&

{t("portable.runtime.stopped")}

} {error && }

{t("portable.realms.title")}

{usable.length === 0 &&

{t("portable.realms.none")}

} {usable.map((r) =>

{r.name}

{t(r.online ? "portable.realm.online" : r.database_ok ? "portable.realm.stopped" : "portable.realm.unreachable")} {r.level_cap ? ` · ${t("portable.realm.cap", { cap: r.level_cap })}` : ""} {r.portable === "setup" ? ` · ${t("portable.realm.setup")}` : ""} {` · ${t(r.kind === "installed" ? "portable.realm.installed" : "portable.realm.prepared")}`}

{r.kind === "prepared" && }
)}

{t("portable.characters.title")}

{characters.length === 0 && {t("portable.characters.none")}} {characters.length > 0 && filteredCharacters.length === 0 && ( {t("portable.filter.none")} )}
{filteredCharacters.map((c) =>

{c.name}

{c.class_name} · {t("portable.level", { level: c.level })} · {t("portable.revision", { n: c.revision })}

{t("portable.lastSync", { when: when(c.updated_at) })}{c.active_realm ? ` · ${t("portable.activeOn", { realm: c.active_realm })}` : ""}

{c.copies.length > 0 &&
    {c.copies.map((x) =>
  • {x.realm_name} {x.projected_level && {t("portable.copy.projected", { level: x.projected_level })}} {t("portable.copy.synced", { n: x.synced_revision })}
  • )}
}
)}

{t("portable.diag.title")}

{t("portable.diag.text")}

{state && state.runtime.errors.length > 0 &&
    {state.runtime.errors.slice(-5).map((e, i) =>
  • {when(e.at)} · {e.message}
  • )}
}
{copied && {t("portable.diag.copied")}}
{playing && setPlaying(null)} onChanged={() => void refresh()} />} {making && setMaking(false)} onChanged={() => void refresh()} />} {history && setHistory(null)} />} {onOpenSettings && null}
; }