import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Check, ChevronLeft, ChevronRight, Loader2, Send } from "lucide-react";
import { api } from "../lib/api";
import { setLanguage, type LangCode } from "../i18n";
import LanguageSwitcher from "./LanguageSwitcher";
// 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);
const [tokenError, setTokenError] = useState(false);
useEffect(() => {
if (!token) {
setTokenError(true);
return;
}
api.setupInfo(token).then(setInfo).catch(() => setTokenError(true));
}, [token]);
// Step state.
const [stepIdx, setStepIdx] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
// 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).
async function next() {
setError("");
setBusy(true);
try {
if (step === "admin") {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email))
throw { detail: t("setup.admin.invalidEmail") };
if (password.length < PASSWORD_MIN)
throw { detail: 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()) throw { detail: 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);
} catch (e: any) {
setError(e?.detail ?? t("setup.genericError"));
} finally {
setBusy(false);
}
}
async function sendTest() {
setTestState("sending");
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: Number(smtp.port) || 587,
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");
}
}
const inputCls =
"w-full bg-card border border-border rounded-xl px-3 py-2 text-sm outline-none focus:border-accent";
return (
{/* Step progress dots */}
{steps.map((s, i) => (
))}
{step === "intro" && (
)}
{step === "admin" && (
)}
{step === "google" && (
)}
{step === "smtp" && (
)}
{step === "finish" && (
)}
{error &&
{error}
}
);
}
function Centered({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
function Section({
title,
desc,
children,
}: {
title: string;
desc: string;
children?: React.ReactNode;
}) {
return (
);
}
function TokenError() {
const { t } = useTranslation();
return (
{t("setup.token.title")}
{t("setup.token.body")}
);
}