import { LogOut, Edit2, CheckCircle2, ShieldCheck, Clock, XCircle, Play, Camera } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { motion } from "motion/react";
import profileIcon from "../../assets/image 5.png";
import coinImage from "../../assets/coin-star.png";
import { logout, getUserInfo } from "../../utils/auth";
import { useEffect, useState } from "react";
import { getUserProfile, getCachedProfile, saveUserProfile, getUserProfileData, type UserProfile, type ProfileChallenge, type ProfileCoinTransaction, type ProfilePost } from "../../services/profileService";
import { PostCard } from "./PostCard";
import { AvatarSelectionModal } from "./AvatarSelectionModal";
import { getProfileImageUrl, getFeedImageUrl, getVideoUrl, getAudioUrl, isImageFile, getMagicBagFileUrl, getAvatarUrl } from "../../services/feedService";
import { ImageWithFallback } from "./figma/ImageWithFallback";
import { usePageTracking } from "../../hooks/usePageTracking";
import { getMissionTypeToTopicId } from "../../utils/topicMapper";
import { useProfile } from "../context/ProfileContext";

const getStatusBadge = (status: string) => {
  if (status === "انجام شده") {
    return {
      icon: <CheckCircle2 className="w-4 h-4" />,
      text: "انجام شده",
      gradient: "linear-gradient(135deg, rgba(32, 201, 151, 0.95) 0%, rgba(16, 185, 129, 0.95) 100%)",
      border: "rgba(110, 231, 183, 0.6)",
      shadow: "0 2px 8px rgba(16, 185, 129, 0.35)",
    };
  } else if (status === "تایید شده") {
    return {
      icon: <ShieldCheck className="w-4 h-4" />,
      text: "تایید شده",
      gradient: "linear-gradient(135deg, rgba(59, 130, 246, 0.95) 0%, rgba(37, 99, 235, 0.95) 100%)",
      border: "rgba(147, 197, 253, 0.62)",
      shadow: "0 2px 8px rgba(37, 99, 235, 0.35)",
    };
  } else if (status === "در حال انجام") {
    return {
      icon: <Play className="w-4 h-4 rotate-180" />,
      text: "در حال انجام",
      gradient: "linear-gradient(135deg, rgba(255, 193, 7, 0.9) 0%, rgba(255, 160, 0, 0.9) 100%)",
      border: "rgba(255, 193, 7, 0.5)",
      shadow: "0 2px 8px rgba(255, 193, 7, 0.4)",
    };
  } else if (status === "رد شده") {
    return {
      icon: <XCircle className="w-4 h-4" />,
      text: "رد شده",
      gradient: "linear-gradient(135deg, rgba(239, 68, 68, 0.9) 0%, rgba(220, 38, 38, 0.9) 100%)",
      border: "rgba(239, 68, 68, 0.5)",
      shadow: "0 2px 8px rgba(239, 68, 68, 0.4)",
    };
  } else {
    return {
      icon: <Clock className="w-4 h-4" />,
      text: status,
      gradient: "linear-gradient(135deg, rgba(156, 163, 175, 0.9) 0%, rgba(107, 114, 128, 0.9) 100%)",
      border: "rgba(156, 163, 175, 0.5)",
      shadow: "0 2px 8px rgba(156, 163, 175, 0.4)",
    };
  }
};

