'use client'

import { useState, useRef, useEffect } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { FiUser, FiChevronDown, FiChevronUp, FiMoreVertical, FiX } from 'react-icons/fi'
import { FaRegHeart, FaHeart } from 'react-icons/fa6'
import { BiSolidPin } from 'react-icons/bi'
import { useTranslation } from 'react-i18next'
import ConfirmModal from '@/components/ConfirmModal'
import type { Comment } from './types'

interface CommentItemProps {
    comment: Comment
    isReply?: boolean
    isFirstReply?: boolean
    isLastReply?: boolean
    depth?: number // 留言深度：0 = 主留言，1 = 第一層回覆，2 = 第二層回覆，3 = 第三層回覆
    onReply?: (commentId: string, replyText: string, replyTo: string) => void
    onDelete?: (commentId: string) => void
    onEdit?: (commentId: string, newContent: string) => Promise<void>
    onPin?: (commentId: string, isPinned: boolean) => Promise<void>
    onLike?: (commentId: string) => Promise<void>
    userAvatar?: string | null
    isLoggedIn?: boolean
    currentUserId?: string | null
    videoOwnerId?: string | null
}

export default function CommentItem({
    comment,
    isReply = false,
    isFirstReply = false,
    isLastReply = false,
    depth = 0,
    onReply,
    onDelete,
    onEdit,
    onPin,
    onLike,
    userAvatar,
    isLoggedIn = false,
    currentUserId,
    videoOwnerId
}: CommentItemProps) {
    const { t } = useTranslation()
    const [showReplies, setShowReplies] = useState(false)
    const [showReplyInput, setShowReplyInput] = useState(false)
    const [replyText, setReplyText] = useState('')
    const [isLiked, setIsLiked] = useState(comment.isLiked || false)
    const [likes, setLikes] = useState(comment.likes || 0)
    const [menuOpen, setMenuOpen] = useState(false)
    const [hovered, setHovered] = useState(false)
    const [confirmModalOpen, setConfirmModalOpen] = useState(false)
    const [confirmClosing, setConfirmClosing] = useState(false)
    const [confirmEntering, setConfirmEntering] = useState(false)
    const [isEditing, setIsEditing] = useState(false)
    const [editText, setEditText] = useState(comment.content)
    const [isSaving, setIsSaving] = useState(false)
    const menuRef = useRef<HTMLDivElement>(null)
    const menuContainerRef = useRef<HTMLDivElement>(null)
    const confirmRef = useRef<HTMLDivElement>(null)
    const hasNestedReplies = comment.nestedReplies && comment.nestedReplies.length > 0
    const avatarSizeClass = isReply ? 'w-6 h-6' : 'w-8 h-8 md:w-9 md:h-9'
    const isOwner = currentUserId && comment.userId && currentUserId === comment.userId
    // 確保 videoOwnerId 不是字符串 "null" 或空值，並且是有效的字符串
    const validVideoOwnerId = videoOwnerId &&
        typeof videoOwnerId === 'string' &&
        videoOwnerId !== 'null' &&
        videoOwnerId !== 'undefined' &&
        videoOwnerId.trim() !== ''
        ? videoOwnerId
        : null
    const isVideoOwner = Boolean(
        currentUserId &&
        validVideoOwnerId &&
        typeof currentUserId === 'string' &&
        typeof validVideoOwnerId === 'string' &&
        currentUserId.trim() === validVideoOwnerId.trim()
    )

    const handleReplySubmit = () => {
        if (replyText.trim() && onReply && isLoggedIn) {
            onReply(comment.id, replyText.trim(), comment.author)
            setReplyText('')
            setShowReplyInput(false)
            setShowReplies(true) // 自動展開回覆列表
        }
    }

    const handleReplyClick = () => {
        setShowReplyInput(!showReplyInput)
        // 點擊回覆時不自動展開子留言列表
        // 只有在提交回覆後才展開（在 handleReplySubmit 中處理）
    }

    const handleLikeClick = async () => {
        if (!onLike || !comment.id) return

        const prevIsLiked = isLiked
        const prevLikes = likes

        // 樂觀更新
        setIsLiked(!prevIsLiked)
        setLikes(prevIsLiked ? Math.max(0, prevLikes - 1) : prevLikes + 1)

        try {
            await onLike(comment.id)
        } catch (error) {
            // 恢復原狀態
            setIsLiked(prevIsLiked)
            setLikes(prevLikes)
        }
    }

    const handleDeleteClick = () => {
        if (onDelete && comment.id) {
            setMenuOpen(false)
            // 打開確認對話框
            setConfirmEntering(true)
            setConfirmModalOpen(true)
            setConfirmClosing(false)
            requestAnimationFrame(() => requestAnimationFrame(() => setConfirmEntering(false)))
        }
    }

    const closeConfirm = () => {
        setConfirmEntering(false)
        setConfirmClosing(true)
        setTimeout(() => {
            setConfirmModalOpen(false)
            setConfirmClosing(false)
        }, 200)
    }

    const handleConfirmDelete = () => {
        if (onDelete && comment.id) {
            onDelete(comment.id)
        }
        closeConfirm()
    }

    const handleEditClick = () => {
        setIsEditing(true)
        setEditText(comment.content)
        setMenuOpen(false)
    }

    const handleCancelEdit = () => {
        setIsEditing(false)
        setEditText(comment.content)
    }

    const handleSaveEdit = async () => {
        if (!onEdit || !comment.id || !editText.trim() || editText.trim() === comment.content) {
            setIsEditing(false)
            return
        }

        setIsSaving(true)
        try {
            await onEdit(comment.id, editText.trim())
            setIsEditing(false)
        } catch (error) {
            console.error('Failed to edit comment:', error)
            // 保持編輯狀態，讓用戶重試
        } finally {
            setIsSaving(false)
        }
    }

    // 處理點擊外部關閉菜單
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            const target = event.target as HTMLElement
            if (!target || !menuOpen) return

            const isClickInsideMenu =
                menuContainerRef.current?.contains(target) ||
                menuRef.current?.contains(target)

            // 如果點擊在菜單外部，關閉菜單
            if (!isClickInsideMenu) {
                setMenuOpen(false)
            }
        }

        if (menuOpen) {
            // 使用 setTimeout 確保事件在當前事件循環之後執行，避免立即觸發
            const timeoutId = setTimeout(() => {
                document.addEventListener('mousedown', handleClickOutside, true)
            }, 0)

            return () => {
                clearTimeout(timeoutId)
                document.removeEventListener('mousedown', handleClickOutside, true)
            }
        }
    }, [menuOpen])

    return (
        <div className="group/comment relative mb-4 last:mb-0 min-w-0">
            {/* 留言內容 */}
            <div
                className="flex gap-2.5 md:gap-3 min-w-0"
                onMouseEnter={() => setHovered(true)}
                onMouseLeave={(e) => {
                    if (menuOpen) return
                    const relatedTarget = e.relatedTarget
                    if (relatedTarget && relatedTarget instanceof HTMLElement) {
                        if (relatedTarget.closest('[data-menu-container]') || relatedTarget.closest('[data-menu-trigger]')) {
                            return
                        }
                    }
                    setHovered(false)
                }}
            >
                {/* YouTube：author-thumbnail + threadline continuation */}
                <div className="relative flex-shrink-0" aria-hidden="true">
                    {comment.userId ? (
                        <Link
                            href={`/user/${encodeURIComponent(comment.userId)}`}
                            className={`${avatarSizeClass} relative rounded-full overflow-hidden bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-800 z-10 block hover:opacity-80 transition-opacity`}
                        >
                            {comment.avatar ? (
                                <Image
                                    src={comment.avatar}
                                    alt={comment.author}
                                    fill
                                    className="pointer-events-none"
                                    unoptimized
                                />
                            ) : (
                                <div className="absolute inset-0 flex items-center justify-center">
                                    <FiUser className="w-4 h-4 text-gray-400" />
                                </div>
                            )}
                        </Link>
                    ) : (
                        <div
                            className={`${avatarSizeClass} relative rounded-full overflow-hidden bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-800 z-10`}
                        >
                            {comment.avatar ? (
                                <Image
                                    src={comment.avatar}
                                    alt={comment.author}
                                    fill
                                    className="pointer-events-none"
                                    unoptimized
                                />
                            ) : (
                                <div className="absolute inset-0 flex items-center justify-center">
                                    <FiUser className="w-4 h-4 text-gray-400" />
                                </div>
                            )}
                        </div>
                    )}

                    {/* threadline/continuation：展開回覆或開啟回覆輸入框時顯示，避免 tree line 因插入輸入框而斷掉 */}
                    {((hasNestedReplies && showReplies) || showReplyInput) && (
                        <div
                            className={`absolute left-0 right-0 bottom-0 pointer-events-none ${isReply ? 'top-6' : 'top-8 md:top-9'}`}
                        >
                            <div className="absolute right-0 top-0 bottom-0 w-1/2 box-border border-l border-gray-300 dark:border-gray-700" />
                        </div>
                    )}
                </div>
                <div className="flex-1 min-w-0 relative">
                    {/* 置頂提示 */}
                    {comment.isPinned && comment.pinnedBy && (
                        <div className="mb-1.5 text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                            <BiSolidPin className="w-3.5 h-3.5 text-blue-500 dark:text-blue-400 flex-shrink-0" />
                            <span>{t('catch.comment.pinnedBy', { name: comment.pinnedBy })}</span>
                        </div>
                    )}
                    <div className="flex items-center gap-2 mb-1">
                        {comment.userId ? (
                            <Link
                                href={`/user/${encodeURIComponent(comment.userId)}`}
                                className="text-xs md:text-sm font-semibold text-black dark:text-white"
                            >
                                {comment.author}
                            </Link>
                        ) : (
                            <span className="text-xs md:text-sm font-semibold text-black dark:text-white">
                                {comment.author}
                            </span>
                        )}
                        <span className="text-xs text-gray-500 dark:text-gray-400">
                            {typeof comment.time === 'string'
                                ? comment.time
                                : (() => {
                                    const { value, unit } = comment.time
                                    if (unit === 'just') {
                                        return t('catch.comment.time.just')
                                    }
                                    const unitKey = `catch.comment.time.${unit}${value > 1 ? 's' : ''}`
                                    return t(unitKey, { count: value })
                                })()}
                            {comment.isEdited && (
                                <span className="ml-1 text-gray-400 dark:text-gray-500">({t('catch.comment.edited')})</span>
                            )}
                        </span>
                    </div>
                    {isEditing ? (
                        <div className="mb-2">
                            <textarea
                                value={editText}
                                onChange={(e) => setEditText(e.target.value)}
                                className="w-full px-3 py-2 text-xs md:text-sm text-black dark:text-gray-300 bg-gray-50 dark:bg-[#1a1c21] border border-gray-300 dark:border-gray-700 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
                                rows={3}
                                disabled={isSaving}
                                autoFocus
                            />
                            <div className="flex items-center gap-2 mt-2">
                                <button
                                    onClick={handleSaveEdit}
                                    disabled={isSaving || !editText.trim() || editText.trim() === comment.content}
                                    className="flex-shrink-0 min-w-[50px] min-h-[30px] rounded-lg text-sm font-medium border border-[#d5d7dc] dark:border-gray-700 text-gray-900 dark:text-white hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                >
                                    {isSaving ? t('catch.comment.saving') : t('catch.comment.save')}
                                </button>
                                <button
                                    onClick={handleCancelEdit}
                                    disabled={isSaving}
                                    className="flex-shrink-0 min-w-[50px] min-h-[30px] rounded-lg text-sm font-medium text-gray-900 dark:text-white hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                >
                                    {t('catch.comment.cancel')}
                                </button>
                            </div>
                        </div>
                    ) : (
                        <p className="text-xs md:text-sm text-black dark:text-gray-300 mb-2 leading-relaxed whitespace-pre-wrap break-words">
                            {comment.replyTo && depth >= 3 ? (
                                <>
                                    <span className="text-blue-500 dark:text-blue-400 font-medium">@{comment.replyTo}</span>{' '}
                                    {comment.content}
                                </>
                            ) : (
                                comment.content
                            )}
                        </p>
                    )}
                    <div className="flex items-center gap-3 md:gap-4 flex-wrap">
                        <button
                            onClick={handleLikeClick}
                            className={`flex items-center gap-1 transition-colors group flex-shrink-0 ${isLiked
                                ? 'text-red-500 dark:text-red-400'
                                : 'text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400'
                                }`}
                        >
                            {isLiked ? (
                                <FaHeart className="w-3.5 h-3.5 group-hover:scale-110 transition-transform flex-shrink-0" />
                            ) : (
                                <FaRegHeart className="w-3.5 h-3.5 group-hover:scale-110 transition-transform flex-shrink-0" />
                            )}
                            <span className="text-xs whitespace-nowrap">{likes > 0 ? likes.toLocaleString() : ''}</span>
                        </button>
                        <button
                            onClick={handleReplyClick}
                            className="text-xs text-gray-500 dark:text-gray-400 hover:text-black dark:hover:text-gray-300 transition-colors flex-shrink-0 whitespace-nowrap"
                        >
                            {t('catch.reply')}
                        </button>
                        {hasNestedReplies && (
                            <button
                                onClick={() => setShowReplies(!showReplies)}
                                className="text-xs text-gray-500 dark:text-gray-400 hover:text-black dark:hover:text-gray-300 transition-colors flex items-center gap-1 flex-shrink-0"
                            >
                                {showReplies ? (
                                    <>
                                        <FiChevronUp className="w-3.5 h-3.5 flex-shrink-0" />
                                        <span className="whitespace-nowrap">{t('catch.comment.hideReplies', { count: comment.nestedReplies?.length ?? 0 })}</span>
                                    </>
                                ) : (
                                    <>
                                        <FiChevronDown className="w-3.5 h-3.5 flex-shrink-0" />
                                        <span className="whitespace-nowrap">{t('catch.comment.showReplies', { count: comment.nestedReplies?.length ?? 0 })}</span>
                                    </>
                                )}
                            </button>
                        )}
                    </div>
                    {/* 三點菜單按鈕 */}
                    {(isOwner || isVideoOwner) && !isEditing && (
                        <div
                            ref={menuContainerRef}
                            className="absolute right-0 top-0 z-10"
                            data-menu-container
                            onMouseEnter={() => setHovered(true)}
                            onMouseLeave={(e) => {
                                if (menuOpen) return
                                const relatedTarget = e.relatedTarget
                                if (relatedTarget && relatedTarget instanceof HTMLElement) {
                                    if (relatedTarget.closest('[data-menu-container]') || relatedTarget.closest('[data-menu-trigger]')) {
                                        return
                                    }
                                }
                                setHovered(false)
                            }}
                        >
                            <button
                                type="button"
                                data-menu-trigger
                                onClick={(e) => {
                                    e.stopPropagation()
                                    setMenuOpen(!menuOpen)
                                    setHovered(true)
                                }}
                                className="p-1 rounded transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
                                style={{ opacity: (hovered || menuOpen) ? 1 : 0 }}
                                aria-label={t('room.message.moreOptions')}
                            >
                                <FiMoreVertical className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                            </button>
                            {menuOpen && (
                                <div
                                    ref={menuRef}
                                    className="absolute right-0 top-full mt-1 bg-white dark:bg-[#0c0d0e] border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50 min-w-[120px] overflow-hidden"
                                    onMouseDown={(e) => {
                                        e.stopPropagation()
                                    }}
                                >
                                    {/* 只有父留言（非回覆）才能置頂 */}
                                    {isVideoOwner && !isReply && depth === 0 && (
                                        <button
                                            type="button"
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                if (onPin && comment.id) {
                                                    onPin(comment.id, !comment.isPinned)
                                                }
                                                setMenuOpen(false)
                                            }}
                                            onMouseDown={(e) => {
                                                e.stopPropagation()
                                            }}
                                            className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-[#1a1c21] transition-colors cursor-pointer"
                                        >
                                            {comment.isPinned ? t('catch.comment.unpin') : t('catch.comment.pin')}
                                        </button>
                                    )}
                                    {isOwner && (
                                        <button
                                            type="button"
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                handleEditClick()
                                            }}
                                            onMouseDown={(e) => {
                                                e.stopPropagation()
                                            }}
                                            className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-[#1a1c21] transition-colors cursor-pointer"
                                        >
                                            {t('catch.comment.edit')}
                                        </button>
                                    )}
                                    {/* 留言作者或影片主都可以刪除留言 */}
                                    {(isOwner || isVideoOwner) && (
                                        <button
                                            type="button"
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                handleDeleteClick()
                                            }}
                                            onMouseDown={(e) => {
                                                e.stopPropagation()
                                            }}
                                            className="block w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-[#1a1c21] transition-colors cursor-pointer"
                                        >
                                            {t('catch.comment.delete')}
                                        </button>
                                    )}
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </div>

            {/* 回覆區域 - YouTube 風格的 tree layout */}
            {(showReplyInput || (hasNestedReplies && showReplies)) && (
                <div className={`min-w-0 ${isFirstReply || isLastReply || (isReply && hasNestedReplies) ? '' : 'ml-1 md:ml-[0.4rem]'}`}>
                    {/* 回覆輸入框：放進 tree layout 的同一個 gutter，避免線條斷點 */}
                    {showReplyInput && (
                        <div className="relative flex flex-row w-full min-w-0 group/reply">
                            {/* threadline - 所有層級都顯示 tree line */}
                            <div className="relative flex-shrink-0 w-6">
                                {!hasNestedReplies ? (
                                    <>
                                        {/* connection：轉彎圓角（沒回覆時固定顯示） */}
                                        <div
                                            className="absolute right-0 top-0 w-1/2 h-6 box-border border-l border-b border-gray-300 dark:border-gray-700 rounded-bl-[16px]"
                                        />
                                        {/* shadow：用背景遮掉多餘線段（不吃 hover） */}
                                        <div className="absolute bottom-0 w-full bg-white dark:bg-[#0c0d0e] h-[calc(100%-36px)] pointer-events-none" />
                                    </>
                                ) : (
                                    /* 有回覆時畫垂直延伸 */
                                    <div className="absolute right-0 top-0 bottom-0 w-1/2 box-border border-l border-gray-300 dark:border-gray-700" />
                                )}
                            </div>

                            {/* input content */}
                            <div className="flex-grow min-w-0 ml-1.5 mt-2">
                                <div className="flex items-center gap-2 md:gap-3 min-w-0">
                                    <div className="relative w-6 h-6 md:w-7 md:h-7 rounded-full overflow-hidden bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-800 flex-shrink-0">
                                        {isLoggedIn && userAvatar ? (
                                            <Image
                                                src={userAvatar}
                                                alt="User avatar"
                                                fill
                                                className="pointer-events-none"
                                                unoptimized
                                            />
                                        ) : (
                                            <div className="absolute inset-0 flex items-center justify-center">
                                                <FiUser className="w-3 h-3 text-gray-400" />
                                            </div>
                                        )}
                                    </div>
                                    <div className="flex-1 min-w-0 flex items-center gap-1 md:gap-2">
                                        <input
                                            type="text"
                                            value={replyText}
                                            onChange={(e) => {
                                                if (isLoggedIn) {
                                                    setReplyText(e.target.value)
                                                }
                                            }}
                                            onKeyDown={(e) => {
                                                if (e.key === 'Enter' && !e.shiftKey && isLoggedIn) {
                                                    e.preventDefault()
                                                    handleReplySubmit()
                                                }
                                            }}
                                            placeholder={isLoggedIn ? t('catch.comment.replyTo', { author: comment.author }) : t('catch.comment.loginRequired')}
                                            disabled={!isLoggedIn}
                                            className="flex-1 min-w-0 px-0 py-1.5 md:py-2 border-0 border-b-2 border-gray-300 dark:border-gray-600 text-xs md:text-sm text-black dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:border-b-2 focus:border-gray-500 dark:focus:border-gray-400 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed bg-transparent"
                                            autoFocus={isLoggedIn}
                                        />
                                        <button
                                            onClick={handleReplySubmit}
                                            disabled={!replyText.trim() || !isLoggedIn}
                                            className="flex-shrink-0 min-w-[50px] min-h-[30px] rounded-lg text-sm font-medium border border-[#d5d7dc] dark:border-gray-700 text-gray-900 dark:text-white hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                        >
                                            {t('catch.reply')}
                                        </button>
                                        <button
                                            onClick={() => {
                                                setShowReplyInput(false)
                                                setReplyText('')
                                            }}
                                            className="flex-shrink-0 min-w-[50px] min-h-[30px] rounded-lg text-sm font-medium   text-gray-900 dark:text-white hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                        >
                                            {t('catch.comment.cancel')}
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 子留言列表：只有在明確展開時才顯示 */}
                    {hasNestedReplies && showReplies && comment.nestedReplies && comment.nestedReplies.map((reply, index) => {
                        const isLast = index === (comment.nestedReplies?.length ?? 0) - 1
                        const nextDepth = depth + 1

                        return (
                            <div
                                key={reply.id}
                                className="relative flex flex-row w-full min-w-0 group/reply"
                            >
                                {/* threadline - 所有層級都顯示 tree line，保持視覺一致性 */}
                                <div className="relative flex-shrink-0 w-6">
                                    {/* connection：轉彎圓角（固定顯示） */}
                                    <div
                                        className="absolute right-0 top-0 w-1/2 h-6 box-border border-l border-b border-gray-300 dark:border-gray-700 rounded-bl-[16px]"
                                    />

                                    {/* continuation：垂直延續（最後一則不顯示） */}
                                    {!isLast && (
                                        <div className="absolute right-0 top-0 w-1/2 h-full box-border border-l border-gray-300 dark:border-gray-700" />
                                    )}

                                    {/* shadow：最後一則用背景遮掉多餘線段（不吃 hover） */}
                                    {isLast && (
                                        <div className="absolute bottom-0 w-full bg-white dark:bg-[#0c0d0e] h-[calc(100%-36px)] pointer-events-none" />
                                    )}
                                </div>

                                {/* sub thread content */}
                                <div className="flex-grow min-w-0 ml-1.5 mt-2">
                                    <CommentItem
                                        comment={reply}
                                        isReply={true}
                                        isFirstReply={index === 0}
                                        isLastReply={isLast}
                                        depth={nextDepth}
                                        onEdit={onEdit}
                                        onReply={onReply}
                                        onDelete={onDelete}
                                        onPin={onPin}
                                        onLike={onLike}
                                        userAvatar={userAvatar}
                                        isLoggedIn={isLoggedIn}
                                        currentUserId={currentUserId}
                                        videoOwnerId={videoOwnerId}
                                    />
                                </div>
                            </div>
                        )
                    })}
                </div>
            )}

            {/* 確認刪除對話框 */}
            <ConfirmModal
                confirmRef={confirmRef}
                isOpen={confirmModalOpen}
                title={t('catch.comment.deleteTitle')}
                message={t('catch.comment.deleteConfirm')}
                confirmText={t('catch.comment.delete')}
                cancelText={t('catch.comment.cancel')}
                onClose={closeConfirm}
                onConfirm={handleConfirmDelete}
                confirmClosing={confirmClosing}
                confirmEntering={confirmEntering}
                severity="danger"
            />
        </div>
    )
}

