"use client";
import React, { useEffect, useState, useRef, useCallback } from "react";
import Image from "next/image";
import Cookies from "js-cookie";
import useApiPost from "../../hooks/postData";
import toast from "react-hot-toast";
import ReportPost from "./ReportPost";
import { useRouter } from "next/navigation";
import PostDetail from "../../Explore/Post_Detail";
import ReelDetail from "../../Explore/Reel_Comment";
import { useAppDispatch, useAppSelector } from "@/app/hooks/hooks";
import { showModal, hideModal } from "@/app/store/Slice/modalSlice";
import TaggedPeopleInPostList from "./TaggedPeopleInPostList";
import { setTaggedPostId } from "@/app/store/Slice/TaggedPeopleListPost";
import { ClipLoader } from "react-spinners";
import ShimmerPost from "./ShimmerHome";
import timeAgo from "./formatTime";
import { setPostId } from "@/app/store/Slice/PostIdSlice";
import DeletePost from "./DeletePost";
import { PostReel } from "@/app/types/GetAllPostReels";
import SharePostUsersList from "./SharePost";
import { setUserId } from "@/app/store/Slice/SetUserIdForChatOpen";
import { setHashtagName } from "@/app/store/Slice/hashtagIdSlice";
import TextTranslate from "@/app/utils/TextTranslate";
import LikeModal from "../../Explore/LikeModal";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";