export function ProfilePage() {
  const navigate = useNavigate();
  usePageTracking("پروفایل");
  const { profile, refreshProfile } = useProfile();

  const [userInfo, setUserInfo] = useState<{ Name: string; Family: string; Username: string } | null>(null);
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [isLoadingProfile, setIsLoadingProfile] = useState(true);
  const [activeTab, setActiveTab] = useState<"challenges" | "coins" | "posts">("challenges");
  const [showAvatarModal, setShowAvatarModal] = useState(false);
  const [challenges, setChallenges] = useState<ProfileChallenge[]>([]);
  const [coinTransactions, setCoinTransactions] = useState<ProfileCoinTransaction[]>([]);
  const [posts, setPosts] = useState<ProfilePost[]>([]);
  const [isLoadingData, setIsLoadingData] = useState(false);

  useEffect(() => {
    const info = getUserInfo();
    setUserInfo(info);
    
    loadProfile();
  }, []);

  useEffect(() => {
    if (profile) {
      setUserProfile(profile);
    }
  }, [profile]);

  const loadProfile = async () => {
    setIsLoadingProfile(true);
    try {
      const cachedProfile = getCachedProfile();
      if (cachedProfile) {
        setUserProfile(cachedProfile);
      }

      const profile = await getUserProfile();
      if (profile) {
        setUserProfile(profile);
      }
    } catch (error) {
      // خطاها در سطح سرویس مدیریت می‌شوند
    } finally {
      setIsLoadingProfile(false);
    }

    // بارگذاری داده‌های کامل پروفایل
    loadProfileData();
  };

  const loadProfileData = async () => {
    setIsLoadingData(true);
    try {
      const data = await getUserProfileData();
      if (data) {
        setChallenges(data.challenges);
        setCoinTransactions(data.coin_transaction);
        setPosts(data.posts);
      }
    } catch (error) {
      console.error("خطا در بارگذاری داده‌های پروفایل:", error);
    } finally {
      setIsLoadingData(false);
    }
  };

  const handleLogout = async () => {
    setIsLoggingOut(true);
    try {
      await logout();
      navigate("/login", { state: { error: "شما با موفقیت از سیستم خارج شدید" } });
    } catch (error) {
      console.error("خطا در خروج:", error);
      navigate("/login", { state: { error: "شما با موفقیت از سیستم خارج شدید" } });
    } finally {
      setIsLoggingOut(false);
    }
  };

const toPersianNumber = (num: number | null | undefined): string => {
  if (num === null || num === undefined) return "۰";
  const persianDigits = "۰۱۲۳۴۵۶۷۸۹";
  return String(num).replace(/\d/g, (digit) => persianDigits[parseInt(digit)]);
};

const toPersianDigitsInText = (value: string | null | undefined): string => {
  if (!value) return "";
  const persianDigits = "۰۱۲۳۴۵۶۷۸۹";
  return value.replace(/\d/g, (digit) => persianDigits[parseInt(digit, 10)]);
};

const getChallengeAccent = (status: string): string => {
  if (status === "انجام شده") {
    return "linear-gradient(180deg, #7EF7C5 0%, #4BCF9F 100%)";
  }
  if (status === "تایید شده") {
    return "linear-gradient(180deg, #87D6FF 0%, #5DAEFF 100%)";
  }
  if (status === "در حال انجام") {
    return "linear-gradient(180deg, #FFD994 0%, #F5B14A 100%)";
  }
  if (status === "رد شده") {
    return "linear-gradient(180deg, #FF8A94 0%, #EF4444 100%)";
  }
  return "linear-gradient(180deg, #F6A6DA 0%, #D777BE 100%)";
};

  const handleAvatarSelect = async (imageFilename: string) => {
    // imageFilename از AvatarSelectionModal نام فایل آپلود شده به سرور است
    console.log("handleAvatarSelect called with:", imageFilename);

    // ذخیره در پروفایل
    if (userProfile) {
      // به‌روزرسانی state موقت
      setUserProfile({ ...userProfile, image: imageFilename });

      // ذخیره در سرور
      try {
        const username = userProfile.username;
        const saveData = {
          WorkflowID: userProfile.user_workflowID,
          user: {
            username: username,
            name: userProfile.name,
            family: userProfile.family,
            education_level: userProfile.education_level,
            base: userProfile.base,
            image: imageFilename,
          },
        };

        console.log("Saving profile with data:", JSON.stringify(saveData));
        const result = await saveUserProfile(saveData);
        console.log("Save profile result:", result);

        // بارگذاری مجدد پروفایل از سرور
        console.log("Reloading profile from server...");
        await refreshProfile();
        console.log("Profile reloaded successfully");
      } catch (error) {
        console.error("Error saving avatar:", error);
        alert("خطا در ذخیره تصویر پروفایل");
      }
    } else {
      console.error("No userProfile available");
    }
  };

  const handleDeletePost = (postId: string) => {
    // حذف پست از لیست
    setPosts((prevPosts) => prevPosts.filter((post) => post.workflow_ID !== postId));
  };

  const navLikePanelStyle = {
    backgroundImage: `
      linear-gradient(180deg, #2E1B3D 0%, #23183E 100%),
      linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)
    `,
    backgroundOrigin: "border-box",
    backgroundClip: "padding-box, border-box",
    boxShadow:
      "0 -7px 20px rgba(7, 0, 18, 0.5), 0 6px 14px rgba(5, 2, 12, 0.26), inset 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 2px 5px rgba(255, 222, 255, 0.09), inset 0 -2px 0 rgba(12, 7, 27, 0.72), inset 0 -8px 14px rgba(8, 4, 18, 0.34), inset 0 0 0 1px rgba(255, 255, 255, 0.045), inset 0 0 0 2px rgba(17, 10, 35, 0.32)",
    backdropFilter: "blur(14px)",
    WebkitBackdropFilter: "blur(14px)",
  } as const;

  const segmentedControlStyle = {
    backgroundImage:
      "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.94) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
    backgroundOrigin: "border-box",
    backgroundClip: "padding-box, border-box",
    border: "0.5px solid transparent",
  } as const;

  return (
    <div
      className="pt-6 pb-2"
      dir="rtl"
    >
      {/* Avatar & Info Section */}
      <motion.div
        initial={{ opacity: 0, y: 15 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex flex-col items-center mb-4"
      >
        {/* Avatar with Edit Button */}
        <div className="mb-3 grid w-full grid-cols-3 items-center">
          <div className="flex justify-center">
            <motion.button
              whileTap={{ scale: isLoggingOut ? 1 : 0.92 }}
              onClick={handleLogout}
              disabled={isLoggingOut}
              aria-label={isLoggingOut ? "در حال خروج" : "خروج"}
              className="flex h-12 min-w-[92px] items-center justify-center gap-1.5 rounded-full px-3"
              style={{
                background: isLoggingOut
                  ? "linear-gradient(145deg, rgba(226, 84, 142, 0.72) 0%, rgba(196, 57, 109, 0.72) 100%)"
                  : "linear-gradient(145deg, rgba(255, 93, 143, 0.95) 0%, rgba(236, 63, 122, 0.95) 52%, rgba(207, 40, 98, 0.95) 100%)",
                boxShadow: isLoggingOut
                  ? "0 6px 12px rgba(170, 34, 79, 0.3), inset 0 1px 0 rgba(255,255,255,0.18)"
                  : "0 10px 18px rgba(207, 40, 98, 0.36), inset 0 1px 0 rgba(255,255,255,0.26)",
                border: "1px solid rgba(255, 188, 214, 0.5)",
                opacity: isLoggingOut ? 0.7 : 1,
                cursor: isLoggingOut ? "not-allowed" : "pointer",
              }}
            >
              <LogOut size={16} color="#fff" />
              <span className="text-xs font-bold text-white">{isLoggingOut ? "خروج..." : "خروج"}</span>
            </motion.button>
          </div>

          <div className="relative mx-auto">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ type: "spring", duration: 0.5 }}
              className="h-24 w-24 rounded-full p-[2px]"
              style={navLikePanelStyle}
            >
              <div className="flex h-full w-full items-center justify-center overflow-hidden rounded-full" style={navLikePanelStyle}>
                {userProfile?.image ? (
                  <ImageWithFallback
                    src={getProfileImageUrl(userProfile.image, userProfile.user_stage_id)}
                    alt="پروفایل"
                    className="h-full w-full rounded-full object-cover"
                    fallbackSrc={profileIcon}
                    style={{
                      filter: "drop-shadow(0 3px 6px rgba(138, 206, 224, 0.6))",
                    }}
                  />
                ) : (
                  <img
                    src={profileIcon}
                    alt="پروفایل"
                    className="h-[84px] w-[84px] rounded-full object-cover"
                  />
                )}
              </div>
            </motion.div>

            {/* دکمه تغییر عکس */}
            <motion.button
              whileTap={{ scale: 0.9 }}
              whileHover={{ scale: 1.1 }}
              onClick={() => setShowAvatarModal(true)}
              className="absolute bottom-0 right-0 flex h-8 w-8 items-center justify-center rounded-full"
              style={{
                background: "linear-gradient(135deg, rgba(255, 193, 7, 0.95) 0%, rgba(255, 152, 0, 0.95) 100%)",
                boxShadow: "0 3px 10px rgba(255, 193, 7, 0.6), 0 0 16px rgba(255, 193, 7, 0.4)",
                border: "2px solid rgba(255, 255, 255, 0.9)",
              }}
            >
              <Camera className="h-3.5 w-3.5" style={{ color: "#5A3800" }} />
            </motion.button>
          </div>

          <div className="flex justify-center">
            {(userProfile?.user_workflowID || !isLoadingProfile) && (
              <motion.button
                whileTap={{ scale: 0.92 }}
                onClick={() => navigate("/edit-profile")}
                aria-label={userProfile?.user_workflowID ? "ویرایش پروفایل" : "تکمیل پروفایل"}
                className="flex h-12 min-w-[92px] items-center justify-center gap-1.5 rounded-full px-3"
                style={{
                  background:
                    "linear-gradient(145deg, rgba(255, 211, 92, 0.98) 0%, rgba(255, 180, 64, 0.97) 55%, rgba(244, 148, 34, 0.96) 100%)",
                  backgroundOrigin: "border-box",
                  backgroundClip: "padding-box, border-box",
                  boxShadow: "0 10px 20px rgba(245, 158, 11, 0.32), inset 0 1px 0 rgba(255,255,255,0.4)",
                  border: "1px solid rgba(255, 236, 167, 0.55)",
                }}
              >
                <Edit2 size={16} color="#fff" />
                <span className="text-xs font-bold text-white">ویرایش</span>
              </motion.button>
            )}
          </div>
        </div>

        {/* Name */}
        <h2
          className="text-white text-lg font-bold mb-0.5"
          style={{
            textShadow: "0 3px 8px rgba(138, 206, 224, 0.6), 0 2px 4px rgba(0, 0, 0, 0.8)",
          }}
        >
          {isLoadingProfile
            ? "در حال بارگذاری..."
            : userProfile
              ? `${userProfile.name} ${userProfile.family}`
              : userInfo
                ? `${userInfo.Name} ${userInfo.Family}`
                : "کاربر گرامی"}
        </h2>



        {/* Education Info */}
        {userProfile && (
          <div style={{ color: "rgba(138, 206, 224, 0.8)" }} className="text-[10px] mb-3">
            {userProfile.education_level} - پایه {userProfile.base}
          </div>
        )}

      </motion.div>

      {/* Tab Switcher */}
      <div className="mb-3 flex rounded-2xl p-1" style={segmentedControlStyle}>
        {(
          [
            { id: "challenges", label: "سابقه چالش‌ها" },
            { id: "coins", label: "سابقه سکه‌ها" },
            { id: "posts", label: "پست‌ها" },
          ] as const
        ).map((tab) => (
          <motion.button
            key={tab.id}
            whileTap={{ scale: 0.96 }}
            onClick={() => setActiveTab(tab.id)}
            className="flex flex-1 items-center justify-center gap-1 rounded-xl py-2.5 text-[11px] font-bold transition-all duration-300"
            style={
              activeTab === tab.id
                ? {
                    background:
                      "linear-gradient(135deg, rgba(174, 117, 255, 0.96) 0%, rgba(138, 82, 238, 0.95) 46%, rgba(102, 55, 204, 0.94) 100%)",
                    color: "#FFFFFF",
                    boxShadow: "0 0 18px rgba(155,108,241,0.4)",
                  }
                : { color: "rgba(251,231,245,0.72)" }
            }
          >
            {tab.label}
          </motion.button>
        ))}
      </div>

      {/* Challenges Tab */}
      {activeTab === "challenges" && (
        <div className="space-y-3">
          {isLoadingData ? (
            <div className="text-center text-white/60 py-8">در حال بارگذاری...</div>
          ) : challenges.length === 0 ? (
            <div className="text-center text-white/60 py-8">هنوز چالشی ثبت نشده است</div>
          ) : (
            challenges.map((challenge, index) => {
              const coins = parseInt(challenge.coin_count || "0");
              const isInProgress = challenge.status === "در حال انجام";
              const statusBadge = getStatusBadge(challenge.status);
              const showEarnedCoins = !isInProgress &&
                (challenge.status === "انجام شده" || challenge.status === "تایید شده") && coins > 0;

              return (
                <motion.div
                  key={challenge.mission_done_id}
                  initial={{ opacity: 0, x: -30 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: index * 0.08, duration: 0.3 }}
                  onClick={() => {
                    if (isInProgress && challenge.mission_id) {
                      const topicId = getMissionTypeToTopicId(challenge.mission_type);
                      navigate(`/chatbot/${topicId}?missionId=${challenge.mission_id}&missionType=${encodeURIComponent(challenge.mission_type)}&continueMode=true`);
                    }
                  }}
                  className={`relative overflow-hidden rounded-2xl px-4 py-3 ${isInProgress ? "cursor-pointer" : ""}`}
                  style={{
                    backgroundImage:
                      "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.94) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
                    backgroundOrigin: "border-box",
                    backgroundClip: "padding-box, border-box",
                    border: isInProgress
                      ? "1px solid rgba(255, 205, 122, 0.58)"
                      : "0.5px solid rgba(255, 255, 255, 0.16)",
                    boxShadow: isInProgress
                      ? "0 10px 22px rgba(255, 183, 77, 0.24), inset 0 1px 0 rgba(255,255,255,0.18)"
                      : "0 10px 22px rgba(10, 6, 22, 0.28), inset 0 1px 0 rgba(255,255,255,0.14)",
                    opacity: 0.9,
                  }}
                  whileHover={isInProgress ? { scale: 1.02, y: -2 } : {}}
                  whileTap={isInProgress ? { scale: 0.98 } : {}}
                >
                  <span
                    className="absolute bottom-0 right-0 top-0 w-1.5"
                    style={{
                      background: getChallengeAccent(challenge.status),
                      opacity: 0.92,
                    }}
                  />
                  <div className="mb-1.5 flex items-start justify-between gap-2">
                    <h3 className="flex-1 text-sm font-extrabold text-[#FBE7F5]">
                      {challenge.mission_title}
                    </h3>
                    <div
                      className="flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10px] font-bold text-white"
                      style={{
                        background: statusBadge.gradient,
                        border: `1px solid ${statusBadge.border}`,
                        boxShadow: statusBadge.shadow,
                      }}
                    >
                      <span>{statusBadge.text}</span>
                      {statusBadge.icon}
                    </div>
                  </div>

                  <div className="mb-0 text-[11px] font-bold text-[#F2DFF0]/72">
                    {challenge.mission_type}
                  </div>

                  <div className="mt0 flex items-center justify-between text-[11px]">
                    <span className="text-[#F2DFF0]/72">
                      {toPersianDigitsInText(challenge.datetime1)}
                    </span>
                    <div className="flex items-center gap-2 rounded-full px-2 py-1">
                      <img src={coinImage} alt="سکه" className="h-5 w-5" />
                      <span className="text-base font-extrabold leading-none text-[#FFD873]">
                        {showEarnedCoins ? toPersianNumber(coins) : "۰"}
                      </span>
                    </div>
                  </div>
                </motion.div>
              );
            })
          )}
        </div>
      )}

      {/* Coins Tab */}
      {activeTab === "coins" && (
        <div className="space-y-3">
          {/* Total Coins Summary */}
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="mb-4 rounded-2xl p-4"
            style={{
              backgroundImage:
                "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.96) 100%), linear-gradient(120deg, rgba(250, 204, 21, 0.28) 0%, rgba(245, 158, 11, 0.24) 50%, rgba(251, 113, 133, 0.26) 100%)",
              backgroundOrigin: "border-box",
              backgroundClip: "padding-box, border-box",
              border: "1px solid transparent",
              boxShadow:
                "0 12px 24px rgba(25, 12, 46, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.18)",
            }}
          >
            <div className="text-center">
              <div className="flex items-center justify-center gap-2">
                <img src={coinImage} alt="سکه" className="h-9 w-9" />
                <span className="text-[32px] font-black leading-none text-[#FFD166]">
                  {toPersianNumber(userProfile?.coin_count)}
                </span>
              </div>
              <p className="mt-2 text-xs font-bold text-[#FFF4D6]/92">مجموع کل سکه‌ها</p>
              <div className="mx-auto mt-3 h-px w-[72%] rounded-full bg-gradient-to-r from-transparent via-[#FFD166] to-transparent opacity-85" />
            </div>
          </motion.div>

          {/* Coin History */}
          {isLoadingData ? (
            <div className="text-center text-white/60 py-8">در حال بارگذاری...</div>
          ) : coinTransactions.length === 0 ? (
            <div className="text-center text-white/60 py-8">هنوز تراکنشی ثبت نشده است</div>
          ) : (
            coinTransactions.map((item, index) => {
              const coins = parseInt(item.coin_count || "0");
              const isNegative = coins < 0;
              const absCoins = Math.abs(coins);

              return (
                <motion.div
                  key={`${item.StageID}-${index}`}
                  initial={{ opacity: 0, x: -30 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: index * 0.08, duration: 0.3 }}
                  className="relative overflow-hidden rounded-2xl px-4 py-3"
                  style={{
                    backgroundImage: isNegative
                      ? "linear-gradient(180deg, rgba(46, 24, 41, 0.9) 0%, rgba(34, 18, 34, 0.94) 100%), linear-gradient(120deg, #fb7185 0%, #ef4444 100%)"
                      : "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.96) 100%), linear-gradient(120deg, rgba(250, 204, 21, 0.22) 0%, rgba(245, 158, 11, 0.18) 42%, rgba(251, 113, 133, 0.24) 100%)",
                    backgroundOrigin: "border-box",
                    backgroundClip: "padding-box, border-box",
                    border: "1px solid transparent",
                    boxShadow: isNegative
                      ? "0 8px 16px rgba(239, 68, 68, 0.18), inset 0 1px 0 rgba(255, 221, 226, 0.2)"
                      : "0 8px 16px rgba(25, 12, 46, 0.22), inset 0 1px 0 rgba(255, 244, 200, 0.12)",
                    opacity: 0.92,
                  }}
                >
                  <span
                    className="absolute bottom-0 right-0 top-0 w-1.5"
                    style={{
                      background: isNegative
                        ? "linear-gradient(180deg, #FB7185 0%, #EF4444 100%)"
                        : "linear-gradient(180deg, #FFD76A 0%, #F59E0B 100%)",
                      opacity: 0.95,
                    }}
                  />
                  <div className="flex items-center justify-between gap-3">
                    <div className="min-w-0 flex-1">
                      <p className="line-clamp-2 text-xs font-semibold leading-5 text-[#FFF4D6]/92">
                        {item.description}
                      </p>
                      <p className="mt-1 text-[10px] text-[#FFE9A8]/60">تراکنش سکه</p>
                    </div>
                    <div
                      className="flex items-center gap-1.5 rounded-full px-2.5 py-1"
                      style={{
                        background: isNegative ? "rgba(239, 68, 68, 0.18)" : "rgba(255, 209, 102, 0.12)",
                        border: isNegative
                          ? "1px solid rgba(251, 113, 133, 0.42)"
                          : "1px solid rgba(255, 224, 140, 0.34)",
                      }}
                    >
                      <img
                        src={coinImage}
                        alt="سکه"
                        className="h-4 w-4"
                        style={{
                          filter: isNegative ? "grayscale(100%) brightness(0.8)" : "none"
                        }}
                      />
                      <span
                        className="text-sm font-extrabold leading-none"
                        style={{
                          color: isNegative ? "#FF9CA8" : "#FFD166"
                        }}
                      >
                        {isNegative ? "-" : "+"}{toPersianNumber(absCoins)}
                      </span>
                    </div>
                  </div>
                </motion.div>
              );
            })
          )}
        </div>
      )}

      {/* Posts Tab */}
      {activeTab === "posts" && (
        <div className="space-y-4">
          {isLoadingData ? (
            <div className="text-center text-white/60 py-8">در حال بارگذاری...</div>
          ) : posts.length === 0 ? (
            <div className="text-center text-white/60 py-8">هنوز پستی منتشر نشده است</div>
          ) : (
            posts.map((post, index) => {
              // تعیین نوع مدیا
              let mediaType: 'image' | 'video' | 'audio' = 'image';
              let mediaUrl: string | undefined;
              let imageUrl: string;

              if (post.film) {
                mediaType = 'video';
                mediaUrl = getVideoUrl(post.StageID);
                imageUrl = post.image ? getFeedImageUrl(post.StageID) : '';
              } else if (post.audio) {
                mediaType = 'audio';
                mediaUrl = getAudioUrl(post.StageID);
                imageUrl = post.image ? getFeedImageUrl(post.StageID) : '';
              } else {
                mediaType = 'image';
                imageUrl = post.image ? getFeedImageUrl(post.StageID) : '';
              }

              return (
                <div key={post.workflow_ID}>
                  {/* Simple Topic Label with Line */}
                  <motion.div
                    initial={{ opacity: 0, y: -5 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: index * 0.05 }}
                    className="mb-3 flex items-center gap-3"
                    dir="rtl"
                  >
                    <div className="h-[1px] flex-1" style={{ background: "rgba(138, 206, 224, 0.3)" }} />
                    <span className="text-xs text-white/60 px-2">
                      {post.mission_type}
                    </span>
                    <div className="h-[1px] flex-1" style={{ background: "rgba(138, 206, 224, 0.3)" }} />
                  </motion.div>

                  {/* Post Card */}
                  <PostCard
                    id={post.workflow_ID}
                    authorName={post.full_name}
                    authorUsername={post.user_id}
                    authorAvatar={getAvatarUrl(post.person_stage_id)}
                    image={imageUrl}
                    title={post.title}
                    caption={post.description}
                    likes={post.like_count || 0}
                    dislikes={post.dislike_count || 0}
                    comments={post.comment_count || 0}
                    timestamp=""
                    topicName={post.mission_type}
                    mediaType={mediaType}
                    mediaUrl={mediaUrl}
                    isOwnPost={true}
                    workflowID={post.workflow_ID}
                    missionType={post.mission_type}
                    initialLikeState={post.like_state || ""}
                    onDelete={handleDeletePost}
                  />
                </div>
              );
            })
          )}
        </div>
      )}

      {/* Avatar Selection Modal */}
      <AvatarSelectionModal
        isOpen={showAvatarModal}
        onClose={() => setShowAvatarModal(false)}
        onSelectAvatar={handleAvatarSelect}
        currentAvatar={userProfile?.image ? getProfileImageUrl(userProfile.image, userProfile.user_stage_id) : undefined}
      />
    </div>
  );
}
