import { signIn, authClient } from "@/src/lib/auth-client"; import { apiRequest } from "@/src/lib/api-client"; import { useAuthStore, type Household } from "@/src/stores/auth.store"; import { useRouter } from "expo-router"; import { useState } from "react"; import * as AppleAuthentication from "expo-apple-authentication"; import { ActivityIndicator, KeyboardAvoidingView, Platform, Pressable, Text, TextInput, View, } from "react-native"; import { useTranslation } from "react-i18next"; export default function LoginScreen() { const router = useRouter(); const { t } = useTranslation(); const { setUser, setHouseholds, setActiveHousehold } = useAuthStore(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); async function handleEmailSignIn() { if (!email || !password) { setError(t('login.fillAllFields')); return; } setIsLoading(true); setError(null); try { const result = await signIn.email({ email, password }); if (result.error) { const msg = result.error.message ?? ""; if (msg.toLowerCase().includes("email") && msg.toLowerCase().includes("verif")) { router.push({ pathname: "/(auth)/verify-email", params: { email } }); return; } setError(msg || t('login.signInError')); return; } if (result.data?.user) setUser(result.data.user); try { const { households } = await apiRequest<{ households: Household[] }>("/api/households"); setHouseholds(households); if (households.length > 0) setActiveHousehold(households[0].id); } catch { // households will be loaded on next app start } router.replace("/(app)/haushalt"); } catch { setError(t('login.signInError')); } finally { setIsLoading(false); } } async function handleAppleSignIn() { try { const credential = await AppleAuthentication.signInAsync({ requestedScopes: [ AppleAuthentication.AppleAuthenticationScope.FULL_NAME, AppleAuthentication.AppleAuthenticationScope.EMAIL, ], }); if (!credential.identityToken) return; const result = await authClient.signIn.social({ provider: "apple", idToken: { token: credential.identityToken }, }); if (result.error) { setError(result.error.message ?? t('common.error')); return; } // session is handled by authClient interceptor router.replace("/(app)/haushalt"); } catch (err: unknown) { if ((err as { code?: string }).code !== "ERR_CANCELED") { setError(t('login.appleSignInError')); } } } return ( {t('login.welcome')} {t('login.subtitle')} {error && ( {error} )} {Platform.OS === "ios" && ( <> {t('common.or')} )} {t('login.emailLabel')} {t('login.passwordLabel')} {isLoading ? ( ) : ( {t('login.signIn')} )} router.push("/(auth)/forgot-password")} className="mb-6 items-center py-2 active:opacity-60" > {t('login.forgotPassword')} {t('login.noAccount')} router.push("/(auth)/register")}> {t('login.register')} ); }