import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { API_URL, deleteComment, getSsulContentById, getUserMe, getVideoComments, isLoggedIn, postVideoComment, toggleVideoLike, } from '../utils/api'; import type { SsulDetailItem } from '../utils/api'; import { CommentItem, P2vContentType, UserMeResponse } from '../types/api'; import { buildContentShareUrl, tryNativeShare } from '../utils/nativeShare'; import LoginPromptModal from './LoginPromptModal'; import { isSafeHttpUrl } from '../utils/url'; import { getP2vContentById } from '../utils/p2vApi'; interface ContentDetailContentProps { contentId: string; contentType: 'ssul' | P2vContentType; isModal?: boolean; onClose?: () => void; } type DetailContent = Pick & { poster_url?: string | null }; /** Shared public detail UI for Ssulbox and P2V content. */ const ContentDetailContent: React.FC = ({ contentId, contentType, isModal = false, onClose, }) => { const { t } = useTranslation(); const authed = isLoggedIn(); const [content, setContent] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [likeCount, setLikeCount] = useState(0); const [isLiked, setIsLiked] = useState(false); const [likeSubmitting, setLikeSubmitting] = useState(false); const [copied, setCopied] = useState(false); const [isLandscape, setIsLandscape] = useState(false); const [showSiteOverlay, setShowSiteOverlay] = useState(false); const [showLoginModal, setShowLoginModal] = useState(false); const [comments, setComments] = useState([]); const [commentsTotal, setCommentsTotal] = useState(0); const [commentsPage, setCommentsPage] = useState(1); const [commentsHasNext, setCommentsHasNext] = useState(false); const [commentsLoading, setCommentsLoading] = useState(false); const [commentInput, setCommentInput] = useState(''); const [commentSubmitting, setCommentSubmitting] = useState(false); const commentTextareaRef = useRef(null); const [currentUser, setCurrentUser] = useState(null); const fetchComments = useCallback( async (page: number, append = false) => { setCommentsLoading(true); try { const res = await getVideoComments(contentId, page, 20, contentType); const sorted = [...res.items].sort( (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime() ); setComments((prev) => (append ? [...prev, ...sorted] : sorted)); setCommentsTotal(res.total); setCommentsHasNext(res.has_next); setCommentsPage(page); } catch (err) { console.error('Failed to fetch content comments:', err); } finally { setCommentsLoading(false); } }, [contentId, contentType] ); useEffect(() => { const fetchContent = async () => { setLoading(true); setError(null); setShowSiteOverlay(false); try { const data = contentType === 'ssul' ? await getSsulContentById(contentId) : await getP2vContentById(contentType, contentId).then((item) => ({ ...item, store_name: item.title, })); setContent(data); setLikeCount(data.like_count); setIsLiked(data.is_liked_by_me); } catch (err) { console.error('Failed to fetch content:', err); setError(t('ado2Contents.loadFailed')); } finally { setLoading(false); } }; setIsLandscape(false); fetchContent(); fetchComments(1); }, [contentId, contentType, fetchComments, t]); useEffect(() => { if (!authed) return; getUserMe().then(setCurrentUser).catch((err) => { console.error('Failed to fetch current user:', err); }); }, [authed]); const formatDate = (dateString: string) => { const date = new Date(dateString); return t('videoDetail.dateFormat', { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate(), }); }; const formatCommentDate = (dateString: string) => { const date = new Date(dateString); return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String( date.getDate() ).padStart(2, '0')}`; }; // ID 가 같아도 콘텐츠 종류에 맞는 공유 경로로 연다. const shareUrl = buildContentShareUrl(API_URL, contentId, contentType); const handleCopyLink = async () => { try { await navigator.clipboard.writeText(shareUrl); } catch { // clipboard API 미지원 환경에서는 무시 } setCopied(true); setTimeout(() => setCopied(false), 2000); }; const handleShareButtonClick = async () => { const handled = await tryNativeShare({ title: content?.store_name ?? t('videoDetail.kakaoDefaultTitle'), url: shareUrl, }); if (handled) { return; } await handleCopyLink(); }; const handleLike = async () => { if (!authed) { setShowLoginModal(true); return; } if (likeSubmitting) return; const prevLiked = isLiked; const prevCount = likeCount; setLikeSubmitting(true); setIsLiked(!prevLiked); setLikeCount(prevLiked ? prevCount - 1 : prevCount + 1); try { const result = await toggleVideoLike(contentId, contentType); setIsLiked(result.is_liked); setLikeCount(result.like_count); } catch (err) { console.error('Failed to toggle content like:', err); setIsLiked(prevLiked); setLikeCount(prevCount); } finally { setLikeSubmitting(false); } }; const handleHeaderAction = () => { onClose?.(); }; const handleCommentFocus = () => { if (!authed) setShowLoginModal(true); }; const handleCommentSubmit = async () => { if (!authed) { setShowLoginModal(true); return; } if (!commentInput.trim() || commentSubmitting) return; setCommentSubmitting(true); try { await postVideoComment(contentId, commentInput.trim(), undefined, contentType); setCommentInput(''); if (commentTextareaRef.current) { commentTextareaRef.current.style.height = 'auto'; } await fetchComments(1); } catch (err) { console.error('Failed to post content comment:', err); } finally { setCommentSubmitting(false); } }; const handleDeleteComment = async (commentId: number) => { try { await deleteComment(commentId); await fetchComments(commentsPage); } catch (err) { console.error('Failed to delete content comment:', err); } }; const renderCommentContent = (content_: string | null, isDeleted: boolean) => { if (isDeleted) { return ( {t('videoDetail.deletedComment')} ); } return content_; }; return (
{/* 헤더 */}
{isModal ? ( <> {/* 제목이 없으면 space-between 인 헤더에서 닫기 버튼이 왼쪽으로 붙는다. 문구는 ADO2 상세와 같은 키를 쓴다 — 통합 목록에서 열리는 같은 모달이므로 콘텐츠 종류에 따라 제목이 바뀌면 오히려 어색하다. */}

{t('sidebar.ado2Contents')}

) : ( )}
{loading ? (

{t('ado2Contents.loading')}

) : error ? (

{error}

) : content ? (

{content.store_name || t('ssulbox.viewer.untitled')}

{formatDate(content.created_at)}

{/* 좋아요 + 공유 */}
{/* 댓글 섹션 */}

{t('videoDetail.commentsTitle')}

{commentsTotal}
{authed && currentUser && (
{currentUser.profile_image_url && ( {currentUser.nickname} )} {currentUser.nickname}
)}