import { useEffect, useRef, useState } from "react";
import { Form, useActionData, useNavigation, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import { formatDate } from "~/locale/format";
import { QRCodeSVG } from "qrcode.react";
import {
FeatherArrowLeft,
FeatherArrowRight,
FeatherCheckCircle,
FeatherKey,
FeatherPlus,
FeatherShieldAlert,
FeatherShieldCheck,
FeatherShieldOff,
FeatherSmartphone,
FeatherTrash2,
FeatherUpload,
FeatherX,
} from "@subframe/core";
import { Alert } from "~/ui/components/Alert";
import { Avatar } from "~/ui/components/Avatar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { CopyToClipboardButton } from "~/ui/components/CopyToClipboardButton";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { InputOtp } from "~/ui/components/InputOtp";
import { Progress } from "~/ui/components/Progress";
import { Select } from "~/ui/components/Select";
import { TextInput } from "~/ui/components/TextInput";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { useRootData } from "~/utils/data/useRootData";
import AvatarCropDialog from "./AvatarCropDialog";
// D-P2 — Settings > Profil nach Davids Subframe-"My Profile"-Design: Profil-Card (Avatar + Name inline-edit +
// E-Mail read-only) + Sicherheits-Card (Passwort ändern -> Modal, 2FA -> Verwalten/Setup/Disable-Modal). Praesentational,
// an die bestehende profile-Action verdrahtet (action=profile / password / startTotpEnrollment /
// confirmTotpEnrollment / disableTotpEnrollment). QR via qrcode.react. Position/Abteilung/Telefon sind in Davids
// Mock enthalten, haben aber kein Backing-Feld -> bewusst weggelassen (CR), statt Mock-Daten zu erfinden.
//
// WF-P2 ("2FA verwalten") — Davids Subframe-Screens token-genau uebernommen:
// M01 "2FA verwalten" -> step "manage" (Verwaltungs-Dialog: Methoden-Liste + Deaktivieren-Banner + Geraet hinzufuegen)
// M02 "Geraet/Token hinzufuegen" -> step "qr" (QR + manueller Schluessel + OTP-Bestaetigung in einer Card)
// M03 "2FA deaktivieren" -> step "disable" (Davids Warn-Card; Bestaetigung per Passwort, s. FLAG unten)
// Backend-Luecken (NICHT erfunden, geflaggt, statt Mock-Daten zu zeigen):
// - M01 Methoden-Liste: nur "Authenticator-App" ist backend-gedeckt. Sicherheitsschluessel (WebAuthn),
// Geraete-Metadaten/"Dieses Geraet"-Badge sowie der Wiederherstellungscodes-Eintrag mit "Neu erstellen"
// (Regenerate) haben kein Backing -> weggelassen.
// - M03: Davids Mock bestaetigt mit dem aktuellen 2FA-Code (OTP). Das bestehende disableTotpEnrollment
// verifiziert das PASSWORT -> Bestaetigung bleibt Passwort-basiert, Texte entsprechend angepasst.
type ProfileUser = { email: string; firstName?: string | null; lastName?: string | null; avatar?: string | null; phone?: string | null };
type MfaStatus = { enabled?: boolean; pending?: boolean; enabledAt?: string | Date | null } | null;
function passwordStrength(pw: string): number {
if (!pw) return 0;
const checks = [pw.length >= 8, /[A-Z]/.test(pw), /[a-z]/.test(pw), /\d/.test(pw), /[^A-Za-z0-9]/.test(pw)];
return Math.round((checks.filter(Boolean).length / checks.length) * 100);
}
function initials(user: ProfileUser): string {
const a = (user.firstName ?? "").trim();
const b = (user.lastName ?? "").trim();
return `${a.charAt(0)}${b.charAt(0)}`.toUpperCase() || user.email.charAt(0).toUpperCase();
}
function userDisplayName(user: ProfileUser): string {
return [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email;
}
// Lokale, token-gleiche Nachbauten von Davids Subframe-"Settings Page"-Slots (NeutralCard/SettingRow/Divider) —
// die SettingsPage/DefaultPageLayoutWithInnerSidebar sind reine Subframe-Library-Komponenten (nicht im Repo);
// hier 1:1 als Markup nachgebaut, OHNE die Settings-Shell/Navigation umzubauen.
function NeutralCard({ children }: { children: React.ReactNode }) {
return (
);
}
function CardDivider() {
return ;
}
function SettingRow({ label, helpText, children }: { label: React.ReactNode; helpText?: React.ReactNode; children: React.ReactNode }) {
return (
{label}
{helpText ? (
{helpText}
) : null}
{children}
);
}
function StatusPill({ tone = "positive", children }: { tone?: "positive" | "neutral"; children: React.ReactNode }) {
return (
{children}
);
}
export default function MyProfileScreen({
user,
mfaStatus,
otpauthUri,
recoveryCodes,
mfaError,
role,
}: {
user: ProfileUser;
mfaStatus: MfaStatus;
otpauthUri?: string;
recoveryCodes?: string[];
mfaError?: string;
role?: TenantUserType | null;
}) {
const { t } = useTranslation();
const { csrf = "" } = useRootData();
const navigation = useNavigation();
const actionData = useActionData<{
success?: string;
passwordSuccess?: string;
error?: string;
// WF-P2 Change Password / V01: Lockout-Signal. FLAG: kein Rate-Limit-/Lockout-Backend fuer den
// Passwortwechsel -> action=password setzt diese Felder (noch) nicht; UI ist vorbereitet (CR).
passwordLocked?: boolean;
passwordLockedRetryLabel?: string;
}>();
const submit = useSubmit();
const submitting = navigation.state !== "idle";
const saved = actionData?.success ?? actionData?.passwordSuccess;
const [pwOpen, setPwOpen] = useState(false);
// 2FA-Modal: null | "manage" (M01) | "password" (Setup-Gate, Action verlangt aktuelles PW) | "qr" (M02) | "success" | "disable" (M03)
const [twoFa, setTwoFa] = useState(null);
const fileInput = useRef(null);
const avatarForm = useRef(null);
const [avatarData, setAvatarData] = useState("");
// Data URI of the picked file while the crop dialog is open; null when closed.
const [cropSource, setCropSource] = useState(null);
// Schritt-Übergänge des 2FA-Flows aus der Action-Antwort ableiten.
useEffect(() => {
if (otpauthUri && twoFa === "password") setTwoFa("qr");
}, [otpauthUri]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (recoveryCodes && recoveryCodes.length > 0) setTwoFa("success");
}, [recoveryCodes]);
// Modal/Inline-Edit erst bei bestätigtem Erfolg schließen (nicht optimistisch beim Submit) -> Fehler bleiben sichtbar.
useEffect(() => {
if (saved) setPwOpen(false);
}, [saved]);
// Disable-/Verwalten-Modal schließen, sobald 2FA tatsächlich deaktiviert ist.
useEffect(() => {
if (!mfaStatus?.enabled && (twoFa === "disable" || twoFa === "manage")) setTwoFa(null);
}, [mfaStatus?.enabled, twoFa]);
// A picked file goes into the crop dialog first; only the section the user
// confirmed there is submitted. Clearing the input lets the same file be
// picked again after a cancel, which otherwise fires no change event.
function onPickAvatar(event: React.ChangeEvent) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
const reader = new FileReader();
reader.onload = () => setCropSource(String(reader.result ?? ""));
reader.readAsDataURL(file);
}
function onCropConfirmed(dataUri: string) {
setCropSource(null);
setAvatarData(dataUri);
requestAnimationFrame(() => avatarForm.current && submit(avatarForm.current));
}
const mfaEnabled = Boolean(mfaStatus?.enabled);
const roleName = role === null || role === undefined ? "" : TenantUserType[role];
const roleLabel = roleName ? t(`settings.profile.types.${roleName}`) : "";
return (
{/* Page headline (title/subtitle) lives in the route's shared PageHeader. */}
{/* Reihe 1 — Profil + Accountsicherheit */}
{initials(user)}
{userDisplayName(user)}
{roleLabel ? {roleLabel} : null}
{/* Bild ändern (Avatar-Upload, autosubmit per onPick) */}
{/* Entfernen (Avatar löschen -> action=profile mit leerem avatar) */}
{t("settings.profile.security.accountSecurity")}
{t("settings.profile.security.twoFactorShort")}
{mfaEnabled ? t("settings.profile.mfa.badge.active") : t("settings.profile.mfa.badge.inactive")}
{/* Reihe 2 — Basis info + Login info */}
{t("settings.profile.basicInfo.title")}
{/* Login info */}
{t("settings.profile.loginInfo.title")}
••••••••••
{mfaEnabled ? t("settings.profile.mfa.badge.active") : t("settings.profile.mfa.badge.inactive")}
{cropSource ? (
setCropSource(null)} onConfirm={onCropConfirmed} />
) : null}
{pwOpen ? (
actionData?.passwordLocked ? (
setPwOpen(false)} />
) : (
setPwOpen(false)} />
)
) : null}
{twoFa ? (
setTwoFa(null)}
/>
) : null}
);
}
function ModalShell({
children,
dataUiId,
center = false,
onClose,
}: {
children: React.ReactNode;
dataUiId: string;
center?: boolean;
onClose: () => void;
}) {
return (
{children}
);
}
// WF-P2 ("Change Password") — Davids Subframe-Screens token-genau uebernommen:
// M01 "Identitaet bestaetigen" -> ChangePasswordDialog (Shield-Header + Konto-Card + aktuelles Passwort,
// Footer Abbrechen/Weiter). An die bestehende action=password verdrahtet (Single-Step, prueft das
// aktuelle Passwort serverseitig).
// V01 "Zu viele Fehlversuche" -> ChangePasswordLockedDialog (Davids Lockout-Card).
// Backend-Luecken (NICHT erfunden, geflaggt):
// - M01 zeigt zusaetzlich eine 2FA-Code-Karte (TOTP-Step-up vor dem Wechsel). Es gibt KEIN Backend, das
// einen TOTP-Step-up waehrend des Passwortwechsels verifiziert (action=password prueft nur das aktuelle
// Passwort) -> 2FA-Karte weggelassen, statt eine wirkungslose Eingabe zu bauen (CR). Die fuer den
// bestehenden Single-Step-Flow noetigen Felder (neues Passwort + Wiederholung) haben kein eigenes
// M01-Design und sind hier konsistent re-skinned ergaenzt.
// - V01: kein Rate-Limit-/Lockout-Backend fuer den Passwortwechsel -> einsatzbereit, wird aber erst
// ausgeloest, wenn die Action passwordLocked (+ Restzeit) liefert (s. actionData-Typ oben).
function ChangePasswordDialog({
user,
csrf,
submitting,
error,
onClose,
}: {
user: ProfileUser;
csrf: string;
submitting: boolean;
error?: string;
onClose: () => void;
}) {
const { t } = useTranslation();
const [pw, setPw] = useState("");
const strength = passwordStrength(pw);
const fullName = [user.firstName, user.lastName].filter(Boolean).join(" ");
return (
}
aria-label={t("shared.close")}
onClick={onClose}
data-ui-id="ui.settings.profile.password.close"
/>
{t("settings.profile.reauth.title")}
{t("settings.profile.reauth.subtitle")}
{initials(user)}
{fullName || user.email}
{user.email}
{t("settings.profile.reauth.currentAccount")}
);
}
function ChangePasswordLockedDialog({ retryLabel, onClose }: { retryLabel?: string; onClose: () => void }) {
const { t } = useTranslation();
return (
} />
{t("settings.profile.changePasswordLocked.title")}
{t("settings.profile.changePasswordLocked.subtitle")}
} data-ui-id="ui.settings.profile.password.locked.retry">
{t("settings.profile.changePasswordLocked.retryCta")}
} onClick={onClose} data-ui-id="ui.settings.profile.password.locked.back">
{t("settings.profile.changePasswordLocked.backToSettings")}
);
}
function DialogOverlay({ children, dataUiId, onClose }: { children: React.ReactNode; dataUiId: string; onClose: () => void }) {
// Davids DialogLayout (zentrierte Card auf abgedunkeltem Hintergrund) — aber
// durch die geteilte Dialog-Komponente, wie jeder andere Pop-up im Produkt.
// Vorher war das ein handgebautes `fixed inset-0` mitten im Seiteninhalt: das
// dunkelte nur den Inhaltsbereich ab, weil Sidebar und Kopfleiste auf
// derselben z-Ebene darueber lagen, und brachte weder Fokus-Falle noch
// Escape-to-close mit. Die Dialog-Komponente portalisiert nach document.body
// und loest das strukturell.
//
// Dialog.Content bleibt hier bewusst transparent und randlos: die Karte
// darin ist Davids Screen und bringt Rahmen, Flaeche und Schatten selbst mit.
return (
);
}
type TwoFaStep = "manage" | "password" | "qr" | "success" | "disable";
function TwoFaModal({
step,
csrf,
submitting,
otpauthUri,
recoveryCodes,
mfaError,
enabledAt,
onStep,
onClose,
}: {
step: TwoFaStep;
csrf: string;
submitting: boolean;
otpauthUri?: string;
recoveryCodes?: string[];
mfaError?: string;
enabledAt?: string | Date | null;
onStep: (step: TwoFaStep) => void;
onClose: () => void;
}) {
const { t, i18n } = useTranslation();
const secret = otpauthUri ? (new URLSearchParams(otpauthUri.split("?")[1] ?? "").get("secret") ?? "") : "";
const groupedSecret = secret.replace(/(.{4})/g, "$1 ").trim();
const [digits, setDigits] = useState(Array(6).fill(""));
const code = digits.join("");
function onOtpChange(index: number, raw: string) {
const clean = raw.replace(/\D/g, "").slice(0, 1);
setDigits((prev) => prev.map((d, idx) => (idx === index ? clean : d)));
}
// M01 — "2FA verwalten": Verwaltungs-Dialog (Einstieg bei aktivem 2FA). Nur die backend-gedeckte
// Authenticator-App-Methode wird gelistet; Sicherheitsschlüssel/Geräte-Metadaten/Recovery-Regenerate
// existieren backendseitig nicht und werden bewusst weggelassen (FLAG), statt Mock-Daten zu zeigen.
if (step === "manage") {
const activatedLabel =
enabledAt != null
? t("settings.profile.mfa.manage.activatedAt", { date: formatDate(enabledAt, i18n.language) })
: t("settings.profile.mfa.status.enabled");
return (
{t("settings.profile.mfa.title")}
{t("settings.profile.mfa.manage.subtitle")}
} onClick={onClose} data-ui-id="ui.settings.profile.mfa.manage.close" />
{t("settings.profile.mfa.disable.title")}
{t("settings.profile.mfa.manage.deactivateHint")}
}
onClick={() => onStep("disable")}
data-ui-id="ui.settings.profile.mfa.manage.deactivate"
>
{t("settings.profile.mfa.disable.cta")}
{t("settings.profile.mfa.manage.methodsLabel")}
} />
{t("settings.profile.mfa.authenticatorApp")}
{activatedLabel}
}
onClick={() => onStep("disable")}
data-ui-id="ui.settings.profile.mfa.manage.remove"
>
{t("shared.remove")}
}
onClick={() => onStep("password")}
data-ui-id="ui.settings.profile.mfa.manage.add"
>
{t("settings.profile.mfa.manage.addDevice")}
);
}
if (step === "success") {
return (
{t("settings.profile.mfa.success.title")}
{t("settings.profile.mfa.success.subtitle")}
{recoveryCodes && recoveryCodes.length > 0 ? (
{t("settings.profile.mfa.recoveryCodes")}
{recoveryCodes.map((code) => (
{code}
))}
) : null}
);
}
// M02 — "Gerät/Token hinzufügen": QR + manueller Schlüssel + OTP-Bestätigung in Davids Card.
// (Der Passwort-Gate-Step "password" läuft davor, da startTotpEnrollment das aktuelle Passwort verlangt.)
if (step === "qr") {
return (
{t("settings.profile.mfa.manage.addDevice")}
{t("settings.profile.mfa.add.subtitle")}
} onClick={onClose} data-ui-id="ui.settings.profile.mfa.setup.close" />
{otpauthUri ? : null}
{t("settings.profile.mfa.add.appHint")}
{secret ? (
<>
{t("settings.profile.mfa.setup.manualKey")}
{groupedSecret}
>
) : null}
);
}
// M03 — "2FA deaktivieren": Davids Warn-Card. FLAG: Davids Mock bestätigt mit dem aktuellen 2FA-Code (OTP);
// das bestehende disableTotpEnrollment verifiziert das Passwort -> Bestätigung bleibt Passwort-basiert.
if (step === "disable") {
return (
} />
{t("settings.profile.mfa.deactivate.title")}
{t("settings.profile.mfa.deactivate.subtitle")}
{t("settings.profile.mfa.deactivate.consequencesTitle")}
{t("settings.profile.mfa.deactivate.consequence1")}
{t("settings.profile.mfa.deactivate.consequence2")}
);
}
// step === "password" — Setup-Gate (Action verlangt aktuelles Passwort, bevor der QR erzeugt wird)
return (
{t("settings.profile.mfa.setup.title")}
{t("settings.profile.mfa.gate.subtitle")}
);
}