const handleUploadProfilePicture = async (file: File) => { try { setUploadingPicture(true); // Convert image to base64 string (without prefix) const base64String = await fileToBase64(file); // Call your API function const response = await handleProfilePixUpdate(user.id, base64String); if (response?.succeeded && response.data) { console.log("Profile picture updated successfully:", response.data); // Get the current user details from cookie const currentUserDetails = Cookies.get(cookieName.USER_DETAILS); const parsedCurrentUser = currentUserDetails ? JSON.parse(currentUserDetails) : null; // Merge the updated data with existing user details const updatedUserDetails = { ...parsedCurrentUser, ...response.data, // Ensure the profile picture URL is properly set profilePicture: response.data.profilePicture || response.data.profilePictureUrl || response.data.pictureUrl, }; console.log("Updated user details:", updatedUserDetails); // Update the cookie with the merged data Cookies.set( cookieName.USER_DETAILS, JSON.stringify(updatedUserDetails), { httpOnly: false, secure: process.env.NODE_ENV === "production", sameSite: "strict", path: "/", } ); // Update the current avatar source immediately with cache busting const newAvatarUrl = response.data.profilePicture || response.data.profilePictureUrl || response.data.pictureUrl; if (newAvatarUrl) { // Reset error state and set new image with cache busting setImageError(false); // Wait a moment for the image to be available on the server before setting cache busting setTimeout(() => { checkImageExists(newAvatarUrl).then((exists) => { if (exists) { setCurrentAvatarSrc(`${newAvatarUrl}?t=${Date.now()}`); } else { // If image doesn't exist yet, try again in a moment setTimeout(() => { setCurrentAvatarSrc(`${newAvatarUrl}?t=${Date.now()}`); }, 1000); } }); }, 500); } setPictureUploadSuccess(true); setShowProfilePictureModal(false); // Show the update notice banner setShowUpdateNotice(true); // Show success message usePopupStore .getState() .showPopup("success", "Profile picture updated successfully!"); } } catch (error: any) { console.error("Error uploading profile picture:", error); usePopupStore .getState() .showPopup("error", error?.message || "An unexpected error occurred."); } finally { setUploadingPicture(false); } };