import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "motion/react";
import { ChevronLeft } from "lucide-react";
import { ImageWithFallback } from "./figma/ImageWithFallback";
import { CommentsModal } from "./CommentsModal";
import { submitLikeDislike, deletePost, saveComment, loadComments, deleteComment, getAvatarUrl, CommentData, loadTeamMembers, TeamMember } from "../../services/feedService";
import { useProfile } from "../context/ProfileContext";
import { useNavigate } from "react-router-dom";
import reactionIconShared from "../../assets/reaction-icon-shared.svg";
import commentIconShared from "../../assets/comment-icon-shared.svg";
import avatarFallbackImage from "../../assets/image 5.png";

// PostCard با طراحی جدید - قسمت پایین بازطراحی شده + آیکون مشارکت‌کنندگان
interface PostCardProps {
  id?: string; // شناسه پست برای حذف
  authorName: string;
  authorUsername: string;
  authorAvatar: string;
  image: string; // کاور برای video/audio یا تصویر برای image
  title: string;
  caption: string;
  likes: number;
  dislikes: number;
  comments: number;
  timestamp: string;
  topicName: string;
  initialComments?: Array<{ id: string; author: string; text: string; authorAvatar?: string; timestamp?: string; likes?: number; isLiked?: boolean; replies?: any[] }>;
  mediaType?: 'image' | 'video' | 'audio';
  mediaUrl?: string; // URL فایل ویدیو یا صوت
  isOwnPost?: boolean;
  participants?: Array<{ name: string; avatar: string }>; // آیکون‌های مشارکت‌کنندگان
  initialLikeState?: "پسند" | "عدم پسند" | ""; // وضعیت لایک/دیس‌لایک از سرور
  missionType?: string; // نوع ماموریت برای ارسال لایک/دیسلایک
  workflowID?: string; // شناسه workflow برای ارسال لایک/دیسلایک
  onDelete?: (postId: string) => void; // callback برای حذف پست
  teamMemberIds?: string; // شناسه اعضای تیم با کاما جدا شده
  preloadedTeamMembers?: TeamMember[];
}

