import { useEffect, useMemo, useRef, useState } from 'react' import { Button, Container, Form } from 'react-bootstrap' import { Link, useParams } from 'react-router-dom' import { createPost, getThread, listPostsByThread } from '../api/client' import { useAuth } from '../context/AuthContext' import { useTranslation } from 'react-i18next' export default function ThreadView() { const { id } = useParams() const { token } = useAuth() const [thread, setThread] = useState(null) const [posts, setPosts] = useState([]) const [error, setError] = useState('') const [loading, setLoading] = useState(true) const [body, setBody] = useState('') const [saving, setSaving] = useState(false) const { t } = useTranslation() const replyRef = useRef(null) useEffect(() => { setLoading(true) Promise.all([getThread(id), listPostsByThread(id)]) .then(([threadData, postData]) => { setThread(threadData) setPosts(postData) }) .catch((err) => setError(err.message)) .finally(() => setLoading(false)) }, [id]) const handleSubmit = async (event) => { event.preventDefault() setSaving(true) setError('') try { await createPost({ body, threadId: id }) setBody('') const updated = await listPostsByThread(id) setPosts(updated) } catch (err) { setError(err.message) } finally { setSaving(false) } } const replyCount = posts.length const formatDate = (value) => { if (!value) return '—' const date = new Date(value) if (Number.isNaN(date.getTime())) return '—' const day = String(date.getDate()).padStart(2, '0') const month = String(date.getMonth() + 1).padStart(2, '0') const year = String(date.getFullYear()) return `${day}.${month}.${year}` } const allPosts = useMemo(() => { if (!thread) return posts const rootPost = { id: `thread-${thread.id}`, body: thread.body, created_at: thread.created_at, user_name: thread.user_name, user_avatar_url: thread.user_avatar_url, user_posts_count: thread.user_posts_count, user_created_at: thread.user_created_at, user_location: thread.user_location, user_rank_name: thread.user_rank_name, user_rank_badge_type: thread.user_rank_badge_type, user_rank_badge_text: thread.user_rank_badge_text, user_rank_badge_url: thread.user_rank_badge_url, isRoot: true, } return [rootPost, ...posts] }, [posts, thread]) const handleJumpToReply = () => { replyRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }) } const totalPosts = allPosts.length return ( {loading &&

{t('thread.loading')}

} {error &&

{error}

} {thread && (

{thread.title}

{t('thread.by')} {thread.user_name || t('thread.anonymous')} {thread.created_at && ( {thread.created_at.slice(0, 10)} )}