import React, { useRef, useState } from 'react'; export default function AvatarUpload({ uploadUrl, initialThumbUrl, initials }) { const [thumbUrl, setThumbUrl] = useState(initialThumbUrl || null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const inputRef = useRef(null); function handleClick() { inputRef.current?.click(); } function handleChange(e) { const file = e.target.files?.[0]; if (!file) return; const fd = new FormData(); fd.append('avatar', file); setLoading(true); setError(null); fetch(uploadUrl, { method: 'POST', body: fd }) .then(r => r.json()) .then(data => { if (data.error) { setError(data.error); return; } setThumbUrl(data.thumbUrl); const navImg = document.querySelector('.hero-auth-avatar:not(.hero-auth-avatar--initials)'); const navInitials = document.querySelector('.hero-auth-avatar.hero-auth-avatar--initials'); if (navImg) { navImg.src = data.thumbUrl; } else if (navInitials) { const img = document.createElement('img'); img.src = data.thumbUrl; img.alt = navInitials.textContent.trim(); img.className = 'hero-auth-avatar'; navInitials.replaceWith(img); } }) .catch(() => setError('Upload failed. Please try again.')) .finally(() => setLoading(false)); } return (
{thumbUrl ? {initials} : {initials} }
{error &&
{error}
}
); }