'use client';

import React, { useState, useEffect, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { motion } from "framer-motion";
import { MoreHorizontal, PencilIcon, Loader2, Lightbulb, Trash2, Share2, X } from "lucide-react";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "sonner";
import { RootState } from "@/lib/store/store";
import { 
  getLoggedInCustomerPost, 
  deleteCustomerPost,
  likeDislike,
  updatePost,
  getAllCategories,
} from "@/lib/api/client";
import { setSelectedCategory } from "@/lib/store/slices/userSlice";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

// ========== SHIMMER SKELETON STYLES ==========
const shimmerStyle = `
  @keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
  }
`;

// Tab headers
const my_post_header = [
  { _id: 1, title: "Send Now", category: "Active" },
  { _id: 2, title: "Save/Draft", category: "InActive" },
];

// Helper functions
const getInitials = (name: string | null | undefined) => {
  if (!name || typeof name !== 'string' || name.trim() === "") return "U";
  return name
    .split(" ")
    .map((word) => word[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
};

const formatRelativeTime = (date: Date | string) => {
  if (!date) return "recently";
  const now = new Date();
  const past = new Date(date);
  if (isNaN(past.getTime())) return "recently";
  
  const diffMins = Math.floor((now.getTime() - past.getTime()) / 60000);
  const diffHours = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHours / 24);
  
  if (diffMins < 1) return "just now";
  if (diffMins < 60) return `${diffMins} minute${diffMins === 1 ? '' : 's'} ago`;
  if (diffHours < 24) return `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`;
  if (diffDays < 7) return `${diffDays} day${diffDays === 1 ? '' : 's'} ago`;
  return past.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
};

// ========== SHIMMER POST SKELETON ==========
const ShimmerPostSkeleton = () => {
  useEffect(() => {
    if (typeof document !== 'undefined' && !document.querySelector('#shimmer-style')) {
      const style = document.createElement('style');
      style.id = 'shimmer-style';
      style.textContent = shimmerStyle;
      document.head.appendChild(style);
    }
  }, []);

  return (
    <div className="bg-card rounded-2xl border border-border/50 p-5 relative overflow-hidden">
      <div className="absolute inset-0 -translate-x-full animate-[shimmer_1.5s_infinite] bg-gradient-to-r from-transparent via-white/30 dark:via-white/10 to-transparent" />
      
      {/* Header Skeleton */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-gray-300 dark:bg-gray-700"></div>
          <div>
            <div className="h-4 w-32 bg-gray-300 dark:bg-gray-700 rounded mb-1"></div>
            <div className="h-3 w-20 bg-gray-300 dark:bg-gray-700 rounded"></div>
          </div>
        </div>
        <div className="w-8 h-8 bg-gray-300 dark:bg-gray-700 rounded-lg"></div>
      </div>
      
      {/* Content Skeleton */}
      <div className="space-y-2 mb-3">
        <div className="h-4 w-full bg-gray-300 dark:bg-gray-700 rounded"></div>
        <div className="h-4 w-3/4 bg-gray-300 dark:bg-gray-700 rounded"></div>
        <div className="h-4 w-1/2 bg-gray-300 dark:bg-gray-700 rounded"></div>
      </div>
      
      {/* Category Badge Skeleton */}
      <div className="mb-3">
        <div className="h-6 w-24 bg-gray-300 dark:bg-gray-700 rounded-full"></div>
      </div>
      
      {/* Like/Dislike Skeleton */}
      <div className="flex items-center gap-6 pt-3 border-t border-border/50">
        <div className="flex items-center gap-2">
          <div className="w-5 h-5 bg-gray-300 dark:bg-gray-700 rounded-full"></div>
          <div className="h-4 w-6 bg-gray-300 dark:bg-gray-700 rounded"></div>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-5 h-5 bg-gray-300 dark:bg-gray-700 rounded-full"></div>
          <div className="h-4 w-6 bg-gray-300 dark:bg-gray-700 rounded"></div>
        </div>
      </div>
    </div>
  );
};

interface MyIdeaClientProps {
  imageData: any;
  sharingIcons: any;
  logoImage: any;
  postsPerPage: number;
}

interface Post {
  _id: string;
  description: string;
  media?: Array<{ url: string; type: string; _id: string }>;
  postCategory?: { mainCategoryName: string } | string;
  counts?: { likes: number; dislikes: number };
  likeStatus?: "like" | "dislike" | null;
  bookmarked?: boolean;
  createdAt: string;
  updatedAt?: string;
  status?: string;
  customerID?: {
    _id: string;
    fullName: string;
    imageURL?: string;
  };
}

export default function MyIdeaClient({ imageData, sharingIcons, logoImage, postsPerPage }: MyIdeaClientProps) {
  const dispatch = useDispatch();
  const router = useRouter();
  const { accessToken, currentCustomer } = useSelector((state: RootState) => state.user);
  
  const [activeTab, setActiveTab] = useState(my_post_header[0].title);
  const [category, setCategory] = useState(my_post_header[0].category);
  const [borderStyle, setBorderStyle] = useState({ width: 0, left: 0 });
  const [openUpdateYourIdea, setOpenUpdateYourIdea] = useState(false);
  const [customerPosts, setCustomerPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [postID, setPostID] = useState<string | null>(null);
  const [refreshPosts, setRefreshPosts] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const [editAllowedTime, setEditAllowedTime] = useState(60);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [openMenuFor, setOpenMenuFor] = useState<string | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const [isDarkMode, setIsDarkMode] = useState(false);

  // ✅ Like/Dislike debouncing refs
  const likeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const dislikeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const abortControllerRef = useRef<AbortController | null>(null);
  const isProcessingRef = useRef(false);

  const [updateImages, setUpdateImages] = useState<string[]>([]);
  const [updateRemovedImages, setUpdateRemovedImages] = useState<string[]>([]);
  const [updateNewImages, setUpdateNewImages] = useState<File[]>([]);
  const [imagePreviewUrls, setImagePreviewUrls] = useState<string[]>([]);
  
  // Update Post States
  const [updateDescription, setUpdateDescription] = useState("");
  const [updateCategory, setUpdateCategory] = useState("");
  const [updateStatus, setUpdateStatus] = useState("Active");
  const [updatingPost, setUpdatingPost] = useState(false);
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [categories, setCategories] = useState<any[]>([]);
  const [isLoadingCategories, setIsLoadingCategories] = useState(false);

  // Fetch categories for dropdown
  const fetchCategories = useCallback(async () => {
    if (!accessToken) return;
    setIsLoadingCategories(true);
    try {
      const result = await getAllCategories(logoImage?.securityKey);
      if (result.success && result.data) {
        setCategories(result.data);
      }
    } catch (error) {
      console.error("Error fetching categories:", error);
    } finally {
      setIsLoadingCategories(false);
    }
  }, [accessToken, logoImage?.securityKey]);

  useEffect(() => {
    fetchCategories();
  }, [fetchCategories]);
  
  // Check dark mode on mount and when class changes
  useEffect(() => {
    const checkDarkMode = () => {
      const isDark = document.documentElement.classList.contains('dark');
      setIsDarkMode(isDark);
    };
  
    checkDarkMode();
  
    const observer = new MutationObserver(checkDarkMode);
    observer.observe(document.documentElement, { 
      attributes: true, 
      attributeFilter: ['class'] 
    });
  
    return () => observer.disconnect();
  }, []);

  // ✅ Same icon functions as IdeaFeed
  const getFilledLikeIcon = () => {
    return isDarkMode ? "/icons/dark-likefilled.svg" : "/icons/like_filled.svg";
  };

  const getFilledDislikeIcon = () => {
    return isDarkMode ? "/icons/dark-dislikefilled.svg" : "/icons/dislike_filled.svg";
  };

  const getUnfilledLikeIcon = () => {
    return isDarkMode ? "/icons/like-dark.svg" : "/icons/like_unfilled.svg";
  };

  const getUnfilledDislikeIcon = () => {
    return isDarkMode ? "/icons/dislike-dark.svg" : "/icons/dislike_unfilled.svg";
  };

  // ✅ Cleanup on unmount
  useEffect(() => {
    return () => {
      if (likeTimeoutRef.current) clearTimeout(likeTimeoutRef.current);
      if (dislikeTimeoutRef.current) clearTimeout(dislikeTimeoutRef.current);
      if (abortControllerRef.current) abortControllerRef.current?.abort();
    };
  }, []);

  // Update border for active tab
  useEffect(() => {
    const updateBorder = () => {
      const activeElement = document.querySelector(`[data-tab="${activeTab}"]`);
      if (activeElement) {
        const rect = activeElement.getBoundingClientRect();
        const parentRect = activeElement.parentElement?.getBoundingClientRect();
        if (parentRect) {
          setBorderStyle({
            width: rect.width,
            left: rect.left - parentRect.left,
          });
        }
      }
    };
    
    const observer = new ResizeObserver(updateBorder);
    const tabs = document.querySelectorAll(".tab-button");
    tabs.forEach((tab) => observer.observe(tab));
    updateBorder();
    return () => observer.disconnect();
  }, [activeTab]);

  // Close menu when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      const isModalOpen = document.querySelector('.fixed.inset-0.bg-black\\/50');
      const isClickOnModal = isModalOpen && isModalOpen.contains(target);
      const isClickOnModalButton = target.closest('.fixed.inset-0') || target.closest('[data-modal="true"]');
      
      if (!isClickOnModal && !isClickOnModalButton && menuRef.current && !menuRef.current.contains(target)) {
        setOpenMenuFor(null);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Fetch posts
  const fetchPosts = useCallback(async (pageNum: number = 1, append: boolean = false) => {
    if (!accessToken) return;
    
    setLoading(true);
    setErrorMessage(null);
    
    try {
      const result = await getLoggedInCustomerPost(
        category,
        accessToken,
        pageNum,
        postsPerPage,
        currentCustomer?.selectedCategory === null ? "" : currentCustomer?.selectedCategory?._id || "",
        logoImage?.securityKey || process.env.NEXT_PUBLIC_SECURITY_KEY
      );
      
      if (result?.success === false && result?.message?.trim() === "Account Not Exits") {
        router.push("/");
        return;
      }
      
      if (result.success) {
        const posts = result?.posts || [];
        if (append) {
          setCustomerPosts(prev => [...prev, ...posts]);
        } else {
          setCustomerPosts(posts);
        }
        setHasMore(posts.length === postsPerPage);
        setEditAllowedTime(result?.editAllowedTime || 60);
      } else {
        if (!append) setCustomerPosts([]);
        setHasMore(false);
        setErrorMessage(result?.message);
      }
    } catch (err: any) {
      console.error("Error fetching posts:", err);
      if (!append) setCustomerPosts([]);
      setHasMore(false);
      setErrorMessage(err?.response?.data?.message || "Server not responding, please try again later.");
    } finally {
      setLoading(false);
    }
  }, [category, accessToken, postsPerPage, currentCustomer?.selectedCategory, logoImage?.securityKey, router]);

  // Load more posts
  const fetchMorePosts = async () => {
    if (isFetchingMore || !hasMore) return;
    setIsFetchingMore(true);
    const nextPage = page + 1;
    
    try {
      const result = await getLoggedInCustomerPost(
        category,
        accessToken!,
        nextPage,
        postsPerPage,
        currentCustomer?.selectedCategory === null ? "" : currentCustomer?.selectedCategory?._id || "",
        logoImage?.securityKey || process.env.NEXT_PUBLIC_SECURITY_KEY
      );
      
      if (result.success && result?.posts?.length > 0) {
        const newPosts = result.posts;
        setCustomerPosts(prev => {
          const existingIds = new Set(prev.map(p => p._id));
          const uniqueNewPosts = newPosts.filter((p: Post) => !existingIds.has(p._id));
          return [...prev, ...uniqueNewPosts];
        });
        setPage(nextPage);
        setHasMore(newPosts.length === postsPerPage);
      } else {
        setHasMore(false);
      }
    } catch (err) {
      console.error("Error fetching more posts:", err);
      setHasMore(false);
    } finally {
      setIsFetchingMore(false);
    }
  };

  // Handle tab click
  const handleTabClick = (tab: typeof my_post_header[0]) => {
    setCategory(tab.category);
    setActiveTab(tab.title);
    setCustomerPosts([]);
    setPage(1);
    setHasMore(true);
    setOpenMenuFor(null);
  };

  const editPost = (post: Post) => {
    console.log("Post data:", post);
    console.log("Media array:", post.media);
    console.log("Image URLs:", post.media?.map(item => item.url));

    setSelectedPost(post);
    setUpdateDescription(post.description || "");
    
    let categoryValue = "";
    if (post.postCategory) {
      if (typeof post.postCategory === 'object') {
        categoryValue = post.postCategory.mainCategoryName || post.postCategory._id || "";
      } else {
        categoryValue = post.postCategory;
      }
    }
    
    setUpdateCategory(categoryValue);
    setUpdateStatus(post.status === "Active" ? "Active" : "InActive");
    setPostID(post._id);
    
    const imageUrls = post.media?.map(item => item.url).filter(url => url) || [];
    setUpdateImages(imageUrls);
    setUpdateRemovedImages([]);
    setUpdateNewImages([]);
    setImagePreviewUrls([]);
    
    setOpenUpdateYourIdea(true);
    setOpenMenuFor(null);
  };

  const handleRemoveImage = (imageUrlToRemove: string) => {
    setUpdateImages(prev => prev.filter(url => url !== imageUrlToRemove));
    setUpdateRemovedImages(prev => [...prev, imageUrlToRemove]);
  };

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    
    const allowedTypes = [
      'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/heic', 'image/heif'
    ];
    
    const validFiles = files.filter(file => {
      if (!allowedTypes.includes(file.type)) {
        toast.error(`${file.name} is not an allowed image type. Allowed: JPEG, PNG, GIF, WEBP`);
        return false;
      }
      if (file.size > 1 * 1024 * 1024) {
        toast.error(`${file.name} exceeds 1 MB limit`);
        return false;
      }
      return true;
    });
    
    if (validFiles.length === 0) return;
    
    setUpdateNewImages(prev => [...prev, ...validFiles]);
    const newPreviews = validFiles.map(file => URL.createObjectURL(file));
    setImagePreviewUrls(prev => [...prev, ...newPreviews]);
  };

  const handleRemoveNewImage = (index: number) => {
    URL.revokeObjectURL(imagePreviewUrls[index]);
    setUpdateNewImages(prev => prev.filter((_, i) => i !== index));
    setImagePreviewUrls(prev => prev.filter((_, i) => i !== index));
  };

  const handleUpdatePost = async () => {
    if (!accessToken || !postID) return;
    
    if (!updateDescription.trim()) {
      toast.error("Please enter description");
      return;
    }
    
    setUpdatingPost(true);
    
    try {
      const formData = new FormData();
      formData.append("description", updateDescription);
      formData.append("status", updateStatus);
      
      if (updateCategory && updateCategory.trim() !== "") {
        formData.append("postCategory", updateCategory);
      }
      
      if (updateRemovedImages.length > 0) {
        formData.append("removedImages", JSON.stringify(updateRemovedImages));
      }
      
      updateNewImages.forEach((image) => {
        formData.append("media", image);
      });
      
      const result = await updatePost(
        formData, postID, accessToken, 
        logoImage?.securityKey || process.env.NEXT_PUBLIC_SECURITY_KEY
      );
      
      if (result.success) {
        toast.success("Post updated successfully!");
        setCustomerPosts([]);
        setPage(1);
        setHasMore(true);
        await fetchPosts(1, false);
        setRefreshPosts(prev => !prev);
        
        setOpenUpdateYourIdea(false);
        setSelectedPost(null);
        setUpdateDescription("");
        setUpdateCategory("");
        setUpdateStatus("Active");
        setPostID(null);
        setUpdateImages([]);
        setUpdateRemovedImages([]);
        setUpdateNewImages([]);
        imagePreviewUrls.forEach(url => URL.revokeObjectURL(url));
        setImagePreviewUrls([]);
        setOpenMenuFor(null);
      } else {
        toast.error(result.message || "Failed to update post");
      }
    } catch (error: any) {
      console.error("Error updating post:", error);
      toast.error(error?.response?.data?.message || "Failed to update post");
    } finally {
      setUpdatingPost(false);
    }
  };

  // Delete post
  const deletePost = async (postId: string) => {
    if (!accessToken) return;
    
    setActionLoading(postId);
    try {
      const result = await deleteCustomerPost(accessToken, postId, logoImage?.securityKey || process.env.NEXT_PUBLIC_SECURITY_KEY);
      if (result.success) {
        toast.success("Post Deleted Successfully");
        setCustomerPosts(prev => prev.filter(p => p._id !== postId));
        setOpenMenuFor(null);
      } else {
        toast.error(result.message || "Failed to delete post");
      }
    } catch (error) {
      toast.error("Failed to delete post");
    } finally {
      setActionLoading(null);
    }
  };

  // Handle share
  const handleShare = (post: Post) => {
    const postUrl = `${BASE_URL}/idea/${post._id}`;
    navigator.clipboard.writeText(postUrl);
    toast.success("Link copied to clipboard!");
    setOpenMenuFor(null);
  };

  // ✅ Fixed Debounced Like Handler (same as IdeaFeed)
  const handleLike = async (post: Post) => {
    if (!accessToken) {
      toast.error("Please login to like posts");
      return;
    }
    
    if (isProcessingRef.current) return;
    
    if (likeTimeoutRef.current) clearTimeout(likeTimeoutRef.current);
    if (dislikeTimeoutRef.current) clearTimeout(dislikeTimeoutRef.current);
    
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    
    abortControllerRef.current = new AbortController();
    isProcessingRef.current = true;
    
    const wasLiked = post.likeStatus === "like";
    const wasDisliked = post.likeStatus === "dislike";
    const postId = post._id;
    
    // Optimistic update
    const updatedPosts = customerPosts.map(p => {
      if (p._id === postId) {
        let newLikes = p.counts?.likes || 0;
        let newDislikes = p.counts?.dislikes || 0;
        let newStatus = null;
        
        if (wasLiked) {
          newLikes -= 1;
          newStatus = null;
        } else {
          newLikes += 1;
          newStatus = "like";
          if (wasDisliked) {
            newDislikes -= 1;
          }
        }
        
        return {
          ...p,
          counts: { likes: newLikes, dislikes: newDislikes },
          likeStatus: newStatus
        };
      }
      return p;
    });
    setCustomerPosts(updatedPosts);
    
    try {
      const result = await likeDislike(accessToken, postId, "like", logoImage?.securityKey || process.env.NEXT_PUBLIC_SECURITY_KEY);
      
      if (result.success) {
        setCustomerPosts(prev => prev.map(p => {
          if (p._id === postId) {
            return {
              ...p,
              counts: result.data.counts,
              likeStatus: result.data.userReaction
            };
          }
          return p;
        }));
      } else {
        // Rollback
        fetchPosts(1, false);
        toast.error(result.message || "Could not like the post");
      }
    } catch (error: any) {
      if (error?.name === 'AbortError') return;
      fetchPosts(1, false);
      toast.error("Could not like the post");
    } finally {
      isProcessingRef.current = false;
    }
  };

  // ✅ Fixed Debounced Dislike Handler (same as IdeaFeed)
  const handleDislike = async (post: Post) => {
    if (!accessToken) {
      toast.error("Please login to dislike posts");
      return;
    }
    
    if (isProcessingRef.current) return;
    
    if (dislikeTimeoutRef.current) clearTimeout(dislikeTimeoutRef.current);
    if (likeTimeoutRef.current) clearTimeout(likeTimeoutRef.current);
    
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    
    abortControllerRef.current = new AbortController();
    isProcessingRef.current = true;
    
    const wasLiked = post.likeStatus === "like";
    const wasDisliked = post.likeStatus === "dislike";
    const postId = post._id;
    
    // Optimistic update
    const updatedPosts = customerPosts.map(p => {
      if (p._id === postId) {
        let newLikes = p.counts?.likes || 0;
        let newDislikes = p.counts?.dislikes || 0;
        let newStatus = null;
        
        if (wasDisliked) {
          newDislikes -= 1;
          newStatus = null;
        } else {
          newDislikes += 1;
          newStatus = "dislike";
          if (wasLiked) {
            newLikes -= 1;
          }
        }
        
        return {
          ...p,
          counts: { likes: newLikes, dislikes: newDislikes },
          likeStatus: newStatus
        };
      }
      return p;
    });
    setCustomerPosts(updatedPosts);
    
    try {
      const result = await likeDislike(accessToken, postId, "dislike", logoImage?.securityKey || process.env.NEXT_PUBLIC_SECURITY_KEY);
      
      if (result.success) {
        setCustomerPosts(prev => prev.map(p => {
          if (p._id === postId) {
            return {
              ...p,
              counts: result.data.counts,
              likeStatus: result.data.userReaction
            };
          }
          return p;
        }));
      } else {
        // Rollback
        fetchPosts(1, false);
        toast.error(result.message || "Could not dislike the post");
      }
    } catch (error: any) {
      if (error?.name === 'AbortError') return;
      fetchPosts(1, false);
      toast.error("Could not dislike the post");
    } finally {
      isProcessingRef.current = false;
    }
  };

  // Cleanup image previews
  useEffect(() => {
    return () => {
      imagePreviewUrls.forEach(url => URL.revokeObjectURL(url));
    };
  }, [imagePreviewUrls]);

  // Initial fetch
  useEffect(() => {
    if (accessToken) {
      fetchPosts(1, false);
    }
  }, [accessToken, category, refreshPosts, fetchPosts]);

  // Reset selected category on mount
  useEffect(() => {
    dispatch(setSelectedCategory(null));
  }, [dispatch]);

  // Redirect if not logged in
  useEffect(() => {
    if (!currentCustomer && !accessToken) {
      router.push("/");
    }
  }, [currentCustomer, accessToken, router]);

  if (!currentCustomer && !accessToken) {
    return null;
  }

  const customerName = currentCustomer?.fullName || "User";

  return (
    <div className="w-full">
      <div className="flex flex-col gap-6">
        {/* Tabs Section */}
        <div className="flex flex-col w-full bg-card rounded-xl border border-border/50">
          <div className="flex flex-col w-full">
            <div className="relative w-full overflow-x-auto hide-scrollbar">
              <div className="flex items-center w-max px-2 space-x-2 relative">
                {my_post_header.map((tab) => (
                  <button
                    key={tab._id}
                    data-tab={tab.title}
                    onClick={() => handleTabClick(tab)}
                    className={`tab-button cursor-pointer px-3 md:px-4 py-3 text-sm font-medium transition-all duration-200 relative ${
                      activeTab === tab.title
                        ? "text-primary"
                        : "text-muted-foreground hover:text-foreground"
                    }`}
                  >
                    {tab.title}
                  </button>
                ))}
                <motion.div
                  className="absolute left-0 bottom-0 h-0.5 bg-primary"
                  animate={{ width: borderStyle.width, x: borderStyle.left }}
                  transition={{ type: "spring", stiffness: 300, damping: 30 }}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Posts List with Shimmer Skeleton */}
        {loading && customerPosts.length === 0 ? (
          <div className="space-y-4">
            {[1, 2, 3].map((i) => (
              <ShimmerPostSkeleton key={i} />
            ))}
          </div>
        ) : errorMessage ? (
          <div className="text-center py-12 text-red-500">{errorMessage}</div>
        ) : customerPosts.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 bg-card rounded-2xl border border-border/50">
            <div className="p-6 bg-secondary rounded-2xl mb-6">
              <Lightbulb className="w-16 h-16 text-muted-foreground" />
            </div>
            <h3 className="text-xl font-bold text-foreground mb-2">
              No Ideas Posted Yet
            </h3>
            <p className="text-muted-foreground text-center max-w-md">
              Share your first idea to get started!
            </p>
          </div>
        ) : (
          <div className="space-y-4">
            {customerPosts.map((post) => {
              const isLiked = post.likeStatus === "like";
              const isDisliked = post.likeStatus === "dislike";
              const categoryName = typeof post.postCategory === 'object' 
                ? post.postCategory?.mainCategoryName 
                : post.postCategory;
              const isEditable = (() => {
                if (!post.createdAt) return false;
                const createdTime = new Date(post.createdAt).getTime();
                const currentTime = new Date().getTime();
                const diffMinutes = (currentTime - createdTime) / (1000 * 60);
                return diffMinutes <= editAllowedTime;
              })();

              return (
                <div key={post._id} className="bg-card rounded-2xl border border-border/50 p-5 hover:shadow-md transition-all duration-200">
                  {/* Post Header */}
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-3">
                      {post.customerID?.imageURL ? (
                        <div className="w-10 h-10 rounded-full overflow-hidden ring-2 ring-border">
                          <Image
                            width={40}
                            height={40}
                            src={`${BASE_URL}/uploads/${post.customerID.imageURL}`}
                            alt={post.customerID?.fullName || customerName}
                            className="w-full h-full object-cover"
                          />
                        </div>
                      ) : (
                        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                          <span className="text-sm font-semibold text-primary">
                            {getInitials(post.customerID?.fullName || customerName)}
                          </span>
                        </div>
                      )}
                      <div>
                        <p className="text-sm font-semibold text-foreground">
                          {post.customerID?.fullName || customerName}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {formatRelativeTime(post.createdAt)}
                        </p>
                      </div>
                    </div>
                    
                    {/* 3 Dots Menu */}
                    <div className="relative">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setOpenMenuFor(openMenuFor === post._id ? null : post._id);
                        }}
                        className="p-1.5 rounded-lg hover:bg-secondary transition-colors"
                      >
                        <MoreHorizontal className="w-5 h-5 text-muted-foreground" />
                      </button>
                      
                      {openMenuFor === post._id && (
                        <div 
                          className="absolute right-0 mt-1 w-32 bg-card rounded-lg shadow-lg border border-border/50 z-20 overflow-hidden"
                          onClick={(e) => e.stopPropagation()}
                          ref={menuRef}
                        >
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleShare(post);
                            }}
                            className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-secondary transition-colors"
                          >
                            <Share2 className="w-4 h-4" />
                            Share
                          </button>
                          {isEditable && (
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                editPost(post);
                              }}
                              className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-secondary transition-colors"
                            >
                              <PencilIcon className="w-4 h-4" />
                              Edit
                            </button>
                          )}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              deletePost(post._id);
                            }}
                            disabled={actionLoading === post._id}
                            className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-500 hover:bg-red-500/10 transition-colors disabled:opacity-50"
                          >
                            {actionLoading === post._id ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                              <Trash2 className="w-4 h-4" />
                            )}
                            Delete
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                  
                  {/* Post Content */}
                  <p className="text-foreground text-base mb-3">
                    {post.description}
                  </p>
                  
                  {/* Category Badge */}
                  {categoryName && categoryName !== "Uncategorized" && (
                    <div className="mb-3">
                      <span className="px-3 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full">
                        {categoryName}
                      </span>
                    </div>
                  )}

                  {/* ✅ ADD IMAGES SECTION - YEH BLOCK ADD KARO */}
{post.media && post.media.length > 0 && (
  <div className="mb-3">
    <div className="grid grid-cols-2 gap-2">
      {post.media.slice(0, 4).map((mediaItem, idx) => {
        if (!mediaItem.url || mediaItem.url === 'undefined' || mediaItem.url === 'null') return null;
        const imageUrl = mediaItem.url.startsWith('http') 
          ? mediaItem.url 
          : `${BASE_URL}/uploads/${mediaItem.url}`;
        return (
          <div key={idx} className="relative rounded-lg overflow-hidden">
            <Image
              src={imageUrl}
              alt={`Post image ${idx + 1}`}
              width={200}
              height={150}
              className="w-full h-32 object-contain rounded-lg"
            />
          </div>
        );
      }).filter(Boolean)}
    </div>
    {post.media.length > 4 && (
      <p className="text-xs text-muted-foreground mt-1">
        +{post.media.length - 4} more images
      </p>
    )}
  </div>
)}
                  
                  {/* ✅ Like/Dislike Buttons - Same as IdeaFeed */}
                  <div className="flex items-center gap-6 pt-3 border-t border-border/50">
                    <button
                      onClick={() => handleLike(post)}
                      className={`flex cursor-pointer items-center gap-2 transition-all ${
                        isLiked ? "text-primary" : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      <Image
                        src={isLiked ? getFilledLikeIcon() : getUnfilledLikeIcon()} 
                        alt="like"
                        width={20}
                        height={20}
                        className="w-5 h-5 rounded-full"
                      />
                      <span className="text-sm">
                        {post.counts?.likes || 0}
                      </span>
                    </button>
                    
                    <button
                      onClick={() => handleDislike(post)}
                      className={`flex cursor-pointer items-center gap-2 transition-all ${
                        isDisliked ? "text-primary" : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      <Image
                        src={isDisliked ? getFilledDislikeIcon() : getUnfilledDislikeIcon()} 
                        alt="dislike"
                        width={20}
                        height={20}
                        className="w-5 h-5 rounded-full"
                      />
                      <span className="text-sm">
                        {post.counts?.dislikes || 0}
                      </span>
                    </button>
                  </div>
                </div>
              );
            })}
            
            {/* Load More with Shimmer */}
            {isFetchingMore && (
              <div className="space-y-4">
                {[1, 2].map((i) => (
                  <ShimmerPostSkeleton key={`loading-more-${i}`} />
                ))}
              </div>
            )}
            
            {hasMore && !isFetchingMore && (
              <div className="flex justify-center pt-4">
                <button
                  onClick={fetchMorePosts}
                  disabled={isFetchingMore}
                  className="px-4 py-2 text-sm text-primary hover:text-primary/80 disabled:opacity-50 transition-colors"
                >
                  Load More
                </button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Update Modal */}
      {openUpdateYourIdea && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-card rounded-xl w-full max-w-md border border-border/50 shadow-xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b border-border/50 sticky top-0 bg-card z-10">
              <h3 className="text-lg font-semibold text-foreground">Update Your Idea</h3>
              <button
                onClick={() => {
                  setOpenUpdateYourIdea(false);
                  setSelectedPost(null);
                  setUpdateDescription("");
                  setUpdateCategory("");
                  setUpdateStatus("Active");
                  setPostID(null);
                  setUpdateImages([]);
                  setUpdateRemovedImages([]);
                  setUpdateNewImages([]);
                  imagePreviewUrls.forEach(url => URL.revokeObjectURL(url));
                  setImagePreviewUrls([]);
                }}
                className="p-1 cursor-pointer rounded-lg hover:bg-secondary transition-colors"
              >
                <X className="w-5 h-5 text-muted-foreground" />
              </button>
            </div>
            
            <div className="p-4 space-y-4">
              {/* Description Input */}
              <div>
                <label className="text-sm font-medium text-foreground mb-1.5 block">
                  Description
                </label>
                <textarea
                  value={updateDescription}
                  onChange={(e) => setUpdateDescription(e.target.value)}
                  className="w-full p-3 bg-secondary/30 rounded-xl border border-border/50 focus:outline-none focus:ring-2 focus:ring-primary/30 text-foreground resize-none h-32"
                  placeholder="Update your idea here..."
                />
              </div>
              
              {/* Images Section */}
              <div>
                <label className="text-sm font-medium text-foreground mb-1.5 block">
                  Images
                </label>
                
                {/* Existing Images */}
                {updateImages.length > 0 && updateImages.some(img => img && img !== 'undefined' && img !== 'null') && (
                  <div className="mb-3">
                    <p className="text-xs text-muted-foreground mb-2">Current Images:</p>
                    <div className="grid grid-cols-3 gap-2">
                      {updateImages.map((imgUrl, idx) => {
                        if (!imgUrl || imgUrl === 'undefined' || imgUrl === 'null') return null;
                        const imageUrl = imgUrl.startsWith('http') ? imgUrl : `${BASE_URL}/uploads/${imgUrl}`;
                        return (
                          <div key={idx} className="relative group aspect-square">
                            <div className="relative w-full h-full">
                              <Image
                                src={imageUrl}
                                alt={`Image ${idx + 1}`}
                                fill
                                className="object-cover rounded-lg border border-border/50"
                              />
                            </div>
                            <button
                              type="button"
                              onClick={() => handleRemoveImage(imgUrl)}
                              className="absolute top-1 right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity z-10"
                            >
                              <X className="w-3 h-3 text-white" />
                            </button>
                          </div>
                        );
                      }).filter(Boolean)}
                    </div>
                  </div>
                )}
                
                {/* New Image Previews */}
                {imagePreviewUrls.length > 0 && (
                  <div className="mb-3">
                    <p className="text-xs text-muted-foreground mb-2">New Images:</p>
                    <div className="grid grid-cols-3 gap-2">
                      {imagePreviewUrls.map((preview, idx) => (
                        <div key={idx} className="relative group aspect-square">
                          <div className="relative w-full h-full">
                            <Image
                              src={preview}
                              alt={`Preview ${idx + 1}`}
                              fill
                              className="object-cover flex rounded-lg border border-border/50"
                            />
                          </div>
                          <button
                            type="button"
                            onClick={() => handleRemoveNewImage(idx)}
                            className="absolute top-1 right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity z-10"
                          >
                            <X className="w-3 h-3 text-white" />
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                
                {/* Upload Button */}
                <button
                  type="button"
                  onClick={() => document.getElementById('update-image-input')?.click()}
                  className="w-full p-3 cursor-pointer border-2 border-dashed border-border/50 rounded-lg text-sm text-muted-foreground hover:border-primary/50 hover:text-primary transition-colors"
                >
                  + Add Images
                </button>
                <input
                  id="update-image-input"
                  type="file"
                  accept="image/*"
                  multiple
                  onChange={handleImageUpload}
                  className="hidden"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  You can add multiple images (Max 5)
                </p>
              </div>
              
            
              
              {/* Status Toggle */}
              <div>
                <label className="text-sm font-medium text-foreground mb-1.5 block">
                  Status
                </label>
                <div className="flex gap-3">
                  <button
                    type="button"
                    onClick={() => setUpdateStatus("Active")}
                    className={`flex-1 px-4 py-2 cursor-pointer rounded-lg text-sm font-medium transition-all ${
                      updateStatus === "Active"
                        ? "bg-primary text-white"
                        : "bg-secondary/50 text-muted-foreground hover:bg-secondary"
                    }`}
                  >
                    Active (Send Now)
                  </button>
                  <button
                    type="button"
                    onClick={() => setUpdateStatus("InActive")}
                    className={`flex-1 px-4 cursor-pointer py-2 rounded-lg text-sm font-medium transition-all ${
                      updateStatus === "InActive"
                        ? "bg-primary text-white"
                        : "bg-secondary/50 text-muted-foreground hover:bg-secondary"
                    }`}
                  >
                    InActive (Save/Draft)
                  </button>
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  {updateStatus === "Active" 
                    ? "Post will be visible to everyone" 
                    : "Post will be saved as draft"}
                </p>
              </div>
            </div>
            
            <div className="flex justify-end gap-3 p-4 border-t border-border/50 sticky bottom-0 bg-card">
              <button
                onClick={() => {
                  setOpenUpdateYourIdea(false);
                  setSelectedPost(null);
                  setUpdateDescription("");
                  setUpdateCategory("");
                  setUpdateStatus("Active");
                  setPostID(null);
                  setUpdateImages([]);
                  setUpdateRemovedImages([]);
                  setUpdateNewImages([]);
                  imagePreviewUrls.forEach(url => URL.revokeObjectURL(url));
                  setImagePreviewUrls([]);
                }}
                className="px-4 py-2 cursor-pointer text-sm text-muted-foreground hover:bg-secondary rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleUpdatePost}
                disabled={updatingPost || !updateDescription.trim()}
                className="px-4 py-2 text-sm cursor-pointer bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-2"
              >
                {updatingPost && <Loader2 className="w-4 h-4 animate-spin" />}
                Update Post
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}