import React, { useState } from 'react'; import { useNavigate, useSearchParams, Link } from 'react-router-dom'; import { toast } from 'sonner'; import Container from '@/components/Layout/Container'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { LogIn, Eye, EyeOff, ArrowLeft } from 'lucide-react'; export default function Login() { const navigate = useNavigate(); const [searchParams] = useSearchParams(); const redirectTo = searchParams.get('redirect') || '/my-account'; const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(''); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(''); setIsLoading(true); try { const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1'; const nonce = (window as any).woonoowCustomer?.nonce || ''; const response = await fetch(`${apiRoot}/auth/customer-login`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce, }, credentials: 'include', body: JSON.stringify({ username, password }), }); const data = await response.json(); if (data.success) { // Update window config with new nonce and user data if ((window as any).woonoowCustomer) { (window as any).woonoowCustomer.nonce = data.nonce; (window as any).woonoowCustomer.user = { isLoggedIn: true, id: data.user.id, name: data.user.name, email: data.user.email, firstName: data.user.first_name, lastName: data.user.last_name, avatar: data.user.avatar, }; } toast.success('Login successful!'); // Set the target URL with hash route, then force reload // The hash change alone doesn't reload the page, so cookies won't be refreshed const targetUrl = window.location.origin + '/store/#' + redirectTo; window.location.href = targetUrl; // Force page reload to refresh cookies and server-side state window.location.reload(); } else { setError(data.message || 'Login failed'); } } catch (err: any) { setError(err.message || 'An error occurred. Please try again.'); } finally { setIsLoading(false); } }; return (
{/* Back link */} Continue shopping
{/* Header */}

Welcome Back

Sign in to your account

{/* Error message */} {error && (
{error}
)} {/* Form */}
setUsername(e.target.value)} placeholder="Enter your email or username" required autoComplete="username" disabled={isLoading} />
setPassword(e.target.value)} placeholder="Enter your password" required autoComplete="current-password" disabled={isLoading} className="pr-10" />
{/* Footer links */}
); }