// components/dashboard/idea-card.tsx
'use client';

import { useEffect, useState, useRef, useCallback } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation"; // ✅ Add this import
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Bookmark,
  Share2,
  MoreHorizontal,
  Flag,
  Sparkles,
  TrendingUp,
  ChevronRight,
  Loader2,
  AlertTriangle,
} from "lucide-react";
import Image from "next/image";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useDispatch, useSelector } from "react-redux";
import { likeDislike, savePostAPI, unSavePostAPI, addFlagReport, hidePostDuration } from "@/lib/api/client";
import { toast } from "sonner";
import { RootState } from "@/lib/store/store";

interface Attachment {
  type: "image" | "pdf" | "doc" | "video";
  url: string;
  name: string;
  thumbnail?: string;
}

interface IdeaCardProps {
  idea: {
    id: string;
    author: {
      name: string;
      username: string;
      avatar?: string;
      country?: string;
      _id?: string; // ✅ Make sure _id is available
    };
    content: string;
    category?: string;
    likes: number;
    dislikes: number;
    timestamp: string;
    isTrending?: boolean;
    aiScore?: number;
    attachments?: Attachment[];
    likeStatus?: "like" | "dislike" | null;
    bookmarked?: boolean;
    isOwner?: boolean;
  };
  onUpdate?: (updatedIdea: any) => void;
  onDelete?: (postId: string) => void;
}

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;


function truncateUrl(url: string, maxLength = 40): string {
  if (url.length <= maxLength) return url;
  return url.slice(0, maxLength) + "...";
}

export function IdeaCard({ idea, onUpdate, onDelete }: IdeaCardProps) {
  const router = useRouter(); // ✅ Initialize router
  const { accessToken, currentCustomer, dynamicImages } = useSelector((state: RootState) => state.user);
  const securityKey = dynamicImages?.securityKey;

  // ✅ Handler for navigating to user profile
  const handleAuthorClick = (e: React.MouseEvent) => {
    e.stopPropagation(); // Prevent triggering the post click
    if (idea.author.username) {
      router.push(`/${idea.author.username}`);
    } else if (idea.author._id) {
      router.push(`/profile/${idea.author._id}`);
    }
  };

  // ✅ Refs for debouncing and request cancellation
  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 lastActionRef = useRef<"like" | "dislike" | null>(null);

  const [liked, setLiked] = useState(idea.likeStatus === "like");
  const [disliked, setDisliked] = useState(idea.likeStatus === "dislike");
  const [saved, setSaved] = useState(idea.bookmarked || false);
  const [likes, setLikes] = useState(idea.likes);
  const [dislikes, setDislikes] = useState(idea.dislikes);
  const [isSaving, setIsSaving] = useState(false);
  
  const [showShareModal, setShowShareModal] = useState(false);
  const [copySuccess, setCopySuccess] = useState(false);
  const [showHideModal, setShowHideModal] = useState(false);
  const [isHiding, setIsHiding] = useState(false);
  const [reportingReason, setReportingReason] = useState<string | null>(null);

  const ideaUrl = `${BASE_URL}/idea/${idea.id}`;
  const isOwner = idea.isOwner || (currentCustomer?.customer?._id === idea.author._id);

  const [isDarkMode, setIsDarkMode] = useState(false);

  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();
  }, []);

  // ✅ Cleanup on unmount
  useEffect(() => {
    return () => {
      if (likeTimeoutRef.current) clearTimeout(likeTimeoutRef.current);
      if (dislikeTimeoutRef.current) clearTimeout(dislikeTimeoutRef.current);
      if (abortControllerRef.current) abortControllerRef.current?.abort();
    };
  }, []);

  const getFilledLikeIcon = () => isDarkMode ? "/icons/dark-likefilled.svg" : "/icons/like-filled.svg";
  const getFilledDislikeIcon = () => isDarkMode ? "/icons/dark-dislikefilled.svg" : "/icons/dislike_filled.svg";
  const getUnfilledLikeIcon = () => isDarkMode ? "/icons/like-dark.svg" : "/icons/like_unfilled.svg";
  const getUnfilledDislikeIcon = () => isDarkMode ? "/icons/dislike-dark.svg" : "/icons/dislike_unfilled.svg";


// components/dashboard/idea-card.tsx

