"use client"; import React, { useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useSearchParams } from "next/navigation"; import Link from "next/link"; export function LoginForm() { const { login } = useAuth(); const searchParams = useSearchParams(); const raw = searchParams.get("redirect") || ""; const hasExplicitRedirect = raw.startsWith("/") && !raw.startsWith("//"); const redirectTo = hasExplicitRedirect ? raw : "/dashboard"; const registerHref = redirectTo !== "/dashboard" ? `/register?redirect=${encodeURIComponent(redirectTo)}` : "/register"; const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [showPassword, setShowPassword] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const getErrorMessage = (err: any) => { if (!err) return "Login failed"; // If it's already a normal Error if (err.message && typeof err.message === "string") { // Handle case where message is accidentally JSON string try { const parsed = JSON.parse(err.message); return parsed.message || err.message; } catch { return err.message; } } // If API response object was thrown directly if (err.message) return err.message; return "Login failed"; }; const onSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); setLoading(true); try { const loggedInUser = await login(email, password); // Skip the generic /dashboard hop (which just redirects again once the role is known) // and go straight to the role-specific dashboard, unless the caller asked for a specific // page back (e.g. returning to a registration flow after login). const target = hasExplicitRedirect ? redirectTo : `/dashboard/${loggedInUser.role || "user"}`; window.location.href = target; } catch (err: any) { setError(getErrorMessage(err) || "Login failed. Please try again."); } finally { setLoading(false); } }; return (
setEmail(e.target.value)} className="w-full border rounded px-3 py-2" required />
setPassword(e.target.value)} className="w-full border rounded px-3 py-2 pr-20" required />
Forgot your password?
Don't have an account? Sign up here.
{error && (

{error}

{error.toLowerCase().includes('not yet active') && (

Check your inbox for an activation email. If you didn't receive it, try logging in again to resend it.

)}
)}

By signing in, you acknowledge that you’ve read and agree to our{" "} Terms of Use {" "} and{" "} Privacy Policy .

); }