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

View file

@ -62,5 +62,48 @@
"privacy": "Privacy Policy", "terms": "Terms of Use",
"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" }
}

View file

@ -62,5 +62,48 @@
"privacy": "Política de Privacidad", "terms": "Términos de Uso",
"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" }
}

View file

@ -62,5 +62,48 @@
"privacy": "Política de Privacidade", "terms": "Termos de Uso",
"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" }
}

View file

@ -1,6 +1,6 @@
'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 es from '@/i18n/es.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 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 }) {
const [locale, setLocale] = useState<Locale>('en');
const [locale, setLocale] = useState<Locale>(getInitialLocale);
const t = useCallback((key: string, params?: Record<string, string | number>): string => {
const keys = key.split('.');
@ -49,6 +66,12 @@ export function I18nProvider({ children }: { children: ReactNode }) {
return value;
}, [locale]);
useEffect(() => {
if (typeof window === 'undefined') return;
localStorage.setItem(localeStorageKey, locale);
document.documentElement.lang = locale;
}, [locale]);
return (
<I18nContext.Provider value={{ locale, setLocale, t }}>
{children}