import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Check, ChevronLeft, ChevronRight, Loader2, Send } from "lucide-react";
import { api, HttpError } from "../lib/api";
import { setLanguage, type LangCode } from "../i18n";
import LanguageSwitcher from "./LanguageSwitcher";
import { Button } from "./ui/Button";
import { Input } from "./ui/Input";
import { SURFACE } from "./ui/surfaces";
// First-run install wizard. Shown by App.tsx while the instance is unconfigured. The one-time
// setup token comes from the URL the app printed to the container logs (?token=…); every step
// posts it back as the X-Setup-Token header. On finish the instance flips to configured, the
// wizard disappears, and the operator signs in with the admin account they just created.
type StepId = "intro" | "admin" | "google" | "smtp" | "finish";
const PASSWORD_MIN = 10;
export default function SetupWizard() {
const { t, i18n } = useTranslation();
const [token] = useState(() => new URLSearchParams(window.location.search).get("token") ?? "");
const [info, setInfo] = useState<{ secrets_manageable: boolean } | null>(null);
// "No token at all" is not a fetch outcome, it is a fact about the URL — so it is derived rather
// than pushed into state by an effect, which had to run and commit before the error could show.
const [infoFailed, setInfoFailed] = useState(false);
const tokenError = !token || infoFailed;
useEffect(() => {
if (!token) return;
api
.setupInfo(token)
.then(setInfo)
.catch(() => setInfoFailed(true));
}, [token]);
// Step state.
const [stepIdx, setStepIdx] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
// Keys the error: failing the same way twice is a new node, so a screen reader announces it again (a clear
// and a set in one handler commit together, leaving the node untouched).
const [attempt, setAttempt] = useState(0);
// Admin account.
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
// Google OAuth (optional).
const [gid, setGid] = useState("");
const [gsecret, setGsecret] = useState("");
// SMTP (optional).
const [smtp, setSmtp] = useState({ host: "", port: "587", user: "", from: "", password: "" });
const [testTo, setTestTo] = useState("");
const [testState, setTestState] = useState<"idle" | "sending" | "ok" | "fail">("idle");
if (tokenError)
return (
);
if (!info)
return (
);
// Steps adapt to the instance: Google + SMTP need encrypted secret storage (TOKEN_ENCRYPTION_KEY).
const steps: StepId[] = [
"intro",
"admin",
...(info.secrets_manageable ? (["google", "smtp"] as StepId[]) : []),
"finish",
];
const step = steps[stepIdx];
const go = (delta: number) => {
setError("");
setStepIdx((i) => Math.min(steps.length - 1, Math.max(0, i + delta)));
};
// Each step's "Next" action persists what it collected, then advances. Optional steps with empty
// fields just advance (skip). Errors surface inline (the setup calls use the quiet flag); a step's own
// validation sets its message and stays.
async function next() {
setAttempt((n) => n + 1);
setError("");
setBusy(true);
try {
await saveStep();
} catch (e) {
setError((e instanceof HttpError ? e.detail : undefined) ?? t("setup.genericError"));
}
setBusy(false);
}
// next()'s steps, apart so `busy` clears on every way out without a try/finally (the React
// Compiler cannot lower one yet, and skips the whole component).
async function saveStep() {
if (step === "admin") {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return setError(t("setup.admin.invalidEmail"));
if (password.length < PASSWORD_MIN)
return setError(t("setup.admin.shortPassword", { n: PASSWORD_MIN }));
await api.setupAdmin(token, email, password);
} else if (step === "google" && (gid.trim() || gsecret.trim())) {
if (!gid.trim() || !gsecret.trim()) return setError(t("setup.google.bothRequired"));
await api.setupConfig(token, {
google_client_id: gid.trim(),
google_client_secret: gsecret.trim(),
});
} else if (step === "smtp" && smtp.host.trim()) {
await api.setupConfig(token, {
smtp_host: smtp.host.trim(),
smtp_port: Number(smtp.port) || 587,
smtp_user: smtp.user.trim(),
smtp_from: smtp.from.trim(),
smtp_password: smtp.password,
});
} else if (step === "finish") {
await api.setupFinish(token);
window.location.href = "/"; // configured now → reloads into the login page
return;
}
go(1);
}
async function sendTest() {
setTestState("sending");
const port = Number(smtp.port) || 587;
try {
// Persist the SMTP fields first so the test uses them, then send.
if (smtp.host.trim())
await api.setupConfig(token, {
smtp_host: smtp.host.trim(),
smtp_port: port,
smtp_user: smtp.user.trim(),
smtp_from: smtp.from.trim(),
smtp_password: smtp.password,
});
await api.setupTestEmail(token, testTo.trim());
setTestState("ok");
} catch {
setTestState("fail");
}
}
return (