const handleLike = useCallback(async () => {
  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 = liked;
  const wasDisliked = disliked;
  const currentLikesCount = likes;
  const currentDislikesCount = dislikes;

  // Optimistic update - UI instantly changes
  if (wasLiked) {
    // Removing like
    setLiked(false);
    setLikes(prev => prev - 1);
  } else {
    // Adding like
    setLiked(true);
    setLikes(prev => prev + 1);
    if (wasDisliked) {
      setDisliked(false);
      setDislikes(prev => prev - 1);
    }
  }

  try {
    const result = await likeDislike(accessToken, idea.id, "like", securityKey);
    
    console.log("🔍 Like API Response:", result);

    if (result.success) {
      // ✅ IMPORTANT: Get counts from API response
      const apiUserReaction = result.data?.userReaction;
      const apiLikes = result.data?.counts?.likes;
      const apiDislikes = result.data?.counts?.dislikes;
      
      console.log("📊 API Returned - Likes:", apiLikes, "Dislikes:", apiDislikes, "Reaction:", apiUserReaction);
      
      // ✅ Update with API response values
      setLikes(apiLikes);
      setDislikes(apiDislikes);
      setLiked(apiUserReaction === "like");
      setDisliked(apiUserReaction === "dislike");

      // Update parent component
      if (onUpdate) {
        onUpdate({
          id: idea.id,
          likeStatus: apiUserReaction,
          likes: apiLikes,
          dislikes: apiDislikes,
        });
      }
    } else {
      // Rollback on failure
      setLiked(wasLiked);
      setLikes(currentLikesCount);
      setDisliked(wasDisliked);
      setDislikes(currentDislikesCount);
      toast.error(result.message || "Could not like the post");
    }
  } catch (error: any) {
    if (error?.name === 'AbortError') return;
    console.error("Like error:", error);
    // Rollback
    setLiked(wasLiked);
    setLikes(currentLikesCount);
    setDisliked(wasDisliked);
    setDislikes(currentDislikesCount);
    toast.error("Could not like the post");
  } finally {
    isProcessingRef.current = false;
  }
}, [accessToken, idea.id, liked, disliked, likes, dislikes, securityKey, onUpdate]);

