import { useCallback, useEffect, useState } from "react"; import { Check, Loader2, Minus } from "lucide-react"; import { api, asUiError, type FriendsMode, type FriendsStatus, type InternetCheck, type UiError } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useHuman, useT, type Key } from "@/i18n"; /** Convenience only; Rust validates again before applying or saving. */ function validLanIpv4(value: string): boolean { if (!/^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){3}$/.test(value)) return false; const octets = value.split(".").map(Number); const [a, b] = octets; return octets.every((n) => n <= 255) && a > 0 && a < 224 && a !== 127 && !(a === 169 && b === 254) && !(a === 100 && b >= 64 && b <= 127); } function Line({ ok, children, warn }: { ok: boolean; warn?: boolean; children: React.ReactNode }) { const t = useT(); return (
  • {ok ? : } {children} {ok ? t("fr.ok") : t("fr.notYet")}
  • ); } const MODES: { id: FriendsMode; title: Key; text: Key }[] = [ { id: "lan", title: "fr.mode.lan.title", text: "fr.mode.lan.text" }, { id: "direct", title: "fr.mode.direct.title", text: "fr.mode.direct.text" }, { id: "private", title: "fr.mode.private.title", text: "fr.mode.private.text" }, ]; /** A link to one of the few help pages the Manager may open; it goes through the backend, which checks the address. */ function ExtLink({ url, children }: { url: string; children: React.ReactNode }) { return ( ); } /** Collapsible step-by-step help inside a mode card. */ function Guide({ steps, links }: { steps: string[]; links?: React.ReactNode }) { const t = useT(); return (
    {t("fr.guide")}
      {steps.map((s, i) => (
    1. {s}
    2. ))}
    {links &&
    {links}
    }
    ); } /** A ready-to-paste realmlist line for the friend, shown as soon as the address is known. */ function RealmlistLine({ host }: { host: string }) { const t = useT(); const [copied, setCopied] = useState(false); const line = `set realmlist ${host}`; return (
    {line}
    ); } export function FriendsPage({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); const [st, setSt] = useState(null); const [net, setNet] = useState(null); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); const [note, setNote] = useState(null); const [copied, setCopied] = useState(false); const [needsRestart, setNeedsRestart] = useState(false); const [lanChoice, setLanChoice] = useState("automatic"); const [customLan, setCustomLan] = useState(""); const refresh = useCallback(() => api.friendsStatus(serverId).then((status) => { setSt(status); }).catch((e) => setError(asUiError(e))), [serverId]); useEffect(() => { let cancelled = false; setSt(null); setNet(null); void api.friendsStatus(serverId).then((status) => { if (cancelled) return; const saved = status.settings.lan_address_override; setCustomLan(saved ?? ""); setLanChoice(saved === null ? "automatic" : status.lan_addresses.some((a) => a.address === saved) ? saved : "custom"); setSt(status); }).catch((e) => { if (!cancelled) setError(asUiError(e)); }); return () => { cancelled = true; }; }, [serverId]); const lanOverride = lanChoice === "automatic" ? null : lanChoice === "custom" ? customLan.trim() : lanChoice; const lanValid = lanOverride === null || validLanIpv4(lanOverride); async function run(label: string, fn: () => Promise) { setBusy(label); setError(null); setNote(null); try { const msg = await fn(); if (msg) setNote(msg); await refresh(); } catch (e) { setError(asUiError(e)); } finally { setBusy(null); } } const check = () => run("check", async () => { setNet(await api.friendsCheckInternet()); }); const enable = (mode: FriendsMode) => run(`enable-${mode}`, async () => { const r = await api.friendsEnable( serverId, mode, mode === "direct" ? net?.public_ip ?? undefined : undefined, mode === "direct" && !!net?.router_found, mode === "lan" ? lanOverride : null, ); setNeedsRestart(r.restart_required); return [r.restart_required ? t("fr.restartToApply") : null, r.note ? (r.note.startsWith("Your router was asked") ? t("fr.note.forwarded") : r.note.startsWith("Your router does not support") ? t("fr.note.manual") : r.note) : null].filter(Boolean).join(" ") || t("fr.ready"); }); if (!st) return

    {error ? human(error.human).message : t("fr.looking")}

    ; const cur = st.settings; const exposed = st.exposure.filter((e) => (e.what === "database" || e.what === "server console") && e.reachable_from_network); const connection = cur.mode === "local" ? null : `set realmlist ${cur.host}`; const selectedLan = lanOverride ?? st.lan_ip; const lanUnavailable = lanOverride !== null && lanValid && !st.lan_addresses.some((a) => a.address === lanOverride); return (

    {t("fr.title")}

    {t("q.friends")}

    {exposed.length > 0 && (

    {t("fr.exposedTitle")}

    {t("fr.exposedText", { what: exposed.map((e) => t(e.what === "database" ? "fr.what.database" : "fr.what.console")).join(t("fr.and")) })}

    )}

    {t("fr.status")}

      {t("fr.st.running")} {t("fr.st.open")} {st.firewall && {t("fr.st.firewall")}} e.what === "database" || e.what === "server console").every((e) => !e.reachable_from_network)}> {t("fr.st.private")}
    {st.secondary_world_port &&

    {t("realm.secondPort", { port: st.secondary_world_port })}

    }
    {MODES.map((m) => (

    {t(m.title)} {cur.mode === m.id && {t("fr.inUse")}}

    {t(m.text)}

    {m.id === "lan" && ( <> {lanChoice === "custom" && <> setCustomLan(e.target.value)} /> } {!lanValid && } {lanUnavailable &&

    {t("fr.lan.unavailable")} {t("fr.lan.unavailableText")}

    } {selectedLan && lanValid && } )} {m.id === "direct" && (
    {net && net.reachability === "cgnat" && (

    {t("fr.cgnat")}

    )} {net?.public_ip && net.reachability !== "cgnat" && (

    {t("fr.publicAddr")} {net.public_ip}{!net.router_found && {t("fr.noRouter")}}

    )} {net?.public_ip && net.reachability !== "cgnat" && cur.mode !== m.id && } {t("fr.g.routerHelp")}} /> {net && !net.public_ip &&

    {t("fr.noInternet")}

    }
    )} {m.id === "private" && (

    {!st.tailscale.installed && {t("fr.tsMissing")}} {st.tailscale.installed && !st.tailscale.connected && {t("fr.tsOff")}} {st.tailscale.connected && <>{t("fr.privateAddr")} {st.tailscale.ip}}

    )} {m.id === "private" && !st.tailscale.installed && (
    {t("fr.tsDownload")}
    )} {m.id === "private" && st.tailscale.connected && st.tailscale.ip && cur.mode !== m.id && } {m.id === "private" && ( {t("fr.tsDownload")} {t("fr.g.ts.admin")} {t("fr.g.ts.share")} } /> )}
    ))} {cur.mode !== "local" && ( )}
    {connection && (

    {t("fr.giveTitle")}

    {t("fr.giveText")}

    {connection}
    )} {note &&

    {note}

    } {needsRestart && st.server_running && ( )} {error &&

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

    }
    ); }