function Post() {
  const token = Cookies.get("Snapta_auth_token");
  const { postData } = useApiPost();
  const [openDelete, setOpenDelete] = useState<string | null>(null);
  const [openReport, setOpenReport] = useState<string | null>(null);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [selectedPost, setSelectedPost] = useState<{
    postId: string;
    images: string[];
  } | null>(null);
  const [items, setItems] = useState<any[]>([]);
  const [pageNo, setPageNo] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [isMuted, setIsMuted] = useState(true); // Single mute state for all videos
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);
  const postRefs = useRef<(HTMLElement | null)[]>([]); //for view count increase
  const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const selectedPostId = useAppSelector((state) => state.SelectedPostId.id);
  const isAddPostModalVisible = useAppSelector(
    (state) => state.modals.AddPostModal
  );
  const isReelDetailOpen = useAppSelector((state) => state.modals.ReelDetail);
  const [isInitialLoading, setIsInitialLoading] = useState(true);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const dispatch = useAppDispatch();
  const router = useRouter();
  const isRefetchingAfterPost = useRef(false);
  const isFetchingRef = useRef(false);
  const isLikeModalVisible = useAppSelector(
    (state) => state.modals.LikeModal
  );
  // Refetch posts after adding new post
  useEffect(() => {
    if (!isAddPostModalVisible && isRefetchingAfterPost.current) {
      fetchData(1, true);
      isRefetchingAfterPost.current = false;
    }

    if (isAddPostModalVisible) {
      isRefetchingAfterPost.current = true;
    }
  }, [isAddPostModalVisible]);

  const fetchData = async (page: number, isRefetch = false) => {
    if (isFetchingRef.current) return;
    isFetchingRef.current = true;

    if (isRefetch) {
      setIsInitialLoading(true);
    } else {
      setIsFetchingMore(true);
    }

    try {
      const res = await postData("/get_all_latest_reel_and_post_pagination", {
        page_no: page,
      });

      if (res?.status === "success") {
        const newItems = res.recent_content || [];

        if (isRefetch || page === 1) {
          setItems(newItems);
        } else {
          setItems((prev) => [...prev, ...newItems]);
        }

        const currentPage = res.current_page || page;
        const lastPage = res.last_page || currentPage;
        setPageNo(currentPage);
        setHasMore(currentPage < lastPage);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      isFetchingRef.current = false;
      setIsInitialLoading(false);
      setIsFetchingMore(false);
    }
  };

function handleHashtagRoute(name: string) {
  // Remove any # symbol if present and encode for URL
  const cleanHashtag = name.replace(/^#/, '');
  dispatch(setHashtagName({ hashtagName: cleanHashtag }));
  router.push(`/Hashtag/${encodeURIComponent(cleanHashtag)}`);
}
  // to setHahstag name
const renderTextWithHashtags = (text: string) => {
  const parts = text.split(/(#\w+)/g); // keeps hashtags

  return parts.map((part, i) => {
    if (/#\w+/.test(part)) {
      return (
        <span
          key={i}
          onClick={() => handleHashtagRoute(part.slice(1))} // Remove # and pass hashtag name
          className="text-[#452B7A] dark:text-[var(--text-secondary)] cursor-pointer hover:underline"
        >
          {part}
        </span>
      );
    } else {
      return <span key={i}>{part}</span>;
    }
  });
};

  // Fetch first page on mount
  useEffect(() => {
    fetchData(1);
  }, []);

  // Scroll handler for pagination
  const handleScroll = useCallback(() => {
    const scrollPosition = window.innerHeight + window.scrollY;
    const threshold = document.documentElement.scrollHeight - 300;

    if (
      scrollPosition >= threshold &&
      !isFetchingMore &&
      hasMore &&
      !isInitialLoading
    ) {
      fetchData(pageNo + 1);
    }
  }, [isFetchingMore, hasMore, pageNo, isInitialLoading]);

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [handleScroll]);

  // IntersectionObserver for video visibility
  const viewedPostIdsRef = useRef<Set<string>>(new Set());

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        let found = false;
        entries.forEach((entry) => {
           const index = Number((entry.target as HTMLElement).dataset.index);
          const isVideo = videoRefs.current[index] instanceof HTMLVideoElement;

          // To view reel
          const postId = items[index]?.post_id;

          // Call view_reel API once
          if (
            entry.isIntersecting &&
            entry.intersectionRatio >= 0.8 &&
            postId &&
            !viewedPostIdsRef.current.has(postId)
          ) {
            viewedPostIdsRef.current.add(postId);
            postData("/view_reel", { reel_id: postId });
          }

          // for audio control of reel
          if (
            entry.isIntersecting &&
            entry.intersectionRatio >= 0.8 &&
            isVideo
          ) {
            found = true;
            setActiveIndex(index);
          }
        });

        if (!found) {
          setActiveIndex(null);
        }
      },
      { threshold: 0.8 }
    );

    postRefs.current.forEach((ref) => {
      if (ref) observer.observe(ref);
    });

    return () => {
      postRefs.current.forEach((ref) => {
        if (ref) observer.unobserve(ref);
      });
    };
  }, [items]);

  // Control video playback and audio
  useEffect(() => {
    videoRefs.current.forEach((ref, index) => {
      if (!ref || !(ref instanceof HTMLVideoElement)) return;

      if (index === activeIndex && !isReelDetailOpen) {
        ref.play().catch(() => { });
        ref.muted = isMuted;
        ref.volume = isMuted ? 0 : 1.0;
      } else {
        ref.pause();
        ref.muted = true;
        ref.volume = 0;
      }
    });
  }, [activeIndex, isMuted, isReelDetailOpen]);

  // Handle mute/unmute toggle
  const handleMuteToggle = () => {
    setIsMuted((prev) => {
      const newMuted = !prev;
      if (activeIndex !== null) {
        const video = videoRefs.current[activeIndex];
        if (video instanceof HTMLVideoElement) {
          video.muted = newMuted;
          video.volume = newMuted ? 0 : 1.0;
        }
      }
      return newMuted;
    });
  };

  // Handle mute toggle from ReelDetail
  const handlePopupMuteToggle = (isMuted: boolean) => {
    setIsMuted(isMuted);
  };

  // Close report/delete dialogs
  const reportRef = useRef<HTMLDivElement>(null);
  const deleteRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        (reportRef.current &&
          !reportRef.current.contains(event.target as Node)) ||
        (deleteRef.current && !deleteRef.current.contains(event.target as Node))
      ) {
        setOpenReport(null);
        setOpenDelete(null);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

 const handleUsernameClick = (username: string) => {
  router.push(`/Profile/${username}`);
};
  const [savedPosts, setSavedPosts] = useState<PostReel[]>([]);

 const handleLikePost = async (postId: string) => {
    // 1. Find the current state to determine the message
    const targetItem = items.find((r) => r.post_id === postId);
    if (!targetItem) return;

    const isCurrentlyLiked = targetItem.is_liked === "1";
    const successMessage = isCurrentlyLiked ? "Post Unliked" : "Post Liked";
    
    // Dynamic subline for likes
    const successSubline = isCurrentlyLiked 
      ? "Like removed from this post." 
      : "You liked this post.";

    // 2. Optimistic UI Update
    setItems((prev) =>
      prev.map((r) =>
        r.post_id === postId
          ? {
            ...r,
            is_liked: r.is_liked === "1" ? "0" : "1",
            total_like:
              r.is_liked === "1"
                ? String(Math.max(0, Number(r.total_like) - 1))
                : String(Number(r.total_like) + 1),
          }
          : r
      )
    );

    try {
      // 3. API Call
      await postData("/like_post", { post_id: postId });

      // 4. Show custom Snapta Success Toast with subline
      showSuccessToast(successMessage, successSubline);

    } catch (error) {
      // 5. Revert UI on failure (Rollback)
      setItems((prev) =>
        prev.map((r) =>
          r.post_id === postId
            ? {
              ...r,
              is_liked: isCurrentlyLiked ? "1" : "0",
              total_like: targetItem.total_like,
            }
            : r
        )
      );

      // Show custom Snapta Error Toast with subline
      showErrorToast("Failed to update like", "Something went wrong.");
    }
  };

  const handleBookmarkPost = async (postId: string, postType: string) => {
    // 1. Find the target item to determine current status
    const targetItem = items.find((r) => r.post_id === postId);
    if (!targetItem) return;

    const isCurrentlyBookmarked = targetItem.is_bookmark === "1";
    const successMessage = isCurrentlyBookmarked ? "Post Unsaved" : "Post Saved";

    // Dynamic subline for bookmarks
    const successSubline = isCurrentlyBookmarked 
      ? "Removed from your bookmarks." 
      : "Added to your bookmarks.";

    // 2. Optimistic UI Update
    setItems((prev) =>
      prev.map((r) =>
        r.post_id === postId
          ? {
            ...r,
            is_bookmark: r.is_bookmark === "1" ? "0" : "1",
          }
          : r
      )
    );

    try {
      // 3. API Call
      await postData("/bookmark_post", { post_id: postId, type: postType });

      // 4. Show custom Snapta Success Toast with subline
      showSuccessToast(successMessage, successSubline);

    } catch (error) {
      // 5. Revert UI on failure (Rollback)
      setItems((prev) =>
        prev.map((r) =>
          r.post_id === postId
            ? {
              ...r,
              is_bookmark: isCurrentlyBookmarked ? "1" : "0",
            }
            : r
        )
      );

      // Show custom Snapta Error Toast with subline
      showErrorToast("Failed to update bookmark", "Something went wrong.");
    }
  };

  const MyUserId = Cookies.get("USERID");

  const handlePopup = (postId: string, userId: number) => {
    if (userId === Number(MyUserId)) {
      setOpenDelete((prev) => (prev === postId ? null : postId));
      setOpenReport(null);
    } else {
      setOpenReport((prev) => (prev === postId ? null : postId));
      setOpenDelete(null);
    }
  };

const handleLikeReel = async (reelId: string) => {
    // 1. Find the target reel to check current status
    const targetReel = items.find((r) => r.post_id === reelId);
    if (!targetReel) return;

    const isCurrentlyLiked = targetReel.is_liked === "1";
    const successMessage = isCurrentlyLiked ? "Reel Unliked" : "Reel Liked";
    
    // Dynamic subline for reel likes
    const successSubline = isCurrentlyLiked 
      ? "Like removed from this reel." 
      : "You liked this reel.";

    // 2. Optimistic UI Update
    setItems((prev) =>
      prev.map((r) =>
        r.post_id === reelId
          ? {
            ...r,
            is_liked: r.is_liked === "1" ? "0" : "1",
            total_like:
              r.is_liked === "1"
                ? String(Math.max(0, Number(r.total_like) - 1))
                : String(Number(r.total_like) + 1),
          }
          : r
      )
    );

    try {
      // 3. API Call
      await postData("/like_reel", { reel_id: reelId });

      // 4. Show custom Snapta Success Toast with subline
      showSuccessToast(successMessage, successSubline);

    } catch (error) {
      // 5. Revert UI on failure (Rollback)
      setItems((prev) =>
        prev.map((r) =>
          r.post_id === reelId
            ? {
              ...r,
              is_liked: isCurrentlyLiked ? "1" : "0",
              total_like: targetReel.total_like,
            }
            : r
        )
      );

      // Show custom Snapta Error Toast with subline
      showErrorToast("Failed to update like", "Something went wrong.");
    }
  };

  const [selectedVideo, setSelectedVideo] = useState<{
    postId: string;
    url: string;
    index: number;
  } | null>(null);

  const handleImageClick = (postId: string, images: string[]) => {
    setSelectedPost({ postId, images });
  };

  const handleVideoClick = (postId: string, url: string, index: number) => {
    setSelectedVideo({ postId, url, index });
    dispatch(showModal("ReelDetail"));
  };

  const open = (postId: string) => {
    if (activeTaggedPostId === postId) {
      dispatch(hideModal("PostTagPeople"));
      setActiveTaggedPostId(null);
    } else {
      dispatch(showModal("PostTagPeople"));
      dispatch(setTaggedPostId(postId));
      setActiveTaggedPostId(postId);
    }
  };

  const isPostTagPeopleModalVisible = useAppSelector(
    (state) => state.modals.PostTagPeople
  );

  const [activeTaggedPostId, setActiveTaggedPostId] = useState<string | null>(
    null
  );

  const handleShare = (postId: any, shareCount: any, postType: any) => {
    dispatch(
      setPostId({ id: postId, share_count: shareCount, post_type: postType })
    );
    dispatch(showModal("SharePost"));
  };

  const isSharePostModalVisible = useAppSelector(
    (state) => state.modals.SharePost
  );

  const modalRef = useRef(null);

  const incrementShareCount = (postId: string) => {
    setItems((prev) =>
      prev.map((post) =>
        post.post_id === postId
          ? { ...post, total_share: Number(post.total_share) + 1 }
          : post
      )
    );
  };

  const sharePostId = useAppSelector((state) => state.PostId.id);

  const handleDeletePost = (deletedPostId: string) => {
    setItems((prev) => prev.filter((item) => item.post_id !== deletedPostId));
    setOpenDelete(null);
  };

  // Double click liking
  const [likedAnimation, setLikedAnimation] = useState<string | null>(null);
  const handleDoubleTapLike = async (postId: string, isLiked: string) => {
    // Only trigger if not already liked
    if (isLiked === "1") return;

    setLikedAnimation(postId);

    setTimeout(() => {
      setLikedAnimation(null);
    }, 900);

    handleLikePost(postId);
  };

  const [currentImageIndices, setCurrentImageIndices] = useState<Record<string, number>>({});

  const clickTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  return (
    <>
      {isInitialLoading ? (
        <ShimmerPost />
      ) : (
        <>
          {items?.length > 0 ? (
            <>
              {items?.map((post, index) => (
                <div
  key={index}
  ref={(el) => {
    itemRefs.current[index] = el;
  }}
  data-index={index}
  className="mt-5 py-4 sm:mx-0 md:rounded-[10px] mb-5 sm:mb-0 bg-[var(--bg-primary)] dark:border dark:border-[color-mix(in_srgb,var(--border-color),white_07%)] transition-colors duration-200"
  style={{
    boxShadow: "0px 4px 20px 0px rgba(0, 0, 0, 0.08), 0px 0px 10px 0px rgba(255, 255, 255, 0.02)"
  }}
>
                  <div className="flex justify-between sm:px-4 px-3">
                    <div className="flex place-items-center">
                      <div className="w-12 h-12 rounded-full overflow-hidden border border-[var(--border-color)]">
                        <img
                          src={post.profile_pic}
                          alt="profile"
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div className="px-3 flex flex-col place-items-start">
                       <button
  onClick={() => handleUsernameClick(post.username)} // Changed: pass username instead of user_id
  className=""
>
  <h2 className="text-base font-gilroy_semibold text-[var(--text-primary)] font-semibold">
    {post.username}
  </h2>
</button>
                        <p className="text-[13px] text-[var(--text-secondary)] font-gilroy_md ">
                          {post.location}
                        </p>
                      </div>
                    </div>

                    <div className="relative flex items-center">
                      <p className="text-[var(--text-secondary)] text-[13px] font-gilroy_md ">
                        {timeAgo(post.created_at)}
                      </p>
                      <button
                        onClick={() => handlePopup(post.post_id, post.user_id)}
                        className="p-1 hover:opacity-70 transition-opacity"
                      >
                        <img src="/assets/dots.png" className="w-6 h-6 img-theme" />
                      </button>

{openReport === post.post_id && (
  <div
    className="absolute right-2 sm:right-0  top-10 z-[999] bg-[var(--modal-color)] shadow-xl rounded-xl p-2 w-48 max-w-[90vw] border border-[var(--border-color)]"
    ref={reportRef}
  >
    <ReportPost
      postId={post.post_id}
      postType={post.post_type}
      userId={post.user_id}
      username={post.username}
      onClose={() => setOpenReport(null)}
    />
  </div>
)}

                     {openDelete === post.post_id && (
  <div
    className="absolute right-0  top-10 z-[999] bg-[var(--modal-color)] shadow-xl rounded-xl p-2 w-48 max-w-[90vw] border border-[var(--border-color)]"
    ref={deleteRef}
  >
    <DeletePost
      postId={post.post_id}
      postType={post.post_type}
      onClose={() => setOpenDelete(null)}
      onDelete={() => handleDeletePost(post.post_id)}
    />
  </div>
)}
                    </div>
                  </div>

                  <div className="sm:px-5 py-2">
                    {post.post_type === "reel" ? (
                      <div className="w-full sm:h-[600px] sm:rounded-[10px] overflow-hidden relative bg-[var(--bg-primary)]">
                        <video
                          ref={(el) => {
                            videoRefs.current[index] = el;
                            postRefs.current[index] = el;
                          }}
                          data-index={index}
                          loop
                          muted={isMuted}
                          playsInline
                          className="w-full h-full object-cover cursor-pointer"
                          onClick={() =>
                            handleVideoClick(
                              post.post_id,
                              post.post_image[0]?.url,
                              index
                            )
                          }
                        >
                          <source src={post.post_image[0]?.url} type="video/mp4" />
                          Your browser does not support the video tag.
                        </video>

                        <img
                          src="/assets/reel_icon.png"
                          alt="reel_icon"
                          height={10}
                          width={10}
                          className="absolute sm:top-6 sm:right-6 top-5 right-3 w-6 h-6"
                        />

                        <button
                          className="absolute bottom-6 right-6 bg-black/40 backdrop-blur-md rounded-full p-2.5 hover:bg-black/60 transition-colors"
                          onClick={() => handleMuteToggle()}
                        >
                          <img
                            src={
                              isMuted ? "/assets/muted.png" : "/assets/unmuted.png"
                            }
                            alt="mute_unmute"
                            width={20}
                            height={20}
                          />
                        </button>

                        {post?.tag_user_list?.length > 0 && (
                          <button
                            className="absolute bottom-2 left-3 bg-black/40 backdrop-blur-md rounded-full p-2.5 hover:bg-black/70 transition-colors"
                            onClick={() => open(post.post_id)}
                          >
                            <img
                              src="/assets/TagPeopleIcon.png"
                              alt="tagPeople"
                              width={15}
                              height={15}
                            />
                          </button>
                        )}

                        {activeTaggedPostId === post.post_id &&
                          isPostTagPeopleModalVisible && (
                            <div
                              className="absolute left-6 bottom-[75px] z-20"
                              ref={modalRef}
                            >
                              <TaggedPeopleInPostList />
                            </div>
                          )}
                      </div>
                   ) : post.post_image?.length > 0 ? (
  <div className="w-full sm:h-[500px] sm:rounded-[10px] overflow-hidden relative bg-[var(--bg-primary)] group">
    <img
      src={post.post_image[currentImageIndices[post.post_id] || 0]?.url}
      ref={(el) => {
        postRefs.current[index] = el;
      }}
      alt="post"
      data-index={index}
      className="w-full h-full object-cover cursor-pointer"
      onClick={() => {
        if (clickTimeoutRef.current) {
          // Double click detected
          clearTimeout(clickTimeoutRef.current);
          clickTimeoutRef.current = null;
          handleDoubleTapLike(post.post_id, post.is_liked);
        } else {
          // Wait to see if second click comes
          clickTimeoutRef.current = setTimeout(() => {
            handleImageClick(
              post.post_id,
              post.post_image.map((img: { url: any; }) => img.url)
            );
            clickTimeoutRef.current = null;
          }, 250);
        }
      }}
    />

    {/* Heart Animation */}
    {likedAnimation === post.post_id && (
      <div className="absolute inset-0 flex items-center justify-center pointer-events-none z-20">
        <img
          src="/assets/filled_heart.png"
          className="w-24 h-24 animate-heart-pop"
        />
      </div>
    )}

    {/* Multiple Post Icon - Only visible when NOT hovering */}
    {post.post_image?.length > 1 && (
      <div className="absolute top-6 right-6 transition-opacity  z-[999999] duration-200 group-hover:opacity-0">
        <img
          src="/assets/Multiple_Post.png"
          alt="multiple_post"
          className="w-5 h-5 shadow-sm img-theme"
        />
      </div>
    )}

    {/* Navigation Buttons - Only show on hover and if multiple images */}
    {post.post_image?.length > 1 && (
      <>
        {/* Previous Button - Hidden on first image */}
        {(currentImageIndices[post.post_id] || 0) > 0 && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              const currentIndex = currentImageIndices[post.post_id] || 0;
              const newIndex = currentIndex - 1;
              
              setCurrentImageIndices(prev => ({
                ...prev,
                [post.post_id]: newIndex
              }));
            }}
            className="absolute left-2 top-1/2 -translate-y-1/2 
              w-8 h-8 rounded-full bg-white/30 backdrop-blur-md 
              flex items-center justify-center text-white 
              opacity-0 group-hover:opacity-100 transition-all duration-200
              hover:bg-white/40 active:scale-95 z-10"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
        )}

        {/* Next Button - Hidden on last image */}
        {(currentImageIndices[post.post_id] || 0) < post.post_image.length - 1 && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              const currentIndex = currentImageIndices[post.post_id] || 0;
              const newIndex = currentIndex + 1;
              
              setCurrentImageIndices(prev => ({
                ...prev,
                [post.post_id]: newIndex
              }));
            }}
            className="absolute right-2 top-1/2 -translate-y-1/2 
              w-8 h-8 rounded-full bg-white/30 backdrop-blur-md 
              flex items-center justify-center text-white 
              opacity-0 group-hover:opacity-100 transition-all duration-200
              hover:bg-white/40 active:scale-95 z-10"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </button>
        )}

        {/* Image Counter - Shows on hover */}
        <div className="absolute bottom-3 left-1/2 -translate-x-1/2 
          bg-black/60 backdrop-blur-md rounded-full px-2.5 py-0.5
          text-white text-xs font-medium 
          opacity-0 group-hover:opacity-100 transition-all duration-200 z-10">
          {(currentImageIndices[post.post_id] || 0) + 1} / {post.post_image.length}
        </div>

        {/* Dot Indicators - Always visible but subtle */}
        <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5 group-hover:opacity-0 transition-opacity duration-200">
          {post.post_image.map((_, imgIndex) => (
            <button
              key={imgIndex}
              onClick={(e) => {
                e.stopPropagation();
                setCurrentImageIndices(prev => ({
                  ...prev,
                  [post.post_id]: imgIndex
                }));
              }}
              className={`h-1.5 rounded-full transition-all duration-200 ${
                imgIndex === (currentImageIndices[post.post_id] || 0)
                  ? 'w-4 bg-white'
                  : 'w-1.5 bg-white/50 hover:bg-white/80'
              }`}
            />
          ))}
        </div>
      </>
    )}

    {/* Tag People Button */}
    {post?.tag_user_list?.length > 0 && (
      <button
        className="absolute bottom-2 left-3 bg-black/40 backdrop-blur-md rounded-full p-2.5 hover:bg-black/70 transition-colors z-10"
        onClick={() => open(post.post_id)}
      >
        <img
          src="/assets/TagPeopleIcon.png"
          alt="tag people"
          width={15}
          height={15}
        />
      </button>
    )}

    {activeTaggedPostId === post.post_id &&
      isPostTagPeopleModalVisible && (
        <div
          className="absolute left-6 bottom-[75px] z-20"
          ref={modalRef}
        >
          <TaggedPeopleInPostList />
        </div>
      )}
  </div>
) : null}
                  </div>

                  <div className="font-gilroy_md text-[var(--text-primary)] px-5 py-2 text-base overflow-hidden leading-relaxed">
                    {renderTextWithHashtags(post.text)}
                  </div>

                  <div className="flex justify-between px-5 pt-2.5">
                    <div className="flex gap-5">
                      <div className="flex gap-1.5 items-center">
                        <button
                          className="active:scale-90 transition-transform"
                          onClick={() =>
                            post.post_type === "reel"
                              ? handleLikeReel(post.post_id)
                              : handleLikePost(post.post_id)
                          }
                        >
                          <img
                            src={
                              post.is_liked === "1"
                                ? "/assets/filled_heart.png"
                                : "/assets/heart1.png"
                            }
                            className={`w-[24px] h-[24px] ${post.is_liked === "1" ? "" : "img-theme"
                              }`}
                          />
                        </button>
                        <p
                          onClick={() => {
                            dispatch(setPostId({
                              id: post.post_id,
                              share_count: post.total_share,
                              post_type: post.post_type // ✅ important
                            }));

                            // ✅ small delay ensures Redux updates before modal reads it
                            setTimeout(() => {
                              dispatch(showModal("LikeModal"));
                            }, 0);
                          }}
                          className="font-gilroy_semibold text-[var(--text-primary)] text-sm cursor-pointer"
                        >
                          {post.total_like}
                        </p>
                      </div>
                      <div className="flex gap-1.5 items-center">
                        <button
                          className="active:scale-90 transition-transform"
                          onClick={() =>
                            post.post_type === "image"
                              ? handleImageClick(
                                post.post_id,
                                post.post_image.map((img: { url: any; }) => img.url)
                              )
                              : handleVideoClick(
                                post.post_id,
                                post.post_image[0]?.url,
                                index
                              )
                          }
                        >
                          <img
                            src="/assets/comment1.png"
                            className="w-[24px] h-[24px] img-theme"
                          />
                        </button>
                        <p className="font-gilroy_semibold text-[var(--text-primary)] text-sm cursor-pointer" onClick={() =>
                          post.post_type === "image"
                            ? handleImageClick(
                              post.post_id,
                              post.post_image.map((img: { url: any; }) => img.url)
                            )
                            : handleVideoClick(
                              post.post_id,
                              post.post_image[0]?.url,
                              index
                            )
                        }>
                          {post.total_comment}
                        </p>
                      </div>
                      <div className="flex gap-1.5 items-center">
                        <button
                          className="active:scale-90 transition-transform"
                          onClick={() =>
                            handleShare(
                              post.post_id,
                              post.total_share,
                              post.post_type
                            )
                          }
                        >
                          <img
                            src="/assets/send1.png"
                            className="w-[24px] h-[24px] img-theme"
                          />
                        </button>
                        <p className="font-gilroy_semibold text-[var(--text-primary)] text-sm cursor-pointer" onClick={() =>
                          handleShare(
                            post.post_id,
                            post.total_share,
                            post.post_type
                          )
                        }>
                          {post.total_share}
                        </p>
                      </div>
                    </div>
                    <button
                      className="active:scale-90 transition-transform"
                      onClick={() =>
                        handleBookmarkPost(post.post_id, post.post_type)
                      }
                    >
                      <div>
                        {savedPosts[post.post_id] || post.is_bookmark === "1" ? (
                          <img
                            src="/assets/filled_save.png"
                            className="w-[21px] h-[21px] img-theme"
                          />
                        ) : (
                          <img
                            src="/assets/savepost1.png"
                            className="w-[21px] h-[21px] img-theme"
                          />
                        )}
                      </div>
                    </button>
                  </div>
                </div>
              ))}
              {isFetchingMore && (
                <div className="flex justify-center py-6">
                  <ClipLoader color="#452B7A" size={25} aria-label="loading" />
                </div>
              )}
            </>
          ) : (
            <div className="flex flex-col items-center justify-center py-20 px-4 text-center">
              <img
                src="/assets/NoPost.png"
                className="w-16 h-16 img-theme mb-4 "

              />
              <h2 className="text-lg font-gilroy_semibold text-[var(--text-primary)] mb-1">
                <TextTranslate text="No Posts Yet" />
              </h2>
              <p className="text-sm font-gilroy_regular text-[var(--text-secondary)] opacity-70 max-w-xs">
                <TextTranslate text="No Post to show start following other users" />
              </p>
            </div>
          )}

        </>
      )}

      {/* Overlay/Backdrop Layer */}
      {(selectedVideo || selectedPost || isSharePostModalVisible) && (
        <div className="fixed inset-0 z-[999] bg-black/30  transition-opacity" />
      )}

      {/* Modals */}
      {selectedVideo && (
        <div className="fixed inset-0 z-[1000] flex items-center justify-center">
          <ReelDetail
            videoSrc={selectedVideo.url}
            postId={selectedVideo.postId}
            isMuted={isMuted}
            onMuteToggle={handlePopupMuteToggle}
            onClose={() => {
              setSelectedVideo(null);
              dispatch(hideModal("ReelDetail"));
            } } onCommentSuccess={function (): void {
              throw new Error("Function not implemented.");
            } }          />
        </div>
      )}

      {selectedPost && (
        <div className="fixed inset-0 z-[1000] flex items-center justify-center">
          <PostDetail
           
            images={selectedPost.images}
            postId={selectedPost.postId}
            onClose={() => {
              setSelectedPost(null);
              // Also hide the modal from Redux state
              dispatch(hideModal());
            }}
          />
        </div>
      )}

      {isSharePostModalVisible && (
        <div className="fixed inset-0 z-[1000] flex items-center justify-center">
          <SharePostUsersList
            onShareSuccess={() => incrementShareCount(String(sharePostId))}
          />
        </div>
      )}
      {isLikeModalVisible && (
        <div className="fixed inset-0 z-[1000] flex items-center justify-center">
          <LikeModal />
        </div>
      )}
    </>
  );
}

export default Post;