// 🔥 FIXED handleDislike function
const handleDislike = useCallback(async () => {
  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 = liked;
  const wasDisliked = disliked;
  const currentLikesCount = likes;
  const currentDislikesCount = dislikes;

  // Optimistic update
  if (wasDisliked) {
    setDisliked(false);
    setDislikes(prev => prev - 1);
  } else {
    setDisliked(true);
    setDislikes(prev => prev + 1);
    if (wasLiked) {
      setLiked(false);
      setLikes(prev => prev - 1);
    }
  }

  try {
    const result = await likeDislike(accessToken, idea.id, "dislike", securityKey);
    
    console.log("🔍 Dislike API Response:", result);

    if (result.success) {
      const apiUserReaction = result.data?.userReaction;
      const apiLikes = result.data?.counts?.likes;
      const apiDislikes = result.data?.counts?.dislikes;
      
      console.log("📊 API Returned - Likes:", apiLikes, "Dislikes:", apiDislikes, "Reaction:", apiUserReaction);
      
      setLikes(apiLikes);
      setDislikes(apiDislikes);
      setLiked(apiUserReaction === "like");
      setDisliked(apiUserReaction === "dislike");

      if (onUpdate) {
        onUpdate({
          id: idea.id,
          likeStatus: apiUserReaction,
          likes: apiLikes,
          dislikes: apiDislikes,
        });
      }
    } else {
      // Rollback
      setLiked(wasLiked);
      setLikes(currentLikesCount);
      setDisliked(wasDisliked);
      setDislikes(currentDislikesCount);
      toast.error(result.message || "Could not dislike the post");
    }
  } catch (error: any) {
    if (error?.name === 'AbortError') return;
    console.error("Dislike error:", error);
    // Rollback
    setLiked(wasLiked);
    setLikes(currentLikesCount);
    setDisliked(wasDisliked);
    setDislikes(currentDislikesCount);
    toast.error("Could not dislike the post");
  } finally {
    isProcessingRef.current = false;
  }
}, [accessToken, idea.id, liked, disliked, likes, dislikes, securityKey, onUpdate]);

  const handleSave = async () => {
    if (!accessToken) {
      toast.error("Please login to save posts");
      return;
    }
    if (isSaving) return;

    setIsSaving(true);
    const wasSaved = saved;
    setSaved(!saved);

    try {
      let result;
      if (!wasSaved) {
        result = await savePostAPI(accessToken, idea.id, securityKey);
      } else {
        result = await unSavePostAPI(accessToken, idea.id, securityKey);
      }

      if (result.success) {
        toast.success(wasSaved ? "Post unsaved" : "Post saved");
        if (onUpdate) {
          onUpdate({ ...idea, bookmarked: !wasSaved });
        }
      } else {
        setSaved(wasSaved);
        toast.error(result.message || "Could not save post");
      }
    } catch (error) {
      setSaved(wasSaved);
      toast.error("Could not save post");
    } finally {
      setIsSaving(false);
    }
  };

 

  const copyToClipboard = async () => {
    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) => {
    let shareUrl = "";
    const text = encodeURIComponent(`Check out this idea: ${idea.content.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(false);
  };

  const handleReport = async (reason: string) => {
    if (!accessToken) {
      toast.error("Please login to report");
      return;
    }

    setReportingReason(reason);
    
    try {
      const result = await addFlagReport(accessToken, idea.id, reason, 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);
    }
  };

  const handleHide = () => {
    setShowHideModal(true);
  };

  const submitHide = async () => {
    if (!accessToken) return;
    
    setIsHiding(true);
    
    try {
      const permanentDate = new Date();
      permanentDate.setFullYear(permanentDate.getFullYear() + 10);
      
      const result = await hidePostDuration(accessToken, idea.id, permanentDate.toISOString(), securityKey);
      
      if (result.success) {
        toast.success("Post hidden successfully");
        setShowHideModal(false);
        if (onDelete) {
          onDelete(idea.id);
        }
      } 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);
    }
  };

  const truncatedContent = idea.content.length > 200
    ? idea.content.slice(0, 200) + "..."
    : idea.content;

  const imageAttachments = idea.attachments?.filter(a => a.type === "image") || [];
  const docAttachments = idea.attachments?.filter(a => a.type === "pdf" || a.type === "doc") || [];
  const videoAttachments = idea.attachments?.filter(a => a.type === "video") || [];

  return (
    <>
      <article className="group relative rounded-2xl glass glass-border p-5 transition-all duration-300 hover:border-primary/30">
        {idea.isTrending && (
          <div className="absolute -top-2 -right-2 flex items-center gap-1 rounded-full bg-accent px-3 py-1 text-xs font-bold text-accent-foreground shadow-lg">
            <TrendingUp className="h-3 w-3" />
            Trending
          </div>
        )}

        <div className="flex items-start justify-between gap-4">
          {/* ✅ Make author section clickable */}
          <div 
            onClick={handleAuthorClick}
            className="flex items-center gap-3 cursor-pointer group/author"
          >
            <div className="relative">
              <Avatar className="h-11 w-11 ring-2 ring-border transition-all group-hover/author:ring-primary">
                <AvatarImage src={idea.author.avatar} alt={idea.author.name} />
                <AvatarFallback className="bg-secondary text-foreground font-semibold">
                  {idea.author.name.split(" ").map((n) => n[0]).join("")}
                </AvatarFallback>
              </Avatar>
              {/* ✅ Show country flag image */}
  {idea.author.countryFlag && (
    <div className="absolute -bottom-1 -right-1">
      <img 
        src={idea.author.countryFlag}
        alt="Country flag"
        className="w-4 h-4  object-contain "
      />
    </div>
  )}
  {/* ✅ Fallback to emoji if no image */}
  {!idea.author.countryFlag && idea.author.country && (
    <span className="absolute -bottom-1 -right-1 text-base">{idea.author.country}</span>
  )}
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h4 className="font-semibold text-foreground transition-colors group-hover/author:text-primary">
                  {idea.author.name}
                </h4>
                {idea.aiScore && idea.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">{idea.aiScore}%</span>
                  </div>
                )}
              </div>
              <p className="text-sm text-muted-foreground transition-colors group-hover/author:text-primary/80">
                {idea.author.username}
              </p>
            </div>
          </div>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary transition-colors">
                <MoreHorizontal className="h-5 w-5" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="glass glass-border w-36">
              <DropdownMenuItem onClick={() => setShowShareModal(true)} className="gap-2 cursor-pointer">
                <Share2 className="h-4 w-4" />
                Share
              </DropdownMenuItem>
              
              {!isOwner && (
                <>
                  <DropdownMenuItem 
                    onClick={() => handleReport("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("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("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} className="gap-2 cursor-pointer">
                    <AlertTriangle className="h-4 w-4" />
                    Hide
                  </DropdownMenuItem>
                </>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>

        <div className="mt-4">
          {idea.category && (
            <span className="mb-2 inline-block rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
              {idea.category}
            </span>
          )}
          <p className="text-foreground leading-relaxed">{truncatedContent}</p>

          {idea.content.length > 200 && (
            <Link
              href={`/idea/${idea.id}`}
              className="inline-flex items-center gap-1 mt-2 text-sm font-medium text-primary hover:underline"
            >
              Read more
              <ChevronRight className="h-4 w-4" />
            </Link>
          )}
        </div>

        {imageAttachments.length > 0 && (
          <div className="mt-4">
            <div className={`grid gap-2 ${imageAttachments.length === 1 ? '' : imageAttachments.length === 2 ? 'grid-cols-2' : 'grid-cols-2'}`}>
              {imageAttachments.slice(0, 4).map((img, idx) => (
                <div
                  key={idx}
                  className={`relative rounded-xl overflow-hidden bg-secondary ${imageAttachments.length === 1 ? 'aspect-video' :
                      imageAttachments.length === 3 && idx === 0 ? 'row-span-2 aspect-square' : 'aspect-square'
                    }`}
                >
                  <img
                    src={img.thumbnail || img.url || "/placeholder.svg"}
                    alt={img.name}
                    className="w-full h-full object-fit"
                  />
                  {imageAttachments.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">+{imageAttachments.length - 4}</span>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {videoAttachments.length > 0 && (
          <div className="mt-4">
            <div className="relative rounded-xl overflow-hidden bg-secondary aspect-video">
              <img
                src={videoAttachments[0].thumbnail || "/placeholder.svg"}
                alt={videoAttachments[0].name}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 flex items-center justify-center bg-background/40">
                <div className="flex h-14 w-14 items-center justify-center rounded-full bg-primary/90 text-primary-foreground">
                  <Play className="h-6 w-6 ml-1" />
                </div>
              </div>
              {videoAttachments.length > 1 && (
                <div className="absolute bottom-2 right-2 rounded-full bg-background/80 px-2 py-1 text-xs font-medium">
                  +{videoAttachments.length - 1} videos
                </div>
              )}
            </div>
          </div>
        )}

        {docAttachments.length > 0 && (
          <div className="mt-4 flex flex-wrap gap-2">
            {docAttachments.map((doc, idx) => (
              <div
                key={idx}
                className="flex items-center gap-2 rounded-lg bg-secondary/50 px-3 py-2 text-sm"
              >
                {doc.type === "pdf" ? (
                  <FileText className="h-4 w-4 text-red-400" />
                ) : (
                  <FileText className="h-4 w-4 text-blue-400" />
                )}
                <span className="text-muted-foreground truncate max-w-32">{doc.name}</span>
              </div>
            ))}
          </div>
        )}

        <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}
              className={`flex cursor-pointer items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-all ${
                liked ? " hover:bg-secondary text-primary" : "text-muted-foreground hover:bg-secondary hover:text-foreground"
              }`}
            >
              <Image src={liked ? getFilledLikeIcon() : getUnfilledLikeIcon()} alt="like" width={28} height={28} className="rounded-full" />
              <span>{likes}</span>
            </button>

            <button
              onClick={handleDislike}
              className={`flex cursor-pointer items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-all ${
                disliked ? " hover:bg-secondary text-primary" : "text-muted-foreground hover:bg-secondary hover:text-foreground"
              }`}
            >
              <Image src={disliked ? getFilledDislikeIcon() : getUnfilledDislikeIcon()} alt="dislike" width={28} height={28} className="rounded-full" />
              <span>{dislikes}</span>
            </button>
          </div>

          <div className="flex items-center gap-2">
            <span className="text-xs text-muted-foreground">{idea.timestamp}</span>
            <button
              onClick={handleSave}
              disabled={isSaving}
              className={`flex h-9 w-9 cursor-pointer items-center justify-center rounded-lg transition-all ${
                saved ? " text-accent" : "text-muted-foreground hover:bg-secondary hover:text-foreground"
              } disabled:opacity-50`}
            >
              <Bookmark className={`h-5 w-5 ${saved ? "fill-accent" : ""}`} />
              {isSaving && <Loader2 className="w-3 h-3 animate-spin absolute" />}
            </button>
            <Link
              href={`/idea/${idea.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>
      </article>

      {/* Share Modal */}
      <Dialog open={showShareModal} onOpenChange={setShowShareModal}>
      <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(ideaUrl)}
    </span>
  </div>
  <button onClick={copyToClipboard} 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={() => shareOnSocial("facebook")} 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={() => shareOnSocial("twitter")} 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={() => shareOnSocial("linkedin")} 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={() => shareOnSocial("whatsapp")} 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>

      {/* Hide Post Modal */}
      <Dialog open={showHideModal} onOpenChange={setShowHideModal}>
        <DialogContent className="w-[95vw] sm:w-full 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 {idea.author.name}'s post?</DialogDescription>
          </DialogHeader>
          
          <div className="flex justify-end gap-2 mt-4">
            <button onClick={() => setShowHideModal(false)} className="px-4 py-2 rounded-lg text-sm font-medium text-muted-foreground hover:bg-secondary transition-colors">
              Cancel
            </button>
            <button onClick={submitHide} 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>
    </>
  );
}

// Helper Icons (same as before)
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 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 Check({ className }: { className?: string }) {
  return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"></polyline></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>;
}