export function PostCard({
  id,
  authorName,
  authorAvatar,
  image,
  title,
  caption,
  likes: initialLikes,
  dislikes: initialDislikes,
  comments,
  timestamp,
  initialComments,
  mediaType = 'image',
  mediaUrl,
  isOwnPost = false,
  initialLikeState = "",
  missionType,
  workflowID,
  onDelete,
  teamMemberIds,
  preloadedTeamMembers,
}: PostCardProps) {
  const COMMENTS_PAGE_SIZE = 25;
  const postChromeStyle = {
    border: "1px solid transparent",
    backgroundImage:
      "linear-gradient(180deg, rgba(46, 27, 61, 0.95) 0%, rgba(35, 24, 62, 0.93) 100%), linear-gradient(120deg, rgba(124, 58, 237, 0.72) 0%, rgba(249, 115, 22, 0.56) 58%, rgba(250, 204, 21, 0.42) 100%)",
    backgroundOrigin: "border-box",
    backgroundClip: "padding-box, border-box",
    boxShadow:
      "0 -9px 24px rgba(7, 0, 18, 0.52), 0 14px 30px rgba(5, 2, 12, 0.42), 0 0 20px rgba(255, 121, 207, 0.16), inset 0 1px 0 rgba(255, 255, 255, 0.24), inset 0 2px 6px rgba(255, 222, 255, 0.1), inset 0 -2px 0 rgba(12, 7, 27, 0.72), inset 0 -10px 18px rgba(8, 4, 18, 0.36), inset 0 0 0 1px rgba(255, 255, 255, 0.06), inset 0 0 0 2px rgba(17, 10, 35, 0.34)",
    backdropFilter: "blur(10px)",
    WebkitBackdropFilter: "blur(10px)",
  } as const;
  const chipStyle = {
    backgroundImage:
      "linear-gradient(180deg, rgba(71, 39, 102, 0.9) 0%, rgba(57, 33, 92, 0.88) 100%), linear-gradient(120deg, rgba(124, 58, 237, 0.72) 0%, rgba(249, 115, 22, 0.56) 58%, rgba(250, 204, 21, 0.42) 100%)",
    backgroundOrigin: "border-box",
    backgroundClip: "padding-box, border-box",
    border: "1px solid transparent",
  } as const;
  const [likes, setLikes] = useState(initialLikes);
  const [dislikes, setDislikes] = useState(initialDislikes);
  
  // تبدیل وضعیت لایک از سرور به state داخلی
  const getInitialLikeStatus = (): "liked" | "disliked" | null => {
    if (initialLikeState === "پسند") return "liked";
    if (initialLikeState === "عدم پسند") return "disliked";
    return null;
  };
  
  const [likeStatus, setLikeStatus] = useState<"liked" | "disliked" | null>(getInitialLikeStatus());
  const [showComments, setShowComments] = useState(false);
  const [expandedCaption, setExpandedCaption] = useState(false);
  const [showParticipants, setShowParticipants] = useState(false);
  const [postComments, setPostComments] = useState<Array<{ id: string; author: string; text: string; authorAvatar?: string; timestamp?: string; likes?: number; isLiked?: boolean; replies?: any[] }>>(initialComments || []);
  const [showProfileWarning, setShowProfileWarning] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [commentsLoading, setCommentsLoading] = useState(false);
  const [commentsLoadingMore, setCommentsLoadingMore] = useState(false);
  const [commentsPage, setCommentsPage] = useState(1);
  const [commentsHasMore, setCommentsHasMore] = useState(false);
  const [teamMembers, setTeamMembers] = useState<TeamMember[]>(preloadedTeamMembers || []);
  const [loadingTeamMembers, setLoadingTeamMembers] = useState(false);

  const { isProfileComplete } = useProfile();
  const navigate = useNavigate();

  // تبدیل ساختار کامنت‌های API به ساختار داخلی با replies
  const organizeComments = (apiComments: CommentData[]) => {
    // تابع بازگشتی برای پیدا کردن تمام replies یک کامنت (در تمام سطوح)
    const findReplies = (parentId: string): any[] => {
      const directReplies = apiComments.filter(c => c.parent === parentId);
      
      return directReplies.map(reply => ({
        id: reply.comment_id,
        author: reply.full_name,
        authorAvatar: getAvatarUrl(reply.user_stage_id),
        text: reply.comment_text,
        timestamp: reply.datetimee,
        likes: 0,
        isLiked: false,
        userStageId: reply.user_stage_id,
        replies: findReplies(reply.comment_id), // بازگشتی: پیدا کردن replies این reply
      }));
    };

    // کامنت‌های اصلی (بدون parent)
    const mainComments = apiComments.filter(c => !c.parent);
    
    // ساخت ساختار سلسله مراتبی برای کامنت‌های اصلی
    return mainComments.map(comment => ({
      id: comment.comment_id,
      author: comment.full_name,
      authorAvatar: getAvatarUrl(comment.user_stage_id),
      text: comment.comment_text,
      timestamp: comment.datetimee,
      likes: 0,
      isLiked: false,
      userStageId: comment.user_stage_id,
      replies: findReplies(comment.comment_id), // پیدا کردن تمام replies (بازگشتی)
    }));
  };

  const fetchComments = async (page: number, append: boolean) => {
    if (!workflowID) return;

    if (append) {
      setCommentsLoadingMore(true);
    } else {
      setCommentsLoading(true);
    }

    try {
      const response = await loadComments(workflowID, page);
      const organized = organizeComments(response.comments);

      setCommentsHasMore(response.comments.length >= COMMENTS_PAGE_SIZE);
      setCommentsPage(page);
      setPostComments((prev) => (append ? [...prev, ...organized] : organized));
    } catch (error) {
      console.error("Error loading comments:", error);
    } finally {
      setCommentsLoading(false);
      setCommentsLoadingMore(false);
    }
  };

  // بارگذاری کامنت‌ها وقتی مودال باز می‌شود
  useEffect(() => {
    if (showComments && workflowID) {
      fetchComments(1, false);
    }
  }, [showComments, workflowID]);

  useEffect(() => {
    if (preloadedTeamMembers) {
      setTeamMembers(preloadedTeamMembers);
    }
  }, [preloadedTeamMembers]);

  // بارگذاری اعضای تیم اگر وجود دارد
  useEffect(() => {
    if (preloadedTeamMembers) return;
    if (teamMemberIds && teamMemberIds.trim() && !loadingTeamMembers) {
      setLoadingTeamMembers(true);
      loadTeamMembers(teamMemberIds)
        .then((response) => {
          if (response.success) {
            setTeamMembers(response.data);
          }
        })
        .catch((error) => {
          console.error("Error loading team members:", error);
        })
        .finally(() => {
          setLoadingTeamMembers(false);
        });
    }
  }, [teamMemberIds, loadingTeamMembers, preloadedTeamMembers]);

  const handleLike = () => {
    // بررسی تکمیل پروفایل
    if (!isProfileComplete) {
      setShowProfileWarning(true);
      return;
    }

    // Optimistic update - بروزرسانی فوری UI بدون انتظار برای سرور
    let kind: "پسند" | "عدم پسند" | "حذف";
    
    if (likeStatus === "liked") {
      // لغو لایک
      setLikes(likes - 1);
      setLikeStatus(null);
      kind = "حذف";
    } else {
      // اگر قبلاً دیس‌لایک کرده بود، ابتدا آن را کم کنیم
      if (likeStatus === "disliked") {
        setDislikes(dislikes - 1);
      }
      setLikes(likes + 1);
      setLikeStatus("liked");
      kind = "پسند";
    }
    
    // ارسال به سرور بدون انتظار برای پاسخ
    if (missionType && workflowID) {
      submitLikeDislike(kind, missionType, workflowID);
    }
  };

  const handleDislike = () => {
    // بررسی تکمیل پروفایل
    if (!isProfileComplete) {
      setShowProfileWarning(true);
      return;
    }

    // Optimistic update - بروزرسانی فوری UI بدون انتظار برای سرور
    let kind: "پسند" | "عدم پسند" | "حذف";
    
    if (likeStatus === "disliked") {
      // لغو دیس‌لایک
      setDislikes(dislikes - 1);
      setLikeStatus(null);
      kind = "حذف";
    } else {
      // اگر قبلاً لایک کرده بود، ابتدا آن را کم کنیم
      if (likeStatus === "liked") {
        setLikes(likes - 1);
      }
      setDislikes(dislikes + 1);
      setLikeStatus("disliked");
      kind = "عدم پسند";
    }
    
    // ارسال به سرور بدون انتظار برای پاسخ
    if (missionType && workflowID) {
      submitLikeDislike(kind, missionType, workflowID);
    }
  };

  const handleAddComment = (text: string, parentId?: string) => {
    // بررسی تکمیل پروفایل
    if (!isProfileComplete) {
      setShowProfileWarning(true);
      return;
    }

    // ارسال کامنت به سرور
    if (missionType && workflowID) {
      saveComment(missionType, workflowID, text, parentId || "");
      
      // بعد از ارسال کامنت، کامنت‌ها را از سرور دوباره بارگذاری می‌کنیم
      // تا comment_id واقعی دریافت شود
      setTimeout(() => {
        fetchComments(1, false);
      }, 500); // تاخیر 500ms برای اطمینان از ثبت در سرور
    }
  };

  const handleLoadMoreComments = () => {
    if (commentsLoadingMore || commentsLoading || !commentsHasMore) return;
    fetchComments(commentsPage + 1, true);
  };

  const handleDeleteComment = (commentId: string) => {
    // حذف کامنت از سرور
    deleteComment(commentId);

    // حذف بازگشتی کامنت و تمام replies آن از لیست داخلی
    const removeComment = (comments: typeof postComments): typeof postComments => {
      return comments.filter((comment) => {
        // اگر این کامنت همان کامنتی است که باید حذف شود
        if (comment.id === commentId) {
          return false; // حذف کامنت
        }
        // اگر replies دارد، آنها را نیز فیلتر کن
        if (comment.replies && comment.replies.length > 0) {
          comment.replies = removeComment(comment.replies); // بازگشتی
        }
        return true;
      });
    };

    setPostComments((prev) => removeComment(prev));
  };

  const modalComments = postComments.map((c) => ({
    id: c.id,
    author: c.author,
    authorAvatar: c.authorAvatar || avatarFallbackImage,
    text: c.text,
    timestamp: c.timestamp || "الان",
    likes: c.likes || 0,
    isLiked: c.isLiked || false,
    userStageId: c.userStageId,
    replies: c.replies || [],
  }));

  const toPersianNumber = (num: number): string => {
    const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    return num.toString().split('').map(digit => persianDigits[parseInt(digit)]).join('');
  };
  const formatRelativeTime = (value?: string): string => {
    if (!value) return "لحظاتی پیش";
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return "لحظاتی پیش";

    const diffMs = Date.now() - parsed.getTime();
    if (diffMs <= 0) return "لحظاتی پیش";

    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    const week = 7 * day;
    const month = 30 * day;

    if (diffMs < hour) return `${toPersianNumber(Math.max(1, Math.floor(diffMs / minute)))} دقیقه پیش`;
    if (diffMs < day) return `${toPersianNumber(Math.floor(diffMs / hour))} ساعت پیش`;
    if (diffMs < month) return `${toPersianNumber(Math.floor(diffMs / week))} هفته پیش`;
    return `${toPersianNumber(Math.floor(diffMs / month))} ماه پیش`;
  };
  const relativeTime = formatRelativeTime(timestamp);
  const actionCapsuleStyle = {
    border: "0.6px solid rgba(255, 205, 236, 0.085)",
    background:
      "linear-gradient(130deg, rgba(255, 255, 255, 0.035) 0%, rgba(255, 255, 255, 0.0075) 32%, rgba(160, 106, 224, 0.05) 100%), linear-gradient(180deg, rgba(88, 52, 126, 0.09) 0%, rgba(48, 31, 85, 0.075) 100%)",
    boxShadow:
      "inset 0 1px 0 rgba(255, 255, 255, 0.07), inset 0 -1px 0 rgba(45, 24, 70, 0.13), inset 0 0 16px rgba(188, 131, 255, 0.04), 0 8px 22px rgba(8, 3, 18, 0.085)",
    backdropFilter: "blur(12px) saturate(108%)",
    WebkitBackdropFilter: "blur(12px) saturate(108%)",
  } as const;
  const likeActiveCapsuleStyle = {
    border: "0.6px solid rgba(255, 140, 220, 0.38)",
    background:
      "linear-gradient(130deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.01) 32%, rgba(255, 121, 207, 0.12) 100%), linear-gradient(180deg, rgba(88, 52, 126, 0.16) 0%, rgba(48, 31, 85, 0.13) 100%)",
    boxShadow:
      "inset 0 1px 0 rgba(255, 255, 255, 0.1), inset 0 -1px 0 rgba(45, 24, 70, 0.16), inset 0 0 18px rgba(255, 121, 207, 0.16), 0 0 14px rgba(255, 121, 207, 0.2)",
  } as const;
  const dislikeActiveCapsuleStyle = {
    border: "0.6px solid rgba(255, 140, 220, 0.38)",
    background:
      "linear-gradient(130deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.01) 32%, rgba(255, 121, 207, 0.12) 100%), linear-gradient(180deg, rgba(88, 52, 126, 0.16) 0%, rgba(48, 31, 85, 0.13) 100%)",
    boxShadow:
      "inset 0 1px 0 rgba(255, 255, 255, 0.1), inset 0 -1px 0 rgba(45, 24, 70, 0.16), inset 0 0 18px rgba(255, 121, 207, 0.16), 0 0 14px rgba(255, 121, 207, 0.2)",
  } as const;
  const collaboratorCapsuleStyle = {
    border: "0.6px solid rgba(255, 205, 236, 0.085)",
    background:
      "linear-gradient(130deg, rgba(255, 255, 255, 0.035) 0%, rgba(255, 255, 255, 0.0075) 32%, rgba(160, 106, 224, 0.05) 100%), linear-gradient(180deg, rgba(88, 52, 126, 0.09) 0%, rgba(48, 31, 85, 0.075) 100%)",
    boxShadow:
      "inset 0 1px 0 rgba(255, 255, 255, 0.07), inset 0 -1px 0 rgba(45, 24, 70, 0.13), inset 0 0 16px rgba(188, 131, 255, 0.04), 0 8px 22px rgba(8, 3, 18, 0.085)",
    backdropFilter: "blur(12px) saturate(108%)",
    WebkitBackdropFilter: "blur(12px) saturate(108%)",
  } as const;

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="mb-4"
    >
      <div className="feed-panel rounded-3xl overflow-hidden" style={postChromeStyle}>
        <div className="flex items-start px-4 pt-4 pb-2" dir="rtl">
          <div className="flex items-start gap-2">
            <div
              className="w-12 h-12 rounded-full overflow-hidden flex-shrink-0"
              style={{
                border: "1px solid rgba(255, 170, 224, 0.82)",
                boxShadow: "0 0 12px rgba(255, 121, 207, 0.35)",
              }}
            >
              <ImageWithFallback
                src={authorAvatar}
                alt={authorName}
                className="w-full h-full object-cover"
                fallbackSrc={avatarFallbackImage}
              />
            </div>
            <div className="pt-0">
              <h3 className="font-bold text-[18px] leading-6 text-right text-white">{authorName}</h3>
              <p className="text-[11px] font-normal text-right text-white/75">{relativeTime}</p>
            </div>
          </div>
        </div>

        <div className="px-4 pb-3" dir="rtl">
          <h3 className="font-semibold mb-1 text-[14px]" style={{ 
            color: "#ffd6f0", 
            textShadow: "0 2px 4px rgba(0, 0, 0, 0.6)"
          }}>
            {title}
          </h3>
          <p
            className="text-white leading-relaxed text-[12px]"
            style={{
              display: "-webkit-box",
              WebkitLineClamp: expandedCaption ? "unset" : 4,
              WebkitBoxOrient: "vertical",
              overflow: "hidden",
            }}
          >
            {caption}
          </p>
          {caption.length > 150 && (
            <button
              onClick={() => setExpandedCaption(!expandedCaption)}
              className="text-xs mt-1"
              style={{ color: "#ff9be0" }}
            >
              {expandedCaption ? "کمتر" : "بیشتر"}
            </button>
          )}
        </div>

        <div className="px-4 pb-3">
          <div
            className="relative w-full rounded-3xl overflow-hidden" 
            style={{ 
              background: "linear-gradient(180deg, rgba(47, 27, 66, 0.92) 0%, rgba(34, 22, 58, 0.9) 100%)",
              boxShadow: "0 4px 16px rgba(0, 0, 0, 0.3), 0 0 20px rgba(255, 121, 207, 0.1)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              backgroundColor: "rgba(10, 20, 35, 0.5)",
            }}
          >
            {mediaType === 'video' ? (
              <video
                src={mediaUrl}
                poster={image} // کاور ویدیو
                controls
                playsInline
                className="w-full h-auto cursor-pointer block"
                style={{
                  objectFit: "contain",
                  display: "block",
                }}
              />
            ) : mediaType === 'audio' ? (
              <div className="w-full">
                {/* کاور صوت */}
                {image && (
                  <ImageWithFallback
                    src={image}
                    alt="کاور صوت"
                    className="w-full h-auto max-h-[600px] mb-4"
                    style={{
                      objectFit: "contain",
                    }}
                  />
                )}
                {/* پلیر صوت */}
                <audio
                  src={mediaUrl}
                  controls
                  className="w-full"
                  style={{
                    background: "rgba(255, 255, 255, 0.1)",
                    borderRadius: "12px",
                  }}
                />
              </div>
            ) : (
              <ImageWithFallback
                src={image}
                alt="پست"
                className="w-full h-auto max-h-[600px]"
                style={{
                  objectFit: "contain",
                }}
              />
            )}
          </div>
        </div>

        <div className="mx-[14px] mb-[10px] mt-1" dir="rtl">
          <div className="flex items-center justify-between gap-2">
            <div className="flex items-center gap-1">
              <motion.button
                whileTap={{ scale: 0.9 }}
                onClick={handleLike}
                className="flex items-center gap-2 px-3 py-1.5 rounded-full transition-all min-w-[30px] justify-center"
                style={likeStatus === "liked" ? { ...actionCapsuleStyle, ...likeActiveCapsuleStyle } : actionCapsuleStyle}
              >
                <img
                  src={reactionIconShared}
                  alt=""
                  className="w-5 h-5 object-contain"
                  style={{
                    filter:
                      likeStatus === "liked"
                        ? "saturate(1.28) hue-rotate(-8deg) brightness(1.08) drop-shadow(0 0 6px rgba(255, 121, 207, 0.6))"
                        : "none",
                    transition: "filter 60ms linear",
                  }}
                />
                <span
                  className="text-sm font-bold min-w-[20px] text-center"
                  style={{ 
                    color: "#FFFFFF",
                    textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  {toPersianNumber(likes)}
                </span>
              </motion.button>

              <motion.button
                whileTap={{ scale: 0.9 }}
                onClick={handleDislike}
                className="flex items-center gap-2 px-3 py-1.5 rounded-full transition-all min-w-[30px] justify-center"
                style={likeStatus === "disliked" ? { ...actionCapsuleStyle, ...dislikeActiveCapsuleStyle } : actionCapsuleStyle}
              >
                <img
                  src={reactionIconShared}
                  alt=""
                  className="w-5 h-5 object-contain rotate-180"
                  style={{
                    filter:
                      likeStatus === "disliked"
                        ? "saturate(1.28) hue-rotate(-8deg) brightness(1.08) drop-shadow(0 0 6px rgba(255, 121, 207, 0.6))"
                        : "none",
                    transition: "filter 60ms linear",
                  }}
                />
                <span
                  className="text-sm font-bold min-w-[20px] text-center"
                  style={{ 
                    color: "#FFFFFF",
                    textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  {toPersianNumber(dislikes)}
                </span>
              </motion.button>
            </div>

            <div className="flex items-center">
              <motion.button
                whileTap={{ scale: 0.9 }}
                onClick={() => setShowComments(!showComments)}
                className="flex items-center gap-2 px-3 py-1.5 rounded-full transition-all min-w-[30px] justify-center"
                style={actionCapsuleStyle}
              >
              <img
                src={commentIconShared}
                alt=""
                className="w-5 h-5 object-contain"
                style={{
                  filter: showComments
                    ? "drop-shadow(0 0 6px rgba(255, 121, 207, 0.6))"
                    : "none",
                  transition: "filter 120ms ease",
                }}
              />
              <span
                className="text-sm font-bold min-w-[20px] text-center"
                style={{
                  color: "#FFFFFF",
                  textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)",
                }}
              >
                {toPersianNumber(comments)}
              </span>
              </motion.button>
            </div>
          </div>
        </div>

        {teamMembers.length > 0 && (
          <div className="mx-[14px] mb-[16px] rounded-full px-4 py-2.5 flex items-center justify-between" style={collaboratorCapsuleStyle} dir="rtl">
            <button type="button" onClick={() => setShowParticipants(true)} className="flex items-center gap-2">
              <div className="flex -space-x-2" dir="ltr">
                {teamMembers.slice(0, 3).map((member) => (
                  <div
                    key={member.StageID}
                    className="w-8 h-8 rounded-full overflow-hidden"
                    style={{
                      boxShadow: "0 2px 8px rgba(0, 0, 0, 0.28)",
                    }}
                  >
                    <ImageWithFallback
                      src={getAvatarUrl(member.StageID.toString())}
                      alt={member.full_name}
                      className="w-full h-full object-cover"
                      fallbackSrc={avatarFallbackImage}
                    />
                  </div>
                ))}
                {teamMembers.length > 3 && (
                  <div
                    className="w-8 h-8 rounded-full flex items-center justify-center text-[11px] font-bold text-white"
                    style={{ background: "rgba(255, 121, 207, 0.35)" }}
                  >
                    +{toPersianNumber(teamMembers.length - 3)}
                  </div>
                )}
              </div>
              <div className="text-[#ffd6f0] text-[14px] whitespace-nowrap">همکاری‌کنندگان</div>
            </button>
            <ChevronLeft size={18} color="#ffd6f0" />
          </div>
        )}
      </div>

      <CommentsModal
        isOpen={showComments}
        onClose={() => setShowComments(false)}
        comments={modalComments}
        postAuthor={authorName}
        onAddComment={handleAddComment}
        onDeleteComment={handleDeleteComment}
        hasMoreComments={commentsHasMore}
        isLoadingMoreComments={commentsLoadingMore}
        onLoadMoreComments={handleLoadMoreComments}
      />

      {/* Modal مشارکت‌کنندگان */}
      <AnimatePresence>
        {showParticipants && teamMembers.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4"
            style={{ backgroundColor: "rgba(0, 0, 0, 0.7)" }}
            onClick={() => setShowParticipants(false)}
          >
            <motion.div
              initial={{ scale: 0.9, y: 20 }}
              animate={{ scale: 1, y: 0 }}
              exit={{ scale: 0.9, y: 20 }}
              onClick={(e) => e.stopPropagation()}
              className="w-full max-w-md rounded-3xl overflow-hidden"
              style={{
                background: "linear-gradient(180deg, rgba(46, 27, 61, 0.98) 0%, rgba(35, 24, 62, 0.98) 100%)",
                border: "1px solid rgba(255, 170, 224, 0.4)",
                boxShadow: "0 20px 60px rgba(0, 0, 0, 0.5)",
                backdropFilter: "blur(14px)",
                WebkitBackdropFilter: "blur(14px)",
                maxHeight: "80vh",
              }}
            >
              {/* Header */}
              <div
                className="px-6 py-4 border-b"
                style={{ borderColor: "rgba(255, 170, 224, 0.2)" }}
              >
                <h3
                  className="text-lg font-bold text-center"
                  style={{
                    color: "#FFFFFF",
                    textShadow: "0 2px 4px rgba(0, 0, 0, 0.3)"
                  }}
                >
                  مشارکت‌کنندگان ({toPersianNumber(teamMembers.length)} نفر)
                </h3>
              </div>

              {/* لیست مشارکت‌کنندگان */}
              <div className="overflow-y-auto p-4" style={{ maxHeight: "60vh" }}>
                <div className="space-y-3">
                  {teamMembers.map((member, index) => (
                    <motion.div
                      key={member.StageID}
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: index * 0.05 }}
                      className="flex items-center gap-3 p-3 rounded-2xl"
                      style={{
                        background: "linear-gradient(135deg, rgba(85, 48, 121, 0.4) 0%, rgba(48, 31, 85, 0.4) 100%)",
                        border: "1px solid rgba(255, 170, 224, 0.2)",
                      }}
                      dir="rtl"
                    >
                      <div
                        className="w-12 h-12 rounded-full overflow-hidden flex-shrink-0"
                        style={{
                          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.3)",
                        }}
                      >
                        <ImageWithFallback
                          src={getAvatarUrl(member.StageID.toString())}
                          alt={member.full_name}
                          className="w-full h-full object-cover"
                          fallbackSrc={avatarFallbackImage}
                        />
                      </div>
                      <div className="flex-1">
                        <h4
                          className="font-bold text-base"
                          style={{
                            color: "#FFFFFF",
                            textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)"
                          }}
                        >
                          {member.full_name}
                        </h4>
                      </div>
                    </motion.div>
                  ))}
                </div>
              </div>

              {/* دکمه بستن */}
              <div className="px-6 py-4">
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => setShowParticipants(false)}
                  className="w-full py-3 rounded-full font-bold text-white"
                  style={{
                    background: "linear-gradient(135deg, rgba(255, 121, 207, 0.9) 0%, rgba(124, 58, 237, 0.85) 100%)",
                    boxShadow: "0 4px 12px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  بستن
                </motion.button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Modal اخطار تکمیل پروفایل */}
      <AnimatePresence>
        {showProfileWarning && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4"
            style={{ backgroundColor: "rgba(0, 0, 0, 0.7)" }}
            onClick={() => setShowProfileWarning(false)}
          >
            <motion.div
              initial={{ scale: 0.9, y: 20 }}
              animate={{ scale: 1, y: 0 }}
              exit={{ scale: 0.9, y: 20 }}
              onClick={(e) => e.stopPropagation()}
              className="w-full max-w-md rounded-3xl overflow-hidden"
              style={{
                background: "linear-gradient(180deg, rgba(32, 76, 106, 0.98) 0%, rgba(20, 40, 60, 0.98) 100%)",
                border: "2px solid rgba(138, 206, 224, 0.3)",
                boxShadow: "0 20px 60px rgba(0, 0, 0, 0.5)",
                maxHeight: "80vh",
              }}
            >
              {/* Header */}
              <div 
                className="px-6 py-4 border-b"
                style={{ borderColor: "rgba(138, 206, 224, 0.2)" }}
              >
                <h3 
                  className="text-lg font-bold text-center"
                  style={{ 
                    color: "#FFFFFF",
                    textShadow: "0 2px 4px rgba(0, 0, 0, 0.3)"
                  }}
                >
                  اخطار
                </h3>
              </div>

              {/* متن اخطار */}
              <div className="p-6" dir="rtl">
                <p 
                  className="text-base text-center leading-relaxed"
                  style={{ 
                    color: "#FFFFFF",
                    textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)"
                  }}
                >
                  برای لایک، دیس‌لایک یا نظر دادن به پست‌ها، ابتدا باید پروفایل خود را تکمیل کنید.
                </p>
              </div>

              {/* دکمه‌های عملیاتی */}
              <div className="px-6 py-4 flex gap-3" dir="rtl">
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => setShowProfileWarning(false)}
                  className="flex-1 py-3 rounded-full font-bold text-white"
                  style={{
                    background: "linear-gradient(135deg, rgba(96, 96, 96, 0.9) 0%, rgba(64, 64, 64, 0.9) 100%)",
                    boxShadow: "0 4px 12px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  بستن
                </motion.button>
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => {
                    setShowProfileWarning(false);
                    navigate("/profile");
                  }}
                  className="flex-1 py-3 rounded-full font-bold text-white"
                  style={{
                    background: "linear-gradient(135deg, #FFB800 0%, #FF9500 100%)",
                    boxShadow: "0 4px 12px rgba(255, 165, 0, 0.4)",
                  }}
                >
                  تکمیل پروفایل
                </motion.button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Modal تایید حذف پست */}
      <AnimatePresence>
        {showDeleteConfirm && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4"
            style={{ backgroundColor: "rgba(0, 0, 0, 0.7)" }}
            onClick={() => setShowDeleteConfirm(false)}
          >
            <motion.div
              initial={{ scale: 0.9, y: 20 }}
              animate={{ scale: 1, y: 0 }}
              exit={{ scale: 0.9, y: 20 }}
              onClick={(e) => e.stopPropagation()}
              className="w-full max-w-md rounded-3xl overflow-hidden"
              style={{
                background: "linear-gradient(180deg, rgba(32, 76, 106, 0.98) 0%, rgba(20, 40, 60, 0.98) 100%)",
                border: "2px solid rgba(138, 206, 224, 0.3)",
                boxShadow: "0 20px 60px rgba(0, 0, 0, 0.5)",
                maxHeight: "80vh",
              }}
            >
              {/* Header */}
              <div 
                className="px-6 py-4 border-b"
                style={{ borderColor: "rgba(138, 206, 224, 0.2)" }}
              >
                <h3 
                  className="text-lg font-bold text-center"
                  style={{ 
                    color: "#FFFFFF",
                    textShadow: "0 2px 4px rgba(0, 0, 0, 0.3)"
                  }}
                >
                  تایید حذف
                </h3>
              </div>

              {/* متن تایید حذف */}
              <div className="p-6" dir="rtl">
                <p 
                  className="text-base text-center leading-relaxed"
                  style={{ 
                    color: "#FFFFFF",
                    textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)"
                  }}
                >
                  آیا مطمئن هستید که می‌خواهید این پست را حذف کنید؟
                </p>
              </div>

              {/* دکمه‌های عملیاتی */}
              <div className="px-6 py-4 flex gap-3" dir="rtl">
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => setShowDeleteConfirm(false)}
                  className="flex-1 py-3 rounded-full font-bold text-white"
                  style={{
                    background: "linear-gradient(135deg, rgba(96, 96, 96, 0.9) 0%, rgba(64, 64, 64, 0.9) 100%)",
                    boxShadow: "0 4px 12px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  انصراف
                </motion.button>
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => {
                    if (missionType && workflowID) {
                      deletePost(missionType, workflowID);
                    }
                    setShowDeleteConfirm(false);
                    if (onDelete && id) {
                      onDelete(id);
                    }
                  }}
                  className="flex-1 py-3 rounded-full font-bold text-white"
                  style={{
                    background: "linear-gradient(135deg, #ef4444 0%, #dc2626 100%)",
                    boxShadow: "0 4px 12px rgba(239, 68, 68, 0.4)",
                  }}
                >
                  حذف
                </motion.button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}
