'use client';

import React, { useState, useEffect, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import Image from "next/image";
import Link from "next/link";
import { 
  Loader, 
  Bookmark, 
  Clock, 
  ChevronRight,
  Sparkles,
  MoreHorizontal,
  Flag,
  Share2,
  AlertTriangle,
  Loader2,
  Check,
} from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { RootState } from "@/lib/store/store";
import { getSavedPosts, unSavePostAPI, likeDislike, addFlagReport, hidePostDuration } from "@/lib/api/client";
import { toast } from "sonner";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
const POSTS_PER_PAGE = parseInt(process.env.NEXT_PUBLIC_POSTS_PER_PAGE || "10");

// Play icon component for video
function Play({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M8 5v14l11-7z" />
    </svg>
  );
}

function FileText({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <line x1="16" y1="13" x2="8" y2="13" />
      <line x1="16" y1="17" x2="8" y2="17" />
      <polyline points="10 9 9 9 8 9" />
    </svg>
  );
}

function truncateUrl(url: string, maxLength = 40): string {
  if (url.length <= maxLength) return url;
  return url.slice(0, maxLength) + "...";
}

interface SavedPost {
  _id: string;
  description?: string;
  createdAt: string;
  timeAgo?: string;
  customerID?: {
    _id: string;
    fullName?: string;
    userName?: string;
    imageURL?: string;
    countryFlag?: string;
  };
  postCategory?: {
    mainCategoryName?: string;
  };
  counts?: {
    likes: number;
    dislikes: number;
  };
  likeStatus?: "like" | "dislike" | null;
  bookmarked?: boolean;
  media?: any[];
  aiScore?: number;
}

interface SavedPageData {
  mainImage?: string;
  pageTitle?: string;
  description?: string;
}

interface SharingIcon {
  _id: string;
  socialTitle: string;
  socialIcon: string;
  socialLink: string;
}

interface LogoImage {
  securityKey?: string;
  loaderImage?: string;
  [key: string]: any;
}

interface SavedContentProps {
  savedPageData: SavedPageData;
  sharingIcons: SharingIcon[];
  logoImage: LogoImage;
}

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 formatTimeAgo = (date: string) => {
  const now = new Date();
  const past = new Date(date);
  const diffMs = now.getTime() - past.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) return "Just now";
  if (diffMins < 60) return `${diffMins} min ago`;
  if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
  if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
  return past.toLocaleDateString();
};

// Helper function to get user display name
const getUserDisplayName = (customer: any) => {
  if (!customer) return "Unknown User";
  return customer.fullName || 
         customer.name || 
         customer.displayName ||
         customer.businessName ||
         "Unknown User";
};

// Helper function to get user handle
const getUserHandle = (customer: any) => {
  if (!customer) return "@user";
  return customer.userName || 
         customer.username ||
         `@${customer.email?.split('@')[0] || 'user'}`;
};

const SavedContent = ({ savedPageData, sharingIcons, logoImage }: SavedContentProps) => {
  const router = useRouter();
  const dispatch = useDispatch();
  const { accessToken, currentCustomer } = useSelector((state: RootState) => state.user);
  
  const [posts, setPosts] = useState<SavedPost[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const [unsaveLoading, setUnsaveLoading] = useState<string | null>(null);
  const [copySuccess, setCopySuccess] = useState(false);

  
  // State for modals and loading
  const [showHideModal, setShowHideModal] = useState<string | null>(null);
  const [isHiding, setIsHiding] = useState(false);
  const [reportingReason, setReportingReason] = useState<string | null>(null);
  const [showShareModal, setShowShareModal] = useState<string | null>(null);

  // ✅ 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 [isDarkMode, setIsDarkMode] = useState(false);

  // 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();
    };
  }, []);

  const bgImage = savedPageData?.mainImage 
    ? `${BASE_URL.replace(/\/$/, "")}/${savedPageData.mainImage.replace(/^\//, "")}` 
    : null;

  // Fetch saved posts
  const fetchSavedPosts = useCallback(async (pageNum: number, isRefresh = false) => {
    if (!accessToken) return;

    if (pageNum === 1) {
      setLoading(true);
    } else {
      setIsFetchingMore(true);
    }
    setError(null);

    try {
      const result = await getSavedPosts(
        accessToken,
        pageNum,
        POSTS_PER_PAGE,
        "",
        logoImage?.securityKey
      );

      if (result.success) {
        const newPosts = result.posts || [];

        const formattedPosts = newPosts.map((post: any) => ({
          ...post,
          timeAgo: formatTimeAgo(post.createdAt)
        }));

        if (isRefresh || pageNum === 1) {
          setPosts(formattedPosts);
        } else {
          setPosts(prev => [...prev, ...formattedPosts]);
        }

        setHasMore(newPosts.length === POSTS_PER_PAGE);
        setPage(pageNum);
        
        if (newPosts.length === 0 && pageNum === 1) {
          setError("No saved posts found");
        }
      } else {
        setError(result.message || "Failed to load saved posts");
        if (isRefresh || pageNum === 1) setPosts([]);
      }
    } catch (error) {
      console.error("Error fetching saved posts:", error);
      setError("Failed to load saved posts");
      if (isRefresh || pageNum === 1) setPosts([]);
    } finally {
      setLoading(false);
      setIsFetchingMore(false);
    }
  }, [accessToken, logoImage?.securityKey]);

  // Handle unsave
  const handleUnsave = async (postId: string) => {
    if (!accessToken) return;
    
    setUnsaveLoading(postId);
    try {
      const result = await unSavePostAPI(accessToken, postId, logoImage?.securityKey);
      if (result.success) {
        setPosts(prev => prev.filter(post => post._id !== postId));
        toast.success("Post removed from saved");
      } else {
        toast.error(result.message || "Failed to unsave post");
      }
    } catch (error) {
      toast.error("Failed to unsave post");
    } finally {
      setUnsaveLoading(null);
    }
  };

  // ✅ Fixed Debounced Like Handler
  const handleLike = async (postId: string) => {
    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 currentPost = posts.find(p => p._id === postId);
    if (!currentPost) {
      isProcessingRef.current = false;
      return;
    }
    
    const wasLiked = currentPost.likeStatus === "like";
    const wasDisliked = currentPost.likeStatus === "dislike";
    
    // Optimistic update
    setPosts(prev => prev.map(post => {
      if (post._id === postId) {
        let newLikes = post.counts?.likes || 0;
        let newDislikes = post.counts?.dislikes || 0;
        let newStatus = null;
        
        if (wasLiked) {
          newLikes -= 1;
          newStatus = null;
        } else {
          newLikes += 1;
          newStatus = "like";
          if (wasDisliked) {
            newDislikes -= 1;
          }
        }
        
        return {
          ...post,
          likeStatus: newStatus,
          counts: { likes: newLikes, dislikes: newDislikes }
        };
      }
      return post;
    }));
    
    try {
      const result = await likeDislike(accessToken, postId, "like", logoImage?.securityKey);
      
      if (result.success) {
        setPosts(prev => prev.map(post => {
          if (post._id === postId) {
            return {
              ...post,
              likeStatus: result.data.userReaction,
              counts: result.data.counts
            };
          }
          return post;
        }));
      } else {
        // Rollback - refetch
        fetchSavedPosts(page, true);
        toast.error(result.message || "Could not like the post");
      }
    } catch (error: any) {
      if (error?.name === 'AbortError') return;
      fetchSavedPosts(page, true);
      toast.error("Could not like the post");
    } finally {
      isProcessingRef.current = false;
    }
  };

  // ✅ Fixed Debounced Dislike Handler
  const handleDislike = async (postId: string) => {
    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 currentPost = posts.find(p => p._id === postId);
    if (!currentPost) {
      isProcessingRef.current = false;
      return;
    }
    
    const wasLiked = currentPost.likeStatus === "like";
    const wasDisliked = currentPost.likeStatus === "dislike";
    
    // Optimistic update
    setPosts(prev => prev.map(post => {
      if (post._id === postId) {
        let newLikes = post.counts?.likes || 0;
        let newDislikes = post.counts?.dislikes || 0;
        let newStatus = null;
        
        if (wasDisliked) {
          newDislikes -= 1;
          newStatus = null;
        } else {
          newDislikes += 1;
          newStatus = "dislike";
          if (wasLiked) {
            newLikes -= 1;
          }
        }
        
        return {
          ...post,
          likeStatus: newStatus,
          counts: { likes: newLikes, dislikes: newDislikes }
        };
      }
      return post;
    }));
    
    try {
      const result = await likeDislike(accessToken, postId, "dislike", logoImage?.securityKey);
      
      if (result.success) {
        setPosts(prev => prev.map(post => {
          if (post._id === postId) {
            return {
              ...post,
              likeStatus: result.data.userReaction,
              counts: result.data.counts
            };
          }
          return post;
        }));
      } else {
        // Rollback - refetch
        fetchSavedPosts(page, true);
        toast.error(result.message || "Could not dislike the post");
      }
    } catch (error: any) {
      if (error?.name === 'AbortError') return;
      fetchSavedPosts(page, true);
      toast.error("Could not dislike the post");
    } finally {
      isProcessingRef.current = false;
    }
  };

  // Handle report - direct submit
  const handleReport = async (postId: string, reason: string) => {
    if (!accessToken) {
      toast.error("Please login to report");
      return;
    }

    setReportingReason(reason);
    
    try {
      const result = await addFlagReport(accessToken, postId, reason, logoImage?.securityKey);
      
      if (result.success) {
        toast.success(`Report submitted successfully for: ${reason}`);
      } else {
        toast.error(result.message || "Failed to submit report");
      }
    } catch (error) {
      console.error("Error reporting post:", error);
      toast.error("Failed to submit report");
    } finally {
      setReportingReason(null);
    }
  };

  // Handle hide post
  const handleHide = (postId: string) => {
    setShowHideModal(postId);
  };

  const submitHide = async (postId: string) => {
    if (!accessToken) return;
    
    setIsHiding(true);
    
    try {
      const permanentDate = new Date();
      permanentDate.setFullYear(permanentDate.getFullYear() + 10);
      
      const result = await hidePostDuration(accessToken, postId, permanentDate.toISOString(), logoImage?.securityKey);
      
      if (result.success) {
        toast.success("Post hidden successfully");
        setShowHideModal(null);
        setPosts(prev => prev.filter(post => post._id !== postId));
      } else {
        toast.error(result.message || "Failed to hide post");
      }
    } catch (error) {
      console.error("Error hiding post:", error);
      toast.error("Failed to hide post");
    } finally {
      setIsHiding(false);
    }
  };

  // Handle share
  const handleShare = (postId: string) => {
    setShowShareModal(postId);
  };

  const copyToClipboard = async (postId: string, postContent: string) => {
  const ideaUrl = `${BASE_URL}/idea/${postId}`;
  try {
    await navigator.clipboard.writeText(ideaUrl);
    setCopySuccess(true);
    setTimeout(() => setCopySuccess(false), 2000);
    toast.success("Link copied to clipboard!");
  } catch (err) {
    toast.error("Failed to copy link");
  }
};

  const shareOnSocial = (platform: string, postId: string, postContent: string) => {
    let shareUrl = "";
    const ideaUrl = `${BASE_URL}/idea/${postId}`;
    const text = encodeURIComponent(`Check out this idea: ${postContent.slice(0, 100)}...`);
    const url = encodeURIComponent(ideaUrl);

    switch (platform) {
      case "facebook":
        shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`;
        break;
      case "twitter":
        shareUrl = `https://twitter.com/intent/tweet?text=${text}&url=${url}`;
        break;
      case "linkedin":
        shareUrl = `https://www.linkedin.com/shareArticle?mini=true&url=${url}&title=${text}`;
        break;
      case "whatsapp":
        shareUrl = `https://wa.me/?text=${text} ${url}`;
        break;
      case "email":
        shareUrl = `mailto:?subject=Check out this idea&body=${text}%0A%0A${url}`;
        break;
      default:
        return;
    }

    window.open(shareUrl, "_blank", "noopener,noreferrer");
    setShowShareModal(null);
  };

  // Load more
  const loadMore = () => {
    if (!loading && hasMore && !isFetchingMore) {
      fetchSavedPosts(page + 1);
    }
  };

  // Initial fetch
  useEffect(() => {
    if (accessToken) {
      fetchSavedPosts(1, true);
    }
  }, [accessToken, fetchSavedPosts]);

  useEffect(() => {
    if (!currentCustomer && !accessToken) {
      router.push("/login");
    }
  }, [currentCustomer, accessToken, router]);

  // Get current post for modals
  const currentPost = showHideModal ? posts.find(p => p._id === showHideModal) : null;
  const sharePost = showShareModal ? posts.find(p => p._id === showShareModal) : null;

  if (!currentCustomer && !accessToken) {
    return null;
  }

  return (
    <div className="w-full">
      <div className="flex flex-col gap-6">
        {/* Header */}
        <div className="flex flex-col gap-2">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-primary/10 rounded-xl">
              <Bookmark className="w-6 h-6 text-primary" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-foreground">Saved Ideas</h1>
              <p className="text-muted-foreground mt-1">
                Ideas you've bookmarked for later
              </p>
            </div>
          </div>
        </div>

        {/* Loading State with skeleton */}
        {loading && posts.length === 0 && (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="h-6 w-32 bg-gray-300 dark:bg-gray-700 rounded animate-pulse" />
            </div>
            <div className="space-y-4">
              {[1, 2, 3, 4, 5].map((i) => (
                <div key={i} className="bg-card rounded-2xl p-5 border animate-pulse">
                  <div className="flex items-start justify-between gap-4 mb-4">
                    <div className="flex items-center gap-3">
                      <div className="w-11 h-11 rounded-full bg-gray-300 dark:bg-gray-700" />
                      <div>
                        <div className="h-5 w-32 bg-gray-300 dark:bg-gray-700 rounded mb-1" />
                        <div className="h-4 w-20 bg-gray-300 dark:bg-gray-700 rounded" />
                      </div>
                    </div>
                    <div className="w-8 h-8 rounded-lg bg-gray-300 dark:bg-gray-700" />
                  </div>
                  <div className="mt-2">
                    <div className="w-20 h-6 bg-gray-300 dark:bg-gray-700 rounded-full mb-2" />
                    <div className="space-y-2">
                      <div className="h-4 w-full bg-gray-300 dark:bg-gray-700 rounded" />
                      <div className="h-4 w-3/4 bg-gray-300 dark:bg-gray-700 rounded" />
                    </div>
                  </div>
                  <div className="mt-4">
                    <div className="grid grid-cols-2 gap-2">
                      <div className="aspect-square rounded-xl bg-gray-300 dark:bg-gray-700" />
                      <div className="aspect-square rounded-xl bg-gray-300 dark:bg-gray-700" />
                    </div>
                  </div>
                  <div className="mt-5 flex items-center justify-between pt-4 border-t border-border/30">
                    <div className="flex items-center gap-1">
                      <div className="w-12 h-9 bg-gray-300 dark:bg-gray-700 rounded-xl" />
                      <div className="w-12 h-9 bg-gray-300 dark:bg-gray-700 rounded-xl" />
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-16 h-4 bg-gray-300 dark:bg-gray-700 rounded" />
                      <div className="w-12 h-9 bg-gray-300 dark:bg-gray-700 rounded-lg" />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Empty State */}
        {!loading && posts.length === 0 && !error && (
          <div className="flex flex-col items-center justify-center py-20 bg-card rounded-2xl border">
            {bgImage ? (
              <Image
                width={200}
                height={150}
                src={bgImage}
                alt="No saved ideas"
                className="w-48 h-36 object-contain mb-6"
                priority
              />
            ) : (
              <div className="p-6 bg-secondary rounded-2xl mb-6">
                <Bookmark className="w-16 h-16 text-muted-foreground" />
              </div>
            )}
            <h3 className="text-xl font-bold text-foreground mb-2">
              No Saved Ideas
            </h3>
            <p className="text-muted-foreground text-center max-w-md">
              You haven't saved any ideas yet. Bookmark interesting ideas to see them here.
            </p>
            <button 
              onClick={() => router.push('/home')}
              className="mt-6 px-6 py-2 bg-primary text-primary-foreground font-medium rounded-xl hover:bg-primary/90 transition-colors"
            >
              Explore Ideas
            </button>
          </div>
        )}

        {/* Error State */}
        {error && posts.length === 0 && (
          <div className="flex flex-col items-center justify-center py-20 bg-card rounded-2xl border">
            <div className="p-6 bg-secondary rounded-2xl mb-6">
              <Bookmark className="w-16 h-16 text-muted-foreground" />
            </div>
            <p className="text-muted-foreground text-center max-w-md">{error}</p>
            <button 
              onClick={() => fetchSavedPosts(1, true)}
              className="mt-6 px-6 py-2 bg-primary text-primary-foreground font-medium rounded-xl hover:bg-primary/90 transition-colors"
            >
              Refresh
            </button>
          </div>
        )}

        {/* Saved Posts List */}
        {!loading && posts.length > 0 && (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-foreground">
                Your Saved Ideas ({posts.length})
              </h2>
            </div>
            
            <div className="space-y-4">
              {posts.map((post) => {
                const isLiked = post.likeStatus === "like";
                const isDisliked = post.likeStatus === "dislike";
                const userName = getUserDisplayName(post.customerID);
                const userHandle = getUserHandle(post.customerID);
                const userAvatar = post.customerID?.imageURL 
                  ? `${BASE_URL}/uploads/${post.customerID.imageURL}` 
                  : undefined;

                return (
                  <div
                    key={post._id}
                    className="bg-card rounded-2xl p-5 border hover:shadow-md transition-all duration-200"
                  >
                    {/* Header */}
                    <div className="flex items-start justify-between gap-4 mb-4">
                      <div className="flex items-center gap-3">
                        <div className="relative">
                          <Avatar className="h-11 w-11 ring-2 ring-border">
                            {userAvatar ? (
                              <AvatarImage src={userAvatar} alt={userName} />
                            ) : null}
                            <AvatarFallback className="bg-secondary text-foreground font-semibold">
                              {getInitials(userName)}
                            </AvatarFallback>
                          </Avatar>
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <h4 className="font-semibold text-foreground">
                              {userName}
                            </h4>
                            {post.aiScore && post.aiScore >= 80 && (
                              <div className="flex items-center gap-1 rounded-full bg-primary/20 px-2 py-0.5">
                                <Sparkles className="h-3 w-3 text-primary" />
                                <span className="text-[10px] font-bold text-primary">{post.aiScore}%</span>
                              </div>
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground">
                            {userHandle}
                          </p>
                        </div>
                      </div>

                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <button className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary transition-colors">
                            <MoreHorizontal className="h-5 w-5 cursor-pointer" />
                          </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="glass glass-border w-36">
                          <DropdownMenuItem onClick={() => handleShare(post._id)} className="gap-2 cursor-pointer">
                            <Share2 className="h-4 w-4" />
                            Share
                          </DropdownMenuItem>
                          
                          <DropdownMenuItem onClick={() => handleReport(post._id, "It's Spam")} disabled={reportingReason === "It's Spam"} className="gap-2 cursor-pointer">
                            {reportingReason === "It's Spam" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Flag className="h-4 w-4" />}
                            It's Spam
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleReport(post._id, "Flag Objectionable")} disabled={reportingReason === "Flag Objectionable"} className="gap-2 cursor-pointer">
                            {reportingReason === "Flag Objectionable" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Flag className="h-4 w-4" />}
                            Flag Objectionable
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleReport(post._id, "Abusive Content")} disabled={reportingReason === "Abusive Content"} className="gap-2 cursor-pointer">
                            {reportingReason === "Abusive Content" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Flag className="h-4 w-4" />}
                            Abusive Content
                          </DropdownMenuItem>
                          
                          <DropdownMenuItem onClick={() => handleHide(post._id)} className="gap-2 cursor-pointer">
                            <AlertTriangle className="h-4 w-4" />
                            Hide
                          </DropdownMenuItem>
                          
                          <DropdownMenuSeparator />
                          
                          <DropdownMenuItem onClick={() => handleUnsave(post._id)} disabled={unsaveLoading === post._id} className="gap-2 cursor-pointer">
                            {unsaveLoading === post._id ? <Loader className="h-4 w-4 animate-spin" /> : <Bookmark className="h-4 w-4" />}
                            Remove from Saved
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>

                    {/* Content */}
                    <div className="mt-2">
                      {post.postCategory?.mainCategoryName && (
                        <span className="mb-2 inline-block rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
                          {post.postCategory.mainCategoryName}
                        </span>
                      )}
                      <p 
                        onClick={() => router.push(`/idea/${post._id}`)}
                        className="text-foreground leading-relaxed cursor-pointer hover:text-primary transition-colors"
                      >
                        {post.description || "No description"}
                      </p>
                    </div>

                    {/* Media Attachments */}
                    {post.media && post.media.length > 0 && (
                      <div className="mt-4">
                        <div className="grid grid-cols-2 gap-2">
                          {post.media.slice(0, 4).map((media, idx) => (
                            <div key={idx} className="relative rounded-xl overflow-hidden bg-secondary aspect-square">
                              {media.type === "image" ? (
                                <img
                                  src={`${BASE_URL}/uploads/${media.url}`}
                                  alt={media.name || "Attachment"}
                                  className="w-full h-full object-cover"
                                />
                              ) : media.type === "video" ? (
                                <div className="relative w-full h-full">
                                  <img src={media.thumbnail || "/placeholder.svg"} alt={media.name || "Video"} className="w-full h-full object-cover" />
                                  <div className="absolute inset-0 flex items-center justify-center bg-background/40">
                                    <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/90">
                                      <Play className="h-5 w-5 ml-0.5 text-white" />
                                    </div>
                                  </div>
                                </div>
                              ) : (
                                <div className="flex items-center justify-center w-full h-full">
                                  <FileText className="h-8 w-8 text-muted-foreground" />
                                </div>
                              )}
                              {post.media.length > 4 && idx === 3 && (
                                <div className="absolute inset-0 bg-background/80 flex items-center justify-center">
                                  <span className="text-lg font-bold text-foreground">+{post.media.length - 4}</span>
                                </div>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* ✅ Actions - Same as IdeaFeed */}
                    <div className="mt-5 flex items-center justify-between border-t border-border/30 pt-4">
                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => handleLike(post._id)}
                          className={cn(
                            "flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-all cursor-pointer",
                            isLiked ? " " : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                          )}
                        >
                          <Image
                            src={isLiked ? getFilledLikeIcon() : getUnfilledLikeIcon()}
                            alt="like"
                            width={28}
                            height={28}
                            className="w-7 h-7"
                          />
                          <span>{post.counts?.likes || 0}</span>
                        </button>

                        <button
                          onClick={() => handleDislike(post._id)}
                          className={cn(
                            "flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-all cursor-pointer",
                            isDisliked ? " " : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                          )}
                        >
                          <Image
                            src={isDisliked ? getFilledDislikeIcon() : getUnfilledDislikeIcon()}
                            alt="dislike"
                            width={28}
                            height={28}
                            className="w-7 h-7"
                          />
                          <span>{post.counts?.dislikes || 0}</span>
                        </button>
                      </div>

                      <div className="flex items-center gap-2">
                        <span className="text-xs text-muted-foreground flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {post.timeAgo || formatTimeAgo(post.createdAt)}
                        </span>
                        <Link
                          href={`/idea/${post._id}`}
                          className="flex h-9 items-center gap-1 rounded-lg px-3 text-sm font-medium text-primary hover:bg-primary/10 transition-all"
                        >
                          View
                          <ChevronRight className="h-4 w-4" />
                        </Link>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Load More */}
            {hasMore && posts.length > 0 && !loading && (
              <div className="flex justify-center pt-4">
                <button
                  onClick={loadMore}
                  disabled={isFetchingMore}
                  className="rounded-xl bg-secondary/50 px-8 py-3 text-sm font-medium text-muted-foreground hover:bg-secondary hover:text-foreground transition-all disabled:opacity-50"
                >
                  {isFetchingMore ? (
                    <div className="flex items-center gap-2">
                      <Loader className="w-4 h-4 animate-spin" />
                      Loading...
                    </div>
                  ) : (
                    "Load More"
                  )}
                </button>
              </div>
            )}

            {/* End Message */}
            {!hasMore && posts.length > 0 && (
              <div className="text-center py-4">
                <p className="text-muted-foreground text-sm">
                  You've seen all your saved ideas
                </p>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Hide Post Modal */}
      <Dialog open={!!showHideModal} onOpenChange={() => setShowHideModal(null)}>
        <DialogContent className="sm:max-w-md glass glass-border">
          <DialogHeader>
            <div className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-amber-500" />
              <DialogTitle>Hide Post</DialogTitle>
            </div>
            <DialogDescription>
              Are you sure you want to hide {currentPost?.customerID?.fullName || "this user"}'s post?
            </DialogDescription>
          </DialogHeader>
          
          <div className="flex justify-end gap-2 mt-4">
            <button
              onClick={() => setShowHideModal(null)}
              className="px-4 py-2 rounded-lg text-sm font-medium text-muted-foreground hover:bg-secondary transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={() => showHideModal && submitHide(showHideModal)}
              disabled={isHiding}
              className="px-4 py-2 rounded-lg text-sm font-medium bg-[#0084a5] text-white hover:bg-[#006a85] disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-2"
            >
              {isHiding && <Loader2 className="h-4 w-4 animate-spin" />}
              Hide Permanently
            </button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Share Modal */}
      <Dialog open={!!showShareModal} onOpenChange={() => setShowShareModal(null)}>
  <DialogContent className="w-[calc(100%-1rem)] sm:max-w-md glass glass-border">
    <DialogHeader>
      <DialogTitle>Share this idea</DialogTitle>
      <DialogDescription>
        Share this idea with your friends and network
      </DialogDescription>
    </DialogHeader>
    
    <div className="flex flex-col gap-4 py-4">
      <div className="flex items-center gap-2 w-full min-w-0 max-w-full">
        <div className="flex items-center gap-2 rounded-lg bg-secondary/50 px-3 py-2 flex-1 min-w-0 max-w-[calc(100%-44px)] overflow-hidden">
          <LinkIcon className="h-4 w-4 text-muted-foreground shrink-0" />
          <span className="text-sm text-foreground truncate min-w-0 block">
            {truncateUrl(`${BASE_URL}/idea/${showShareModal}`)}
          </span>
        </div>
        <button
          onClick={() => sharePost && copyToClipboard(sharePost._id, sharePost.description || "")}
          className="flex cursor-pointer h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-colors"
        >
          {copySuccess ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
        </button>
      </div>

      <div className="grid grid-cols-4 gap-1 sm:gap-2">
        <button onClick={() => sharePost && shareOnSocial("facebook", sharePost._id, sharePost.description || "")} className="flex cursor-pointer flex-col items-center gap-1 p-2 rounded-lg hover:bg-secondary transition-colors">
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#1877F2]/10 text-[#1877F2]"><Facebook className="h-5 w-5" /></div>
          <span className="text-xs text-muted-foreground">Facebook</span>
        </button>
        <button onClick={() => sharePost && shareOnSocial("twitter", sharePost._id, sharePost.description || "")} className="flex cursor-pointer flex-col items-center gap-1 p-2 rounded-lg hover:bg-secondary transition-colors">
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#1DA1F2]/10 text-[#1DA1F2]"><Twitter className="h-5 w-5" /></div>
          <span className="text-xs text-muted-foreground">Twitter</span>
        </button>
        <button onClick={() => sharePost && shareOnSocial("linkedin", sharePost._id, sharePost.description || "")} className="flex cursor-pointer flex-col items-center gap-1 p-2 rounded-lg hover:bg-secondary transition-colors">
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#0077B5]/10 text-[#0077B5]"><Linkedin className="h-5 w-5" /></div>
          <span className="text-xs text-muted-foreground">LinkedIn</span>
        </button>
        <button onClick={() => sharePost && shareOnSocial("whatsapp", sharePost._id, sharePost.description || "")} className="flex cursor-pointer flex-col items-center gap-1 p-2 rounded-lg hover:bg-secondary transition-colors">
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#25D366]/10 text-[#25D366]"><MessageCircle className="h-5 w-5" /></div>
          <span className="text-xs text-muted-foreground">WhatsApp</span>
        </button>
      </div>
    </div>
  </DialogContent>
</Dialog>

    </div>
  );
};

// Helper icons
function LinkIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
      <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
    </svg>
  );
}

function Copy({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
    </svg>
  );
}

function Facebook({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />
    </svg>
  );
}

function Twitter({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z" />
    </svg>
  );
}

function Linkedin({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z" />
      <rect x="2" y="9" width="4" height="12" />
      <circle cx="4" cy="4" r="2" />
    </svg>
  );
}

function MessageCircle({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
    </svg>
  );
}

export default SavedContent;