Fix login i18n and forgot password page

This commit is contained in:
Tiago Yamamoto 2025-12-22 13:45:02 -03:00
parent 79a59e44cd
commit af7b68ee86
6 changed files with 255 additions and 30 deletions

View file

@ -0,0 +1,69 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useTranslation } from "@/lib/i18n";
export default function ForgotPasswordPage() {
const { t } = useTranslation();
const [email, setEmail] = useState("");
const [submitted, setSubmitted] = useState(false);
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSubmitted(true);
};
return (
<div className="min-h-screen flex items-center justify-center bg-background px-6 py-12">
<div className="w-full max-w-md space-y-6">
<div className="text-center space-y-2">
<h1 className="text-3xl font-bold">{t("auth.forgot.title")}</h1>
<p className="text-muted-foreground">{t("auth.forgot.subtitle")}</p>
</div>
<Card className="border-0 shadow-lg">
<CardContent className="pt-6 space-y-4">
{submitted && (
<Alert>
<AlertDescription>{t("auth.forgot.success")}</AlertDescription>
</Alert>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">{t("auth.forgot.fields.email")}</Label>
<Input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
placeholder={t("auth.forgot.fields.emailPlaceholder")}
required
/>
</div>
<Button type="submit" className="w-full h-11">
{t("auth.forgot.submit")}
</Button>
</form>
</CardContent>
</Card>
<div className="text-center">
<Link
href="/login"
className="text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-2"
>
{t("auth.forgot.backLogin")}
</Link>
</div>
</div>
</div>
);
}

View file

@ -1,6 +1,6 @@
"use client"; "use client";
import { useState } from "react"; import { useMemo, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import Image from "next/image"; import Image from "next/image";
@ -27,20 +27,25 @@ import { motion } from "framer-motion";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod"; import { z } from "zod";
import { useTranslation } from "@/lib/i18n";
const loginSchema = z.object({ type LoginFormData = {
email: z.string().min(3, "Usuário deve ter pelo menos 3 caracteres"), email: string;
password: z.string().min(3, "Senha deve ter pelo menos 3 caracteres"), password: string;
rememberMe: z.boolean().optional(), rememberMe?: boolean;
}); };
type LoginFormData = z.infer<typeof loginSchema>;
export default function LoginPage() { export default function LoginPage() {
const router = useRouter(); const router = useRouter();
const { t } = useTranslation();
const [error, setError] = useState(""); const [error, setError] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const loginSchema = useMemo(() => z.object({
email: z.string().min(3, t("auth.login.validation.username")),
password: z.string().min(3, t("auth.login.validation.password")),
rememberMe: z.boolean().optional(),
}), [t]);
const { const {
register, register,
@ -71,11 +76,11 @@ export default function LoginPage() {
router.push("/dashboard"); router.push("/dashboard");
} else { } else {
setError("Usuário ou senha inválidos."); setError(t("auth.login.errors.invalidCredentials"));
} }
} catch (err: any) { } catch (err: any) {
console.error(err); console.error(err);
setError(err.message || "Erro ao fazer login. Tente novamente."); setError(err.message || t("auth.login.errors.generic"));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@ -105,12 +110,11 @@ export default function LoginPage() {
</div> </div>
<h1 className="text-4xl font-bold mb-4"> <h1 className="text-4xl font-bold mb-4">
Conecte-se ao seu futuro profissional {t("auth.login.hero.title")}
</h1> </h1>
<p className="text-lg opacity-90 leading-relaxed"> <p className="text-lg opacity-90 leading-relaxed">
A plataforma que une talentos e oportunidades. Entre na sua conta e {t("auth.login.hero.subtitle")}
descubra as melhores vagas do mercado.
</p> </p>
<div className="mt-8 space-y-4"> <div className="mt-8 space-y-4">
@ -118,19 +122,19 @@ export default function LoginPage() {
<div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center"> <div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
<UserIcon className="w-4 h-4" /> <UserIcon className="w-4 h-4" />
</div> </div>
<span>Perfil profissional completo</span> <span>{t("auth.login.hero.bulletProfile")}</span>
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center"> <div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
<Building2 className="w-4 h-4" /> <Building2 className="w-4 h-4" />
</div> </div>
<span>Empresas de destaque</span> <span>{t("auth.login.hero.bulletCompanies")}</span>
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center"> <div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
<Briefcase className="w-4 h-4" /> <Briefcase className="w-4 h-4" />
</div> </div>
<span>Vagas exclusivas</span> <span>{t("auth.login.hero.bulletJobs")}</span>
</div> </div>
</div> </div>
</motion.div> </motion.div>
@ -144,9 +148,9 @@ export default function LoginPage() {
className="w-full max-w-md space-y-6" className="w-full max-w-md space-y-6"
> >
<div className="text-center space-y-2"> <div className="text-center space-y-2">
<h2 className="text-3xl font-bold">Bem-vindo de volta</h2> <h2 className="text-3xl font-bold">{t("auth.login.title")}</h2>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
Entre com sua conta para continuar {t("auth.login.subtitle")}
</p> </p>
</div> </div>
@ -166,13 +170,13 @@ export default function LoginPage() {
)} )}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="email">Usuário</Label> <Label htmlFor="email">{t("auth.login.fields.username")}</Label>
<div className="relative" suppressHydrationWarning> <div className="relative" suppressHydrationWarning>
<UserIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /> <UserIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input <Input
id="email" id="email"
type="text" type="text"
placeholder="Digite seu usuário" placeholder={t("auth.login.fields.usernamePlaceholder")}
className="pl-10" className="pl-10"
{...register("email")} {...register("email")}
/> />
@ -185,13 +189,13 @@ export default function LoginPage() {
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="password">Senha</Label> <Label htmlFor="password">{t("auth.login.fields.password")}</Label>
<div className="relative"> <div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /> <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input <Input
id="password" id="password"
type={showPassword ? "text" : "password"} type={showPassword ? "text" : "password"}
placeholder="••••••••" placeholder={t("auth.login.fields.passwordPlaceholder")}
className="pl-10 pr-10" className="pl-10 pr-10"
{...register("password")} {...register("password")}
/> />
@ -223,14 +227,14 @@ export default function LoginPage() {
htmlFor="rememberMe" htmlFor="rememberMe"
className="text-sm font-normal cursor-pointer" className="text-sm font-normal cursor-pointer"
> >
Lembrar de mim {t("auth.login.rememberMe")}
</Label> </Label>
</div> </div>
<Link // Link is not defined in import if I removed it? No it is. <Link
href="#" href="/forgot-password"
className="text-sm text-primary hover:underline" className="text-sm text-primary hover:underline"
> >
Esqueceu a senha? {t("auth.login.forgotPassword")}
</Link> </Link>
</div> </div>
@ -239,7 +243,7 @@ export default function LoginPage() {
className="w-full h-11 cursor-pointer" className="w-full h-11 cursor-pointer"
disabled={loading} disabled={loading}
> >
{loading ? "Entrando..." : "Entrar"} {loading ? t("auth.login.loading") : t("auth.login.submit")}
</Button> </Button>
</form> </form>
</CardContent> </CardContent>
@ -250,7 +254,7 @@ export default function LoginPage() {
href="/" href="/"
className="text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-2" className="text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-2"
> >
Voltar para home {t("auth.login.backHome")}
</Link> </Link>
</div> </div>
</motion.div> </motion.div>

View file

@ -62,5 +62,48 @@
"privacy": "Privacy Policy", "terms": "Terms of Use", "privacy": "Privacy Policy", "terms": "Terms of Use",
"copyright": "© {year} GoHorse Jobs. All rights reserved." "copyright": "© {year} GoHorse Jobs. All rights reserved."
}, },
"auth": {
"login": {
"title": "Welcome back",
"subtitle": "Sign in to continue",
"hero": {
"title": "Connect to your professional future",
"subtitle": "The platform that brings talent and opportunities together. Sign in and discover the best jobs in the market.",
"bulletProfile": "Complete professional profile",
"bulletCompanies": "Featured companies",
"bulletJobs": "Exclusive jobs"
},
"fields": {
"username": "Username",
"usernamePlaceholder": "Enter your username",
"password": "Password",
"passwordPlaceholder": "••••••••"
},
"rememberMe": "Remember me",
"forgotPassword": "Forgot password?",
"submit": "Sign in",
"loading": "Signing in...",
"backHome": "← Back to home",
"validation": {
"username": "Username must be at least 3 characters",
"password": "Password must be at least 3 characters"
},
"errors": {
"invalidCredentials": "Invalid username or password.",
"generic": "Error signing in. Please try again."
}
},
"forgot": {
"title": "Reset your password",
"subtitle": "Enter your email and we'll send recovery instructions.",
"fields": {
"email": "Email",
"emailPlaceholder": "you@email.com"
},
"submit": "Send reset link",
"success": "If the email exists, we'll send recovery instructions shortly.",
"backLogin": "← Back to login"
}
},
"common": { "loading": "Loading...", "error": "Error", "retry": "Retry", "noResults": "No results found" } "common": { "loading": "Loading...", "error": "Error", "retry": "Retry", "noResults": "No results found" }
} }

View file

@ -62,5 +62,48 @@
"privacy": "Política de Privacidad", "terms": "Términos de Uso", "privacy": "Política de Privacidad", "terms": "Términos de Uso",
"copyright": "© {year} GoHorse Jobs. Todos los derechos reservados." "copyright": "© {year} GoHorse Jobs. Todos los derechos reservados."
}, },
"auth": {
"login": {
"title": "Bienvenido de nuevo",
"subtitle": "Inicia sesión para continuar",
"hero": {
"title": "Conéctate con tu futuro profesional",
"subtitle": "La plataforma que une talentos y oportunidades. Inicia sesión y descubre las mejores ofertas del mercado.",
"bulletProfile": "Perfil profesional completo",
"bulletCompanies": "Empresas destacadas",
"bulletJobs": "Vacantes exclusivas"
},
"fields": {
"username": "Usuario",
"usernamePlaceholder": "Ingresa tu usuario",
"password": "Contraseña",
"passwordPlaceholder": "••••••••"
},
"rememberMe": "Recordarme",
"forgotPassword": "¿Olvidaste tu contraseña?",
"submit": "Ingresar",
"loading": "Ingresando...",
"backHome": "← Volver al inicio",
"validation": {
"username": "El usuario debe tener al menos 3 caracteres",
"password": "La contraseña debe tener al menos 3 caracteres"
},
"errors": {
"invalidCredentials": "Usuario o contraseña inválidos.",
"generic": "Error al iniciar sesión. Inténtalo de nuevo."
}
},
"forgot": {
"title": "Restablecer contraseña",
"subtitle": "Ingresa tu correo y te enviaremos instrucciones de recuperación.",
"fields": {
"email": "Correo electrónico",
"emailPlaceholder": "tu@email.com"
},
"submit": "Enviar enlace de restablecimiento",
"success": "Si el correo existe, te enviaremos instrucciones en breve.",
"backLogin": "← Volver al login"
}
},
"common": { "loading": "Cargando...", "error": "Error", "retry": "Reintentar", "noResults": "No se encontraron resultados" } "common": { "loading": "Cargando...", "error": "Error", "retry": "Reintentar", "noResults": "No se encontraron resultados" }
} }

View file

@ -62,5 +62,48 @@
"privacy": "Política de Privacidade", "terms": "Termos de Uso", "privacy": "Política de Privacidade", "terms": "Termos de Uso",
"copyright": "© {year} GoHorse Jobs. Todos os direitos reservados." "copyright": "© {year} GoHorse Jobs. Todos os direitos reservados."
}, },
"auth": {
"login": {
"title": "Bem-vindo de volta",
"subtitle": "Entre com sua conta para continuar",
"hero": {
"title": "Conecte-se ao seu futuro profissional",
"subtitle": "A plataforma que une talentos e oportunidades. Entre na sua conta e descubra as melhores vagas do mercado.",
"bulletProfile": "Perfil profissional completo",
"bulletCompanies": "Empresas de destaque",
"bulletJobs": "Vagas exclusivas"
},
"fields": {
"username": "Usuário",
"usernamePlaceholder": "Digite seu usuário",
"password": "Senha",
"passwordPlaceholder": "••••••••"
},
"rememberMe": "Lembrar de mim",
"forgotPassword": "Esqueceu a senha?",
"submit": "Entrar",
"loading": "Entrando...",
"backHome": "← Voltar para home",
"validation": {
"username": "Usuário deve ter pelo menos 3 caracteres",
"password": "Senha deve ter pelo menos 3 caracteres"
},
"errors": {
"invalidCredentials": "Usuário ou senha inválidos.",
"generic": "Erro ao fazer login. Tente novamente."
}
},
"forgot": {
"title": "Recuperar senha",
"subtitle": "Informe seu e-mail e enviaremos instruções de recuperação.",
"fields": {
"email": "E-mail",
"emailPlaceholder": "seu@email.com"
},
"submit": "Enviar link de recuperação",
"success": "Se o e-mail existir, enviaremos as instruções em instantes.",
"backLogin": "← Voltar para login"
}
},
"common": { "loading": "Carregando...", "error": "Erro", "retry": "Tentar novamente", "noResults": "Nenhum resultado encontrado" } "common": { "loading": "Carregando...", "error": "Erro", "retry": "Tentar novamente", "noResults": "Nenhum resultado encontrado" }
} }

View file

@ -1,6 +1,6 @@
'use client'; 'use client';
import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react'; import React, { createContext, useContext, useState, useCallback, ReactNode, useEffect } from 'react';
import en from '@/i18n/en.json'; import en from '@/i18n/en.json';
import es from '@/i18n/es.json'; import es from '@/i18n/es.json';
import ptBR from '@/i18n/pt-BR.json'; import ptBR from '@/i18n/pt-BR.json';
@ -21,8 +21,25 @@ const dictionaries: Record<Locale, typeof en> = {
const I18nContext = createContext<I18nContextType | null>(null); const I18nContext = createContext<I18nContextType | null>(null);
const localeStorageKey = 'locale';
const normalizeLocale = (language: string): Locale => {
if (language.startsWith('pt')) return 'pt-BR';
if (language.startsWith('es')) return 'es';
return 'en';
};
const getInitialLocale = (): Locale => {
if (typeof window === 'undefined') return 'en';
const storedLocale = localStorage.getItem(localeStorageKey);
if (storedLocale && storedLocale in dictionaries) {
return storedLocale as Locale;
}
return normalizeLocale(navigator.language);
};
export function I18nProvider({ children }: { children: ReactNode }) { export function I18nProvider({ children }: { children: ReactNode }) {
const [locale, setLocale] = useState<Locale>('en'); const [locale, setLocale] = useState<Locale>(getInitialLocale);
const t = useCallback((key: string, params?: Record<string, string | number>): string => { const t = useCallback((key: string, params?: Record<string, string | number>): string => {
const keys = key.split('.'); const keys = key.split('.');
@ -49,6 +66,12 @@ export function I18nProvider({ children }: { children: ReactNode }) {
return value; return value;
}, [locale]); }, [locale]);
useEffect(() => {
if (typeof window === 'undefined') return;
localStorage.setItem(localeStorageKey, locale);
document.documentElement.lang = locale;
}, [locale]);
return ( return (
<I18nContext.Provider value={{ locale, setLocale, t }}> <I18nContext.Provider value={{ locale, setLocale, t }}>
{children} {children}