import { useState, useEffect, useCallback } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Alert, ActivityIndicator } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { useColors } from '../../lib/theme';
import { apiFetch } from '../../lib/api';
import { UserAvatar } from '../../components/UserAvatar';
import { PostCard } from '../../components/PostCard';
import { PostCardSkeleton } from '../../components/PostCardSkeleton';
import { PostCommentsSheet } from '../../components/PostCommentsSheet';
import { type CommunityPost } from '../../stores/community';
type ForeignProfile = {
id: string;
nickname: string;
avatar: string | null;
tier: string;
totalPoints: number;
postsCount: number;
followersCount: number;
followingCount: number;
approvedDomainsCount: number;
isFollowing: boolean;
isSelf: boolean;
joinedAt: string;
recentPosts: unknown[];
};
function formatJoinedAt(iso: string): string {
try {
const d = new Date(iso);
return d.toLocaleDateString('de-DE', { month: 'long', year: 'numeric' });
} catch {
return '';
}
}
type StatProps = { value: string; label: string };
function ForeignStat({ value, label }: StatProps) {
const colors = useColors();
return (
{value}
{label}
);
}
export default function ForeignProfileScreen() {
const insets = useSafeAreaInsets();
const router = useRouter();
const colors = useColors();
const { t } = useTranslation();
const { userId } = useLocalSearchParams<{ userId: string }>();
const [isFollowing, setIsFollowing] = useState(false);
const [localFollowersCount, setLocalFollowersCount] = useState(null);
const [followPending, setFollowPending] = useState(false);
const [activeCommentsPostId, setActiveCommentsPostId] = useState(null);
const openComments = useCallback((postId: string) => setActiveCommentsPostId(postId), []);
const closeComments = useCallback(() => setActiveCommentsPostId(null), []);
const { data: profile, isLoading, isError } = useQuery({
queryKey: ['foreign-profile', userId],
queryFn: () => apiFetch(`/api/social/profile/${userId}`),
enabled: !!userId,
});
const { data: userPosts = [], isLoading: postsLoading } = useQuery({
queryKey: ['community-posts', { userId }],
queryFn: () => apiFetch(`/api/community/posts?userId=${userId}&limit=20`),
enabled: !!userId,
});
useEffect(() => {
if (!profile) return;
if (profile.isSelf) {
router.replace('/profile');
return;
}
setIsFollowing(profile.isFollowing);
setLocalFollowersCount(profile.followersCount);
}, [profile]);
async function handleFollow() {
if (followPending || !profile) return;
const optimisticFollowing = !isFollowing;
const optimisticCount = (localFollowersCount ?? profile.followersCount) + (optimisticFollowing ? 1 : -1);
setIsFollowing(optimisticFollowing);
setLocalFollowersCount(optimisticCount);
setFollowPending(true);
try {
const res = await apiFetch<{ following: boolean; followersCount: number }>(
'/api/social/follow',
{ method: 'POST', body: { userId: profile.id } },
);
setIsFollowing(res.following);
setLocalFollowersCount(res.followersCount);
} catch {
setIsFollowing(!optimisticFollowing);
setLocalFollowersCount(localFollowersCount ?? profile.followersCount);
Alert.alert(t('common.error'), t('common.unknown_error'));
} finally {
setFollowPending(false);
}
}
if (isLoading) {
return (
router.back()} hitSlop={8} activeOpacity={0.5} style={{ padding: 8 }}>
);
}
if (isError || !profile) {
return (
router.back()} hitSlop={8} activeOpacity={0.5} style={{ padding: 8 }}>
{t('common.unknown_error')}
router.back()} activeOpacity={0.7}>
{t('common.back')}
);
}
const displayFollowers = localFollowersCount ?? profile.followersCount;
return (
router.back()} hitSlop={8} activeOpacity={0.5} style={{ padding: 8 }}>
Profil
{profile.nickname}
Mitglied seit {formatJoinedAt(profile.joinedAt)}
{isFollowing ? 'Folge ich' : 'Folgen'}
router.push({ pathname: '/dm', params: { userId: profile.id } })}
activeOpacity={0.7}
style={{ flex: 1 }}
>
Nachricht
{t('community.recent_posts')}
{postsLoading ? (
) : userPosts.length === 0 ? (
{t('community.no_posts')}
) : (
userPosts.map((post) => (
))
)}